file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/5/0xbC249A1D91DbD54CEEfBBdC66e01FC515FA3980c/sources/src/contracts/facilitators/aave/tokens/GhoAToken.sol | Transfers the underlying asset to `target`. It performs a mint of GHO on behalf of the `target` Used by the Pool to transfer assets in borrow(), withdraw() and flashLoan() target The recipient of the underlying amount The amount getting transferred/ | function transferUnderlyingTo(address target, uint256 amount) external virtual override onlyPool {
IGhoToken(_underlyingAsset).mint(target, amount);
}
| 7,037,069 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import "./IlluviumPoolBase.sol";
/**
* @title Illuvium Core Pool
*
* @notice Core pools represent permanent pools like ILV or ILV/ETH Pair pool,
* core pools allow staking for arbitrary periods of time up to 1 year
*
* @dev See IlluviumPoolBase for more details
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
contract IlluviumCorePool is IlluviumPoolBase {
/// @dev Flag indicating pool type, false means "core pool"
bool public constant override isFlashPool = false;
/// @dev Link to deployed IlluviumVault instance
address public vault;
/// @dev Used to calculate vault rewards
/// @dev This value is different from "reward per token" used in locked pool
/// @dev Note: stakes are different in duration and "weight" reflects that
uint256 public vaultRewardsPerWeight;
/// @dev Pool tokens value available in the pool;
/// pool token examples are ILV (ILV core pool) or ILV/ETH pair (LP core pool)
/// @dev For LP core pool this value doesnt' count for ILV tokens received as Vault rewards
/// while for ILV core pool it does count for such tokens as well
uint256 public poolTokenReserve;
/**
* @dev Fired in receiveVaultRewards()
*
* @param _by an address that sent the rewards, always a vault
* @param amount amount of tokens received
*/
event VaultRewardsReceived(address indexed _by, uint256 amount);
/**
* @dev Fired in _processVaultRewards() and dependent functions, like processRewards()
*
* @param _by an address which executed the function
* @param _to an address which received a reward
* @param amount amount of reward received
*/
event VaultRewardsClaimed(address indexed _by, address indexed _to, uint256 amount);
/**
* @dev Fired in setVault()
*
* @param _by an address which executed the function, always a factory owner
*/
event VaultUpdated(address indexed _by, address _fromVal, address _toVal);
/**
* @dev Creates/deploys an instance of the core pool
*
* @param _ilv ILV ERC20 Token IlluviumERC20 address
* @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address
* @param _factory Pool factory IlluviumPoolFactory instance/address
* @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair
* @param _initBlock initial block used to calculate the rewards
* @param _weight number representing a weight of the pool, actual weight fraction
* is calculated as that number divided by the total pools weight and doesn't exceed one
*/
constructor(
address _ilv,
address _silv,
IlluviumPoolFactory _factory,
address _poolToken,
uint64 _initBlock,
uint32 _weight
) IlluviumPoolBase(_ilv, _silv, _factory, _poolToken, _initBlock, _weight) {}
/**
* @notice Calculates current vault rewards value available for address specified
*
* @dev Performs calculations based on current smart contract state only,
* not taking into account any additional time/blocks which might have passed
*
* @param _staker an address to calculate vault rewards value for
* @return pending calculated vault reward value for the given address
*/
function pendingVaultRewards(address _staker) public view returns (uint256 pending) {
User memory user = users[_staker];
return weightToReward(user.totalWeight, vaultRewardsPerWeight) - user.subVaultRewards;
}
/**
* @dev Executed only by the factory owner to Set the vault
*
* @param _vault an address of deployed IlluviumVault instance
*/
function setVault(address _vault) external {
// verify function is executed by the factory owner
require(factory.owner() == msg.sender, "access denied");
// verify input is set
require(_vault != address(0), "zero input");
// emit an event
emit VaultUpdated(msg.sender, vault, _vault);
// update vault address
vault = _vault;
}
/**
* @dev Executed by the vault to transfer vault rewards ILV from the vault
* into the pool
*
* @dev This function is executed only for ILV core pools
*
* @param _rewardsAmount amount of ILV rewards to transfer into the pool
*/
function receiveVaultRewards(uint256 _rewardsAmount) external {
require(msg.sender == vault, "access denied");
// return silently if there is no reward to receive
if (_rewardsAmount == 0) {
return;
}
require(usersLockingWeight > 0, "zero locking weight");
transferIlvFrom(msg.sender, address(this), _rewardsAmount);
vaultRewardsPerWeight += rewardToWeight(_rewardsAmount, usersLockingWeight);
// update `poolTokenReserve` only if this is a ILV Core Pool
if (poolToken == ilv) {
poolTokenReserve += _rewardsAmount;
}
emit VaultRewardsReceived(msg.sender, _rewardsAmount);
}
/**
* @notice Service function to calculate and pay pending vault and yield rewards to the sender
*
* @dev Internally executes similar function `_processRewards` from the parent smart contract
* to calculate and pay yield rewards; adds vault rewards processing
*
* @dev Can be executed by anyone at any time, but has an effect only when
* executed by deposit holder and when at least one block passes from the
* previous reward processing
* @dev Executed internally when "staking as a pool" (`stakeAsPool`)
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*
* @dev _useSILV flag has a context of yield rewards only
*
* @param _useSILV flag indicating whether to mint sILV token as a reward or not;
* when set to true - sILV reward is minted immediately and sent to sender,
* when set to false - new ILV reward deposit gets created if pool is an ILV pool
* (poolToken is ILV token), or new pool deposit gets created together with sILV minted
* when pool is not an ILV pool (poolToken is not an ILV token)
*/
function processRewards(bool _useSILV) external override {
_processRewards(msg.sender, _useSILV, true);
}
/**
* @dev Executed internally by the pool itself (from the parent `IlluviumPoolBase` smart contract)
* as part of yield rewards processing logic (`IlluviumPoolBase._processRewards` function)
* @dev Executed when _useSILV is false and pool is not an ILV pool - see `IlluviumPoolBase._processRewards`
*
* @param _staker an address which stakes (the yield reward)
* @param _amount amount to be staked (yield reward amount)
*/
function stakeAsPool(address _staker, uint256 _amount) external {
require(factory.poolExists(msg.sender), "access denied");
_sync();
User storage user = users[_staker];
if (user.tokenAmount > 0) {
_processRewards(_staker, true, false);
}
uint256 depositWeight = _amount * YEAR_STAKE_WEIGHT_MULTIPLIER;
Deposit memory newDeposit =
Deposit({
tokenAmount: _amount,
lockedFrom: uint64(now256()),
lockedUntil: uint64(now256() + 365 days),
weight: depositWeight,
isYield: true
});
user.tokenAmount += _amount;
user.totalWeight += depositWeight;
user.deposits.push(newDeposit);
usersLockingWeight += depositWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
// update `poolTokenReserve` only if this is a LP Core Pool (stakeAsPool can be executed only for LP pool)
poolTokenReserve += _amount;
}
/**
* @inheritdoc IlluviumPoolBase
*
* @dev Additionally to the parent smart contract, updates vault rewards of the holder,
* and updates (increases) pool token reserve (pool tokens value available in the pool)
*/
function _stake(
address _staker,
uint256 _amount,
uint64 _lockedUntil,
bool _useSILV,
bool _isYield
) internal override {
super._stake(_staker, _amount, _lockedUntil, _useSILV, _isYield);
User storage user = users[_staker];
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
poolTokenReserve += _amount;
}
/**
* @inheritdoc IlluviumPoolBase
*
* @dev Additionally to the parent smart contract, updates vault rewards of the holder,
* and updates (decreases) pool token reserve (pool tokens value available in the pool)
*/
function _unstake(
address _staker,
uint256 _depositId,
uint256 _amount,
bool _useSILV
) internal override {
User storage user = users[_staker];
Deposit memory stakeDeposit = user.deposits[_depositId];
require(stakeDeposit.lockedFrom == 0 || now256() > stakeDeposit.lockedUntil, "deposit not yet unlocked");
poolTokenReserve -= _amount;
super._unstake(_staker, _depositId, _amount, _useSILV);
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
}
/**
* @inheritdoc IlluviumPoolBase
*
* @dev Additionally to the parent smart contract, processes vault rewards of the holder,
* and for ILV pool updates (increases) pool token reserve (pool tokens value available in the pool)
*/
function _processRewards(
address _staker,
bool _useSILV,
bool _withUpdate
) internal override returns (uint256 pendingYield) {
_processVaultRewards(_staker);
pendingYield = super._processRewards(_staker, _useSILV, _withUpdate);
// update `poolTokenReserve` only if this is a ILV Core Pool
if (poolToken == ilv && !_useSILV) {
poolTokenReserve += pendingYield;
}
}
/**
* @dev Used internally to process vault rewards for the staker
*
* @param _staker address of the user (staker) to process rewards for
*/
function _processVaultRewards(address _staker) private {
User storage user = users[_staker];
uint256 pendingVaultClaim = pendingVaultRewards(_staker);
if (pendingVaultClaim == 0) return;
// read ILV token balance of the pool via standard ERC20 interface
uint256 ilvBalance = IERC20(ilv).balanceOf(address(this));
require(ilvBalance >= pendingVaultClaim, "contract ILV balance too low");
// update `poolTokenReserve` only if this is a ILV Core Pool
if (poolToken == ilv) {
// protects against rounding errors
poolTokenReserve -= pendingVaultClaim > poolTokenReserve ? poolTokenReserve : pendingVaultClaim;
}
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
// transfer fails if pool ILV balance is not enough - which is a desired behavior
transferIlv(_staker, pendingVaultClaim);
emit VaultRewardsClaimed(msg.sender, _staker, pendingVaultClaim);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import "../interfaces/IPool.sol";
import "../interfaces/ICorePool.sol";
import "./ReentrancyGuard.sol";
import "./IlluviumPoolFactory.sol";
import "../utils/SafeERC20.sol";
import "../token/EscrowedIlluviumERC20.sol";
/**
* @title Illuvium Pool Base
*
* @notice An abstract contract containing common logic for any pool,
* be it a flash pool (temporary pool like SNX) or a core pool (permanent pool like ILV/ETH or ILV pool)
*
* @dev Deployment and initialization.
* Any pool deployed must be bound to the deployed pool factory (IlluviumPoolFactory)
* Additionally, 3 token instance addresses must be defined on deployment:
* - ILV token address
* - sILV token address, used to mint sILV rewards
* - pool token address, it can be ILV token address, ILV/ETH pair address, and others
*
* @dev Pool weight defines the fraction of the yield current pool receives among the other pools,
* pool factory is responsible for the weight synchronization between the pools.
* @dev The weight is logically 10% for ILV pool and 90% for ILV/ETH pool.
* Since Solidity doesn't support fractions the weight is defined by the division of
* pool weight by total pools weight (sum of all registered pools within the factory)
* @dev For ILV Pool we use 100 as weight and for ILV/ETH pool - 900.
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
abstract contract IlluviumPoolBase is IPool, IlluviumAware, ReentrancyGuard {
/// @dev Data structure representing token holder using a pool
struct User {
// @dev Total staked amount
uint256 tokenAmount;
// @dev Total weight
uint256 totalWeight;
// @dev Auxiliary variable for yield calculation
uint256 subYieldRewards;
// @dev Auxiliary variable for vault rewards calculation
uint256 subVaultRewards;
// @dev An array of holder's deposits
Deposit[] deposits;
}
/// @dev Token holder storage, maps token holder address to their data record
mapping(address => User) public users;
/// @dev Link to sILV ERC20 Token EscrowedIlluviumERC20 instance
address public immutable override silv;
/// @dev Link to the pool factory IlluviumPoolFactory instance
IlluviumPoolFactory public immutable factory;
/// @dev Link to the pool token instance, for example ILV or ILV/ETH pair
address public immutable override poolToken;
/// @dev Pool weight, 100 for ILV pool or 900 for ILV/ETH
uint32 public override weight;
/// @dev Block number of the last yield distribution event
uint64 public override lastYieldDistribution;
/// @dev Used to calculate yield rewards
/// @dev This value is different from "reward per token" used in locked pool
/// @dev Note: stakes are different in duration and "weight" reflects that
uint256 public override yieldRewardsPerWeight;
/// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking
uint256 public override usersLockingWeight;
/**
* @dev Stake weight is proportional to deposit amount and time locked, precisely
* "deposit amount wei multiplied by (fraction of the year locked plus one)"
* @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1],
* weight is stored multiplied by 1e6 constant, as an integer
* @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6
* @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and
* weight is a deposit amount multiplied by 2 * 1e6
*/
uint256 internal constant WEIGHT_MULTIPLIER = 1e6;
/**
* @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one,
* we use simplified calculation and use the following constant instead previos one
*/
uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER;
/**
* @dev Rewards per weight are stored multiplied by 1e12, as integers.
*/
uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e12;
/**
* @dev Fired in _stake() and stake()
*
* @param _by an address which performed an operation, usually token holder
* @param _from token holder address, the tokens will be returned to that address
* @param amount amount of tokens staked
*/
event Staked(address indexed _by, address indexed _from, uint256 amount);
/**
* @dev Fired in _updateStakeLock() and updateStakeLock()
*
* @param _by an address which performed an operation
* @param depositId updated deposit ID
* @param lockedFrom deposit locked from value
* @param lockedUntil updated deposit locked until value
*/
event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil);
/**
* @dev Fired in _unstake() and unstake()
*
* @param _by an address which performed an operation, usually token holder
* @param _to an address which received the unstaked tokens, usually token holder
* @param amount amount of tokens unstaked
*/
event Unstaked(address indexed _by, address indexed _to, uint256 amount);
/**
* @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.)
*
* @param _by an address which performed an operation
* @param yieldRewardsPerWeight updated yield rewards per weight value
* @param lastYieldDistribution usually, current block number
*/
event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution);
/**
* @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.)
*
* @param _by an address which performed an operation
* @param _to an address which claimed the yield reward
* @param sIlv flag indicating if reward was paid (minted) in sILV
* @param amount amount of yield paid
*/
event YieldClaimed(address indexed _by, address indexed _to, bool sIlv, uint256 amount);
/**
* @dev Fired in setWeight()
*
* @param _by an address which performed an operation, always a factory
* @param _fromVal old pool weight value
* @param _toVal new pool weight value
*/
event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal);
/**
* @dev Overridden in sub-contracts to construct the pool
*
* @param _ilv ILV ERC20 Token IlluviumERC20 address
* @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address
* @param _factory Pool factory IlluviumPoolFactory instance/address
* @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair
* @param _initBlock initial block used to calculate the rewards
* note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing
* @param _weight number representing a weight of the pool, actual weight fraction
* is calculated as that number divided by the total pools weight and doesn't exceed one
*/
constructor(
address _ilv,
address _silv,
IlluviumPoolFactory _factory,
address _poolToken,
uint64 _initBlock,
uint32 _weight
) IlluviumAware(_ilv) {
// verify the inputs are set
require(_silv != address(0), "sILV address not set");
require(address(_factory) != address(0), "ILV Pool fct address not set");
require(_poolToken != address(0), "pool token address not set");
require(_initBlock > 0, "init block not set");
require(_weight > 0, "pool weight not set");
// verify sILV instance supplied
require(
EscrowedIlluviumERC20(_silv).TOKEN_UID() ==
0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62,
"unexpected sILV TOKEN_UID"
);
// verify IlluviumPoolFactory instance supplied
require(
_factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7,
"unexpected FACTORY_UID"
);
// save the inputs into internal state variables
silv = _silv;
factory = _factory;
poolToken = _poolToken;
weight = _weight;
// init the dependent internal state variables
lastYieldDistribution = _initBlock;
}
/**
* @notice Calculates current yield rewards value available for address specified
*
* @param _staker an address to calculate yield rewards value for
* @return calculated yield reward value for the given address
*/
function pendingYieldRewards(address _staker) external view override returns (uint256) {
// `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight`
uint256 newYieldRewardsPerWeight;
// if smart contract state was not updated recently, `yieldRewardsPerWeight` value
// is outdated and we need to recalculate it in order to calculate pending rewards correctly
if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) {
uint256 endBlock = factory.endBlock();
uint256 multiplier =
blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution;
uint256 ilvRewards = (multiplier * weight * factory.ilvPerBlock()) / factory.totalWeight();
// recalculated value for `yieldRewardsPerWeight`
newYieldRewardsPerWeight = rewardToWeight(ilvRewards, usersLockingWeight) + yieldRewardsPerWeight;
} else {
// if smart contract state is up to date, we don't recalculate
newYieldRewardsPerWeight = yieldRewardsPerWeight;
}
// based on the rewards per weight value, calculate pending rewards;
User memory user = users[_staker];
uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards;
return pending;
}
/**
* @notice Returns total staked token balance for the given address
*
* @param _user an address to query balance for
* @return total staked token balance
*/
function balanceOf(address _user) external view override returns (uint256) {
// read specified user token amount and return
return users[_user].tokenAmount;
}
/**
* @notice Returns information on the given deposit for the given address
*
* @dev See getDepositsLength
*
* @param _user an address to query deposit for
* @param _depositId zero-indexed deposit ID for the address specified
* @return deposit info as Deposit structure
*/
function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) {
// read deposit at specified index and return
return users[_user].deposits[_depositId];
}
/**
* @notice Returns number of deposits for the given address. Allows iteration over deposits.
*
* @dev See getDeposit
*
* @param _user an address to query deposit length for
* @return number of deposits for the given address
*/
function getDepositsLength(address _user) external view override returns (uint256) {
// read deposits array length and return
return users[_user].deposits.length;
}
/**
* @notice Stakes specified amount of tokens for the specified amount of time,
* and pays pending yield rewards if any
*
* @dev Requires amount to stake to be greater than zero
*
* @param _amount amount of tokens to stake
* @param _lockUntil stake period as unix timestamp; zero means no locking
* @param _useSILV a flag indicating if previous reward to be paid as sILV
*/
function stake(
uint256 _amount,
uint64 _lockUntil,
bool _useSILV
) external override {
// delegate call to an internal function
_stake(msg.sender, _amount, _lockUntil, _useSILV, false);
}
/**
* @notice Unstakes specified amount of tokens, and pays pending yield rewards if any
*
* @dev Requires amount to unstake to be greater than zero
*
* @param _depositId deposit ID to unstake from, zero-indexed
* @param _amount amount of tokens to unstake
* @param _useSILV a flag indicating if reward to be paid as sILV
*/
function unstake(
uint256 _depositId,
uint256 _amount,
bool _useSILV
) external override {
// delegate call to an internal function
_unstake(msg.sender, _depositId, _amount, _useSILV);
}
/**
* @notice Extends locking period for a given deposit
*
* @dev Requires new lockedUntil value to be:
* higher than the current one, and
* in the future, but
* no more than 1 year in the future
*
* @param depositId updated deposit ID
* @param lockedUntil updated deposit locked until value
* @param useSILV used for _processRewards check if it should use ILV or sILV
*/
function updateStakeLock(
uint256 depositId,
uint64 lockedUntil,
bool useSILV
) external {
// sync and call processRewards
_sync();
_processRewards(msg.sender, useSILV, false);
// delegate call to an internal function
_updateStakeLock(msg.sender, depositId, lockedUntil);
}
/**
* @notice Service function to synchronize pool state with current time
*
* @dev Can be executed by anyone at any time, but has an effect only when
* at least one block passes between synchronizations
* @dev Executed internally when staking, unstaking, processing rewards in order
* for calculations to be correct and to reflect state progress of the contract
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*/
function sync() external override {
// delegate call to an internal function
_sync();
}
/**
* @notice Service function to calculate and pay pending yield rewards to the sender
*
* @dev Can be executed by anyone at any time, but has an effect only when
* executed by deposit holder and when at least one block passes from the
* previous reward processing
* @dev Executed internally when staking and unstaking, executes sync() under the hood
* before making further calculations and payouts
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*
* @param _useSILV flag indicating whether to mint sILV token as a reward or not;
* when set to true - sILV reward is minted immediately and sent to sender,
* when set to false - new ILV reward deposit gets created if pool is an ILV pool
* (poolToken is ILV token), or new pool deposit gets created together with sILV minted
* when pool is not an ILV pool (poolToken is not an ILV token)
*/
function processRewards(bool _useSILV) external virtual override {
// delegate call to an internal function
_processRewards(msg.sender, _useSILV, true);
}
/**
* @dev Executed by the factory to modify pool weight; the factory is expected
* to keep track of the total pools weight when updating
*
* @dev Set weight to zero to disable the pool
*
* @param _weight new weight to set for the pool
*/
function setWeight(uint32 _weight) external override {
// verify function is executed by the factory
require(msg.sender == address(factory), "access denied");
// emit an event logging old and new weight values
emit PoolWeightUpdated(msg.sender, weight, _weight);
// set the new weight value
weight = _weight;
}
/**
* @dev Similar to public pendingYieldRewards, but performs calculations based on
* current smart contract state only, not taking into account any additional
* time/blocks which might have passed
*
* @param _staker an address to calculate yield rewards value for
* @return pending calculated yield reward value for the given address
*/
function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) {
// read user data structure into memory
User memory user = users[_staker];
// and perform the calculation using the values read
return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards;
}
/**
* @dev Used internally, mostly by children implementations, see stake()
*
* @param _staker an address which stakes tokens and which will receive them back
* @param _amount amount of tokens to stake
* @param _lockUntil stake period as unix timestamp; zero means no locking
* @param _useSILV a flag indicating if previous reward to be paid as sILV
* @param _isYield a flag indicating if that stake is created to store yield reward
* from the previously unstaked stake
*/
function _stake(
address _staker,
uint256 _amount,
uint64 _lockUntil,
bool _useSILV,
bool _isYield
) internal virtual {
// validate the inputs
require(_amount > 0, "zero amount");
require(
_lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days),
"invalid lock interval"
);
// update smart contract state
_sync();
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// process current pending rewards if any
if (user.tokenAmount > 0) {
_processRewards(_staker, _useSILV, false);
}
// in most of the cases added amount `addedAmount` is simply `_amount`
// however for deflationary tokens this can be different
// read the current balance
uint256 previousBalance = IERC20(poolToken).balanceOf(address(this));
// transfer `_amount`; note: some tokens may get burnt here
transferPoolTokenFrom(address(msg.sender), address(this), _amount);
// read new balance, usually this is just the difference `previousBalance - _amount`
uint256 newBalance = IERC20(poolToken).balanceOf(address(this));
// calculate real amount taking into account deflation
uint256 addedAmount = newBalance - previousBalance;
// set the `lockFrom` and `lockUntil` taking into account that
// zero value for `_lockUntil` means "no locking" and leads to zero values
// for both `lockFrom` and `lockUntil`
uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0;
uint64 lockUntil = _lockUntil;
// stake weight formula rewards for locking
uint256 stakeWeight =
(((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount;
// makes sure stakeWeight is valid
assert(stakeWeight > 0);
// create and save the deposit (append it to deposits array)
Deposit memory deposit =
Deposit({
tokenAmount: addedAmount,
weight: stakeWeight,
lockedFrom: lockFrom,
lockedUntil: lockUntil,
isYield: _isYield
});
// deposit ID is an index of the deposit in `deposits` array
user.deposits.push(deposit);
// update user record
user.tokenAmount += addedAmount;
user.totalWeight += stakeWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
// update global variable
usersLockingWeight += stakeWeight;
// emit an event
emit Staked(msg.sender, _staker, _amount);
}
/**
* @dev Used internally, mostly by children implementations, see unstake()
*
* @param _staker an address which unstakes tokens (which previously staked them)
* @param _depositId deposit ID to unstake from, zero-indexed
* @param _amount amount of tokens to unstake
* @param _useSILV a flag indicating if reward to be paid as sILV
*/
function _unstake(
address _staker,
uint256 _depositId,
uint256 _amount,
bool _useSILV
) internal virtual {
// verify an amount is set
require(_amount > 0, "zero amount");
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// get a link to the corresponding deposit, we may write to it later
Deposit storage stakeDeposit = user.deposits[_depositId];
// deposit structure may get deleted, so we save isYield flag to be able to use it
bool isYield = stakeDeposit.isYield;
// verify available balance
// if staker address ot deposit doesn't exist this check will fail as well
require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake");
// update smart contract state
_sync();
// and process current pending rewards if any
_processRewards(_staker, _useSILV, false);
// recalculate deposit weight
uint256 previousWeight = stakeDeposit.weight;
uint256 newWeight =
(((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) /
365 days +
WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount);
// update the deposit, or delete it if its depleted
if (stakeDeposit.tokenAmount - _amount == 0) {
delete user.deposits[_depositId];
} else {
stakeDeposit.tokenAmount -= _amount;
stakeDeposit.weight = newWeight;
}
// update user record
user.tokenAmount -= _amount;
user.totalWeight = user.totalWeight - previousWeight + newWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
// update global variable
usersLockingWeight = usersLockingWeight - previousWeight + newWeight;
// if the deposit was created by the pool itself as a yield reward
if (isYield) {
// mint the yield via the factory
factory.mintYieldTo(msg.sender, _amount);
} else {
// otherwise just return tokens back to holder
transferPoolToken(msg.sender, _amount);
}
// emit an event
emit Unstaked(msg.sender, _staker, _amount);
}
/**
* @dev Used internally, mostly by children implementations, see sync()
*
* @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`),
* updates factory state via `updateILVPerBlock`
*/
function _sync() internal virtual {
// update ILV per block value in factory if required
if (factory.shouldUpdateRatio()) {
factory.updateILVPerBlock();
}
// check bound conditions and if these are not met -
// exit silently, without emitting an event
uint256 endBlock = factory.endBlock();
if (lastYieldDistribution >= endBlock) {
return;
}
if (blockNumber() <= lastYieldDistribution) {
return;
}
// if locking weight is zero - update only `lastYieldDistribution` and exit
if (usersLockingWeight == 0) {
lastYieldDistribution = uint64(blockNumber());
return;
}
// to calculate the reward we need to know how many blocks passed, and reward per block
uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber();
uint256 blocksPassed = currentBlock - lastYieldDistribution;
uint256 ilvPerBlock = factory.ilvPerBlock();
// calculate the reward
uint256 ilvReward = (blocksPassed * ilvPerBlock * weight) / factory.totalWeight();
// update rewards per weight and `lastYieldDistribution`
yieldRewardsPerWeight += rewardToWeight(ilvReward, usersLockingWeight);
lastYieldDistribution = uint64(currentBlock);
// emit an event
emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution);
}
/**
* @dev Used internally, mostly by children implementations, see processRewards()
*
* @param _staker an address which receives the reward (which has staked some tokens earlier)
* @param _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards()
* @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false
* @return pendingYield the rewards calculated and optionally re-staked
*/
function _processRewards(
address _staker,
bool _useSILV,
bool _withUpdate
) internal virtual returns (uint256 pendingYield) {
// update smart contract state if required
if (_withUpdate) {
_sync();
}
// calculate pending yield rewards, this value will be returned
pendingYield = _pendingYieldRewards(_staker);
// if pending yield is zero - just return silently
if (pendingYield == 0) return 0;
// get link to a user data structure, we will write into it later
User storage user = users[_staker];
// if sILV is requested
if (_useSILV) {
// - mint sILV
mintSIlv(_staker, pendingYield);
} else if (poolToken == ilv) {
// calculate pending yield weight,
// 2e6 is the bonus weight when staking for 1 year
uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER;
// if the pool is ILV Pool - create new ILV deposit
// and save it - push it into deposits array
Deposit memory newDeposit =
Deposit({
tokenAmount: pendingYield,
lockedFrom: uint64(now256()),
lockedUntil: uint64(now256() + 365 days), // staking yield for 1 year
weight: depositWeight,
isYield: true
});
user.deposits.push(newDeposit);
// update user record
user.tokenAmount += pendingYield;
user.totalWeight += depositWeight;
// update global variable
usersLockingWeight += depositWeight;
} else {
// for other pools - stake as pool
address ilvPool = factory.getPoolAddress(ilv);
ICorePool(ilvPool).stakeAsPool(_staker, pendingYield);
}
// update users's record for `subYieldRewards` if requested
if (_withUpdate) {
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
}
// emit an event
emit YieldClaimed(msg.sender, _staker, _useSILV, pendingYield);
}
/**
* @dev See updateStakeLock()
*
* @param _staker an address to update stake lock
* @param _depositId updated deposit ID
* @param _lockedUntil updated deposit locked until value
*/
function _updateStakeLock(
address _staker,
uint256 _depositId,
uint64 _lockedUntil
) internal {
// validate the input time
require(_lockedUntil > now256(), "lock should be in the future");
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// get a link to the corresponding deposit, we may write to it later
Deposit storage stakeDeposit = user.deposits[_depositId];
// validate the input against deposit structure
require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock");
// verify locked from and locked until values
if (stakeDeposit.lockedFrom == 0) {
require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days");
stakeDeposit.lockedFrom = uint64(now256());
} else {
require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days");
}
// update locked until value, calculate new weight
stakeDeposit.lockedUntil = _lockedUntil;
uint256 newWeight =
(((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) /
365 days +
WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount;
// save previous weight
uint256 previousWeight = stakeDeposit.weight;
// update weight
stakeDeposit.weight = newWeight;
// update user total weight and global locking weight
user.totalWeight = user.totalWeight - previousWeight + newWeight;
usersLockingWeight = usersLockingWeight - previousWeight + newWeight;
// emit an event
emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil);
}
/**
* @dev Converts stake weight (not to be mixed with the pool weight) to
* ILV reward value, applying the 10^12 division on weight
*
* @param _weight stake weight
* @param rewardPerWeight ILV reward per weight
* @return reward value normalized to 10^12
*/
function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) {
// apply the formula and return
return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER;
}
/**
* @dev Converts reward ILV value to stake weight (not to be mixed with the pool weight),
* applying the 10^12 multiplication on the reward
* - OR -
* @dev Converts reward ILV value to reward/weight if stake weight is supplied as second
* function parameter instead of reward/weight
*
* @param reward yield reward
* @param rewardPerWeight reward/weight (or stake weight)
* @return stake weight (or reward/weight)
*/
function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) {
// apply the reverse formula and return
return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight;
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override block number in helper test smart contracts
*
* @return `block.number` in mainnet, custom values in testnets (if overridden)
*/
function blockNumber() public view virtual returns (uint256) {
// return current block number
return block.number;
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override time in helper test smart contracts
*
* @return `block.timestamp` in mainnet, custom values in testnets (if overridden)
*/
function now256() public view virtual returns (uint256) {
// return current block timestamp
return block.timestamp;
}
/**
* @dev Executes EscrowedIlluviumERC20.mint(_to, _values)
* on the bound EscrowedIlluviumERC20 instance
*
* @dev Reentrancy safe due to the EscrowedIlluviumERC20 design
*/
function mintSIlv(address _to, uint256 _value) private {
// just delegate call to the target
EscrowedIlluviumERC20(silv).mint(_to, _value);
}
/**
* @dev Executes SafeERC20.safeTransfer on a pool token
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*/
function transferPoolToken(address _to, uint256 _value) internal nonReentrant {
// just delegate call to the target
SafeERC20.safeTransfer(IERC20(poolToken), _to, _value);
}
/**
* @dev Executes SafeERC20.safeTransferFrom on a pool token
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*/
function transferPoolTokenFrom(
address _from,
address _to,
uint256 _value
) internal nonReentrant {
// just delegate call to the target
SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import "./ILinkedToILV.sol";
/**
* @title Illuvium Pool
*
* @notice An abstraction representing a pool, see IlluviumPoolBase for details
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
interface IPool is ILinkedToILV {
/**
* @dev Deposit is a key data structure used in staking,
* it represents a unit of stake with its amount, weight and term (time interval)
*/
struct Deposit {
// @dev token amount staked
uint256 tokenAmount;
// @dev stake weight
uint256 weight;
// @dev locking period - from
uint64 lockedFrom;
// @dev locking period - until
uint64 lockedUntil;
// @dev indicates if the stake was created as a yield reward
bool isYield;
}
// for the rest of the functions see Soldoc in IlluviumPoolBase
function silv() external view returns (address);
function poolToken() external view returns (address);
function isFlashPool() external view returns (bool);
function weight() external view returns (uint32);
function lastYieldDistribution() external view returns (uint64);
function yieldRewardsPerWeight() external view returns (uint256);
function usersLockingWeight() external view returns (uint256);
function pendingYieldRewards(address _user) external view returns (uint256);
function balanceOf(address _user) external view returns (uint256);
function getDeposit(address _user, uint256 _depositId) external view returns (Deposit memory);
function getDepositsLength(address _user) external view returns (uint256);
function stake(
uint256 _amount,
uint64 _lockedUntil,
bool useSILV
) external;
function unstake(
uint256 _depositId,
uint256 _amount,
bool useSILV
) external;
function sync() external;
function processRewards(bool useSILV) external;
function setWeight(uint32 _weight) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import "./IPool.sol";
interface ICorePool is IPool {
function vaultRewardsPerToken() external view returns (uint256);
function poolTokenReserve() external view returns (uint256);
function stakeAsPool(address _staker, uint256 _amount) external;
function receiveVaultRewards(uint256 _amount) external;
}
// https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/security/ReentrancyGuard.sol
// #24a0bc23cfe3fbc76f8f2510b78af1e948ae6651
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/**
* @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.1;
import "../interfaces/IPool.sol";
import "./IlluviumAware.sol";
import "./IlluviumCorePool.sol";
import "../token/EscrowedIlluviumERC20.sol";
import "../utils/Ownable.sol";
/**
* @title Illuvium Pool Factory
*
* @notice ILV Pool Factory manages Illuvium Yield farming pools, provides a single
* public interface to access the pools, provides an interface for the pools
* to mint yield rewards, access pool-related info, update weights, etc.
*
* @notice The factory is authorized (via its owner) to register new pools, change weights
* of the existing pools, removing the pools (by changing their weights to zero)
*
* @dev The factory requires ROLE_TOKEN_CREATOR permission on the ILV token to mint yield
* (see `mintYieldTo` function)
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
contract IlluviumPoolFactory is Ownable, IlluviumAware {
/**
* @dev Smart contract unique identifier, a random number
* @dev Should be regenerated each time smart contact source code is changed
* and changes smart contract itself is to be redeployed
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant FACTORY_UID = 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7;
/// @dev Auxiliary data structure used only in getPoolData() view function
struct PoolData {
// @dev pool token address (like ILV)
address poolToken;
// @dev pool address (like deployed core pool instance)
address poolAddress;
// @dev pool weight (200 for ILV pools, 800 for ILV/ETH pools - set during deployment)
uint32 weight;
// @dev flash pool flag
bool isFlashPool;
}
/**
* @dev ILV/block determines yield farming reward base
* used by the yield pools controlled by the factory
*/
uint192 public ilvPerBlock;
/**
* @dev The yield is distributed proportionally to pool weights;
* total weight is here to help in determining the proportion
*/
uint32 public totalWeight;
/**
* @dev ILV/block decreases by 3% every blocks/update (set to 91252 blocks during deployment);
* an update is triggered by executing `updateILVPerBlock` public function
*/
uint32 public immutable blocksPerUpdate;
/**
* @dev End block is the last block when ILV/block can be decreased;
* it is implied that yield farming stops after that block
*/
uint32 public endBlock;
/**
* @dev Each time the ILV/block ratio gets updated, the block number
* when the operation has occurred gets recorded into `lastRatioUpdate`
* @dev This block number is then used to check if blocks/update `blocksPerUpdate`
* has passed when decreasing yield reward by 3%
*/
uint32 public lastRatioUpdate;
/// @dev sILV token address is used to create ILV core pool(s)
address public immutable silv;
/// @dev Maps pool token address (like ILV) -> pool address (like core pool instance)
mapping(address => address) public pools;
/// @dev Keeps track of registered pool addresses, maps pool address -> exists flag
mapping(address => bool) public poolExists;
/**
* @dev Fired in createPool() and registerPool()
*
* @param _by an address which executed an action
* @param poolToken pool token address (like ILV)
* @param poolAddress deployed pool instance address
* @param weight pool weight
* @param isFlashPool flag indicating if pool is a flash pool
*/
event PoolRegistered(
address indexed _by,
address indexed poolToken,
address indexed poolAddress,
uint64 weight,
bool isFlashPool
);
/**
* @dev Fired in changePoolWeight()
*
* @param _by an address which executed an action
* @param poolAddress deployed pool instance address
* @param weight new pool weight
*/
event WeightUpdated(address indexed _by, address indexed poolAddress, uint32 weight);
/**
* @dev Fired in updateILVPerBlock()
*
* @param _by an address which executed an action
* @param newIlvPerBlock new ILV/block value
*/
event IlvRatioUpdated(address indexed _by, uint256 newIlvPerBlock);
/**
* @dev Creates/deploys a factory instance
*
* @param _ilv ILV ERC20 token address
* @param _silv sILV ERC20 token address
* @param _ilvPerBlock initial ILV/block value for rewards
* @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks
* @param _initBlock block number to measure _blocksPerUpdate from
* @param _endBlock block number when farming stops and rewards cannot be updated anymore
*/
constructor(
address _ilv,
address _silv,
uint192 _ilvPerBlock,
uint32 _blocksPerUpdate,
uint32 _initBlock,
uint32 _endBlock
) IlluviumAware(_ilv) {
// verify the inputs are set
require(_silv != address(0), "sILV address not set");
require(_ilvPerBlock > 0, "ILV/block not set");
require(_blocksPerUpdate > 0, "blocks/update not set");
require(_initBlock > 0, "init block not set");
require(_endBlock > _initBlock, "invalid end block: must be greater than init block");
// verify sILV instance supplied
require(
EscrowedIlluviumERC20(_silv).TOKEN_UID() ==
0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62,
"unexpected sILV TOKEN_UID"
);
// save the inputs into internal state variables
silv = _silv;
ilvPerBlock = _ilvPerBlock;
blocksPerUpdate = _blocksPerUpdate;
lastRatioUpdate = _initBlock;
endBlock = _endBlock;
}
/**
* @notice Given a pool token retrieves corresponding pool address
*
* @dev A shortcut for `pools` mapping
*
* @param poolToken pool token address (like ILV) to query pool address for
* @return pool address for the token specified
*/
function getPoolAddress(address poolToken) external view returns (address) {
// read the mapping and return
return pools[poolToken];
}
/**
* @notice Reads pool information for the pool defined by its pool token address,
* designed to simplify integration with the front ends
*
* @param _poolToken pool token address to query pool information for
* @return pool information packed in a PoolData struct
*/
function getPoolData(address _poolToken) public view returns (PoolData memory) {
// get the pool address from the mapping
address poolAddr = pools[_poolToken];
// throw if there is no pool registered for the token specified
require(poolAddr != address(0), "pool not found");
// read pool information from the pool smart contract
// via the pool interface (IPool)
address poolToken = IPool(poolAddr).poolToken();
bool isFlashPool = IPool(poolAddr).isFlashPool();
uint32 weight = IPool(poolAddr).weight();
// create the in-memory structure and return it
return PoolData({ poolToken: poolToken, poolAddress: poolAddr, weight: weight, isFlashPool: isFlashPool });
}
/**
* @dev Verifies if `blocksPerUpdate` has passed since last ILV/block
* ratio update and if ILV/block reward can be decreased by 3%
*
* @return true if enough time has passed and `updateILVPerBlock` can be executed
*/
function shouldUpdateRatio() public view returns (bool) {
// if yield farming period has ended
if (blockNumber() > endBlock) {
// ILV/block reward cannot be updated anymore
return false;
}
// check if blocks/update (91252 blocks) have passed since last update
return blockNumber() >= lastRatioUpdate + blocksPerUpdate;
}
/**
* @dev Creates a core pool (IlluviumCorePool) and registers it within the factory
*
* @dev Can be executed by the pool factory owner only
*
* @param poolToken pool token address (like ILV, or ILV/ETH pair)
* @param initBlock init block to be used for the pool created
* @param weight weight of the pool to be created
*/
function createPool(
address poolToken,
uint64 initBlock,
uint32 weight
) external virtual onlyOwner {
// create/deploy new core pool instance
IPool pool = new IlluviumCorePool(ilv, silv, this, poolToken, initBlock, weight);
// register it within a factory
registerPool(address(pool));
}
/**
* @dev Registers an already deployed pool instance within the factory
*
* @dev Can be executed by the pool factory owner only
*
* @param poolAddr address of the already deployed pool instance
*/
function registerPool(address poolAddr) public onlyOwner {
// read pool information from the pool smart contract
// via the pool interface (IPool)
address poolToken = IPool(poolAddr).poolToken();
bool isFlashPool = IPool(poolAddr).isFlashPool();
uint32 weight = IPool(poolAddr).weight();
// ensure that the pool is not already registered within the factory
require(pools[poolToken] == address(0), "this pool is already registered");
// create pool structure, register it within the factory
pools[poolToken] = poolAddr;
poolExists[poolAddr] = true;
// update total pool weight of the factory
totalWeight += weight;
// emit an event
emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool);
}
/**
* @notice Decreases ILV/block reward by 3%, can be executed
* no more than once per `blocksPerUpdate` blocks
*/
function updateILVPerBlock() external {
// checks if ratio can be updated i.e. if blocks/update (91252 blocks) have passed
require(shouldUpdateRatio(), "too frequent");
// decreases ILV/block reward by 3%
ilvPerBlock = (ilvPerBlock * 97) / 100;
// set current block as the last ratio update block
lastRatioUpdate = uint32(blockNumber());
// emit an event
emit IlvRatioUpdated(msg.sender, ilvPerBlock);
}
/**
* @dev Mints ILV tokens; executed by ILV Pool only
*
* @dev Requires factory to have ROLE_TOKEN_CREATOR permission
* on the ILV ERC20 token instance
*
* @param _to an address to mint tokens to
* @param _amount amount of ILV tokens to mint
*/
function mintYieldTo(address _to, uint256 _amount) external {
// verify that sender is a pool registered withing the factory
require(poolExists[msg.sender], "access denied");
// mint ILV tokens as required
mintIlv(_to, _amount);
}
/**
* @dev Changes the weight of the pool;
* executed by the pool itself or by the factory owner
*
* @param poolAddr address of the pool to change weight for
* @param weight new weight value to set to
*/
function changePoolWeight(address poolAddr, uint32 weight) external {
// verify function is executed either by factory owner or by the pool itself
require(msg.sender == owner() || poolExists[msg.sender]);
// recalculate total weight
totalWeight = totalWeight + weight - IPool(poolAddr).weight();
// set the new pool weight
IPool(poolAddr).setWeight(weight);
// emit an event
emit WeightUpdated(msg.sender, poolAddr, weight);
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override block number in helper test smart contracts
*
* @return `block.number` in mainnet, custom values in testnets (if overridden)
*/
function blockNumber() public view virtual returns (uint256) {
// return current block number
return block.number;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import "../interfaces/IERC20.sol";
import "./Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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 {
uint256 newAllowance = token.allowance(address(this), spender) - 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.1;
import "../utils/ERC20.sol";
import "../utils/AccessControl.sol";
contract EscrowedIlluviumERC20 is ERC20("Escrowed Illuvium", "sILV"), AccessControl {
/**
* @dev Smart contract unique identifier, a random number
* @dev Should be regenerated each time smart contact source code is changed
* and changes smart contract itself is to be redeployed
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant TOKEN_UID = 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62;
/**
* @notice Must be called by ROLE_TOKEN_CREATOR addresses.
*
* @param recipient address to receive the tokens.
* @param amount number of tokens to be minted.
*/
function mint(address recipient, uint256 amount) external {
require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)");
_mint(recipient, amount);
}
/**
* @param amount number of tokens to be burned.
*/
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/**
* @title Linked to ILV Marker Interface
*
* @notice Marks smart contracts which are linked to IlluviumERC20 token instance upon construction,
* all these smart contracts share a common ilv() address getter
*
* @notice Implementing smart contracts MUST verify that they get linked to real IlluviumERC20 instance
* and that ilv() getter returns this very same instance address
*
* @author Basil Gorin
*/
interface ILinkedToILV {
/**
* @notice Getter for a verified IlluviumERC20 instance address
*
* @return IlluviumERC20 token instance address smart contract is linked to
*/
function ilv() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import "../token/IlluviumERC20.sol";
import "../interfaces/ILinkedToILV.sol";
/**
* @title Illuvium Aware
*
* @notice Helper smart contract to be inherited by other smart contracts requiring to
* be linked to verified IlluviumERC20 instance and performing some basic tasks on it
*
* @author Basil Gorin
*/
abstract contract IlluviumAware is ILinkedToILV {
/// @dev Link to ILV ERC20 Token IlluviumERC20 instance
address public immutable override ilv;
/**
* @dev Creates IlluviumAware instance, requiring to supply deployed IlluviumERC20 instance address
*
* @param _ilv deployed IlluviumERC20 instance address
*/
constructor(address _ilv) {
// verify ILV address is set and is correct
require(_ilv != address(0), "ILV address not set");
require(IlluviumERC20(_ilv).TOKEN_UID() == 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c, "unexpected TOKEN_UID");
// write ILV address
ilv = _ilv;
}
/**
* @dev Executes IlluviumERC20.safeTransferFrom(address(this), _to, _value, "")
* on the bound IlluviumERC20 instance
*
* @dev Reentrancy safe due to the IlluviumERC20 design
*/
function transferIlv(address _to, uint256 _value) internal {
// just delegate call to the target
transferIlvFrom(address(this), _to, _value);
}
/**
* @dev Executes IlluviumERC20.transferFrom(_from, _to, _value)
* on the bound IlluviumERC20 instance
*
* @dev Reentrancy safe due to the IlluviumERC20 design
*/
function transferIlvFrom(address _from, address _to, uint256 _value) internal {
// just delegate call to the target
IlluviumERC20(ilv).transferFrom(_from, _to, _value);
}
/**
* @dev Executes IlluviumERC20.mint(_to, _values)
* on the bound IlluviumERC20 instance
*
* @dev Reentrancy safe due to the IlluviumERC20 design
*/
function mintIlv(address _to, uint256 _value) internal {
// just delegate call to the target
IlluviumERC20(ilv).mint(_to, _value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = msg.sender;
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import "../utils/AddressUtils.sol";
import "../utils/AccessControl.sol";
import "./ERC20Receiver.sol";
/**
* @title Illuvium (ILV) ERC20 token
*
* @notice Illuvium is a core ERC20 token powering the game.
* It serves as an in-game currency, is tradable on exchanges,
* it powers up the governance protocol (Illuvium DAO) and participates in Yield Farming.
*
* @dev Token Summary:
* - Symbol: ILV
* - Name: Illuvium
* - Decimals: 18
* - Initial token supply: 7,000,000 ILV
* - Maximum final token supply: 10,000,000 ILV
* - Up to 3,000,000 ILV may get minted in 3 years period via yield farming
* - Mintable: total supply may increase
* - Burnable: total supply may decrease
*
* @dev Token balances and total supply are effectively 192 bits long, meaning that maximum
* possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens)
*
* @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe.
* Additionally, Solidity 0.8.1 enforces overflow/underflow safety.
*
* @dev ERC20: reviewed according to https://eips.ethereum.org/EIPS/eip-20
*
* @dev ERC20: contract has passed OpenZeppelin ERC20 tests,
* see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js
* see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js
* see adopted copies of these tests in the `test` folder
*
* @dev ERC223/ERC777: not supported;
* send tokens via `safeTransferFrom` and implement `ERC20Receiver.onERC20Received` on the receiver instead
*
* @dev Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) - resolved
* Related events and functions are marked with "ISBN:978-1-7281-3027-9" tag:
* - event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value)
* - event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value)
* - function increaseAllowance(address _spender, uint256 _value) public returns (bool)
* - function decreaseAllowance(address _spender, uint256 _value) public returns (bool)
* See: https://ieeexplore.ieee.org/document/8802438
* See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @author Basil Gorin
*/
contract IlluviumERC20 is AccessControl {
/**
* @dev Smart contract unique identifier, a random number
* @dev Should be regenerated each time smart contact source code is changed
* and changes smart contract itself is to be redeployed
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant TOKEN_UID = 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c;
/**
* @notice Name of the token: Illuvium
*
* @notice ERC20 name of the token (long name)
*
* @dev ERC20 `function name() public view returns (string)`
*
* @dev Field is declared public: getter name() is created when compiled,
* it returns the name of the token.
*/
string public constant name = "Illuvium";
/**
* @notice Symbol of the token: ILV
*
* @notice ERC20 symbol of that token (short name)
*
* @dev ERC20 `function symbol() public view returns (string)`
*
* @dev Field is declared public: getter symbol() is created when compiled,
* it returns the symbol of the token
*/
string public constant symbol = "ILV";
/**
* @notice Decimals of the token: 18
*
* @dev ERC20 `function decimals() public view returns (uint8)`
*
* @dev Field is declared public: getter decimals() is created when compiled,
* it returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should
* be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`).
*
* @dev NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including balanceOf() and transfer().
*/
uint8 public constant decimals = 18;
/**
* @notice Total supply of the token: initially 7,000,000,
* with the potential to grow up to 10,000,000 during yield farming period (3 years)
*
* @dev ERC20 `function totalSupply() public view returns (uint256)`
*
* @dev Field is declared public: getter totalSupply() is created when compiled,
* it returns the amount of tokens in existence.
*/
uint256 public totalSupply; // is set to 7 million * 10^18 in the constructor
/**
* @dev A record of all the token balances
* @dev This mapping keeps record of all token owners:
* owner => balance
*/
mapping(address => uint256) public tokenBalances;
/**
* @notice A record of each account's voting delegate
*
* @dev Auxiliary data structure used to sum up an account's voting power
*
* @dev This mapping keeps record of all voting power delegations:
* voting delegator (token owner) => voting delegate
*/
mapping(address => address) public votingDelegates;
/**
* @notice A voting power record binds voting power of a delegate to a particular
* block when the voting power delegation change happened
*/
struct VotingPowerRecord {
/*
* @dev block.number when delegation has changed; starting from
* that block voting power value is in effect
*/
uint64 blockNumber;
/*
* @dev cumulative voting power a delegate has obtained starting
* from the block stored in blockNumber
*/
uint192 votingPower;
}
/**
* @notice A record of each account's voting power
*
* @dev Primarily data structure to store voting power for each account.
* Voting power sums up from the account's token balance and delegated
* balances.
*
* @dev Stores current value and entire history of its changes.
* The changes are stored as an array of checkpoints.
* Checkpoint is an auxiliary data structure containing voting
* power (number of votes) and block number when the checkpoint is saved
*
* @dev Maps voting delegate => voting power record
*/
mapping(address => VotingPowerRecord[]) public votingPowerHistory;
/**
* @dev A record of nonces for signing/validating signatures in `delegateWithSig`
* for every delegate, increases after successful validation
*
* @dev Maps delegate address => delegate nonce
*/
mapping(address => uint256) public nonces;
/**
* @notice A record of all the allowances to spend tokens on behalf
* @dev Maps token owner address to an address approved to spend
* some tokens on behalf, maps approved address to that amount
* @dev owner => spender => value
*/
mapping(address => mapping(address => uint256)) public transferAllowances;
/**
* @notice Enables ERC20 transfers of the tokens
* (transfer by the token owner himself)
* @dev Feature FEATURE_TRANSFERS must be enabled in order for
* `transfer()` function to succeed
*/
uint32 public constant FEATURE_TRANSFERS = 0x0000_0001;
/**
* @notice Enables ERC20 transfers on behalf
* (transfer by someone else on behalf of token owner)
* @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for
* `transferFrom()` function to succeed
* @dev Token owner must call `approve()` first to authorize
* the transfer on behalf
*/
uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002;
/**
* @dev Defines if the default behavior of `transfer` and `transferFrom`
* checks if the receiver smart contract supports ERC20 tokens
* @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom`
* @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `safeTransferFrom`
*/
uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004;
/**
* @notice Enables token owners to burn their own tokens,
* including locked tokens which are burnt first
* @dev Feature FEATURE_OWN_BURNS must be enabled in order for
* `burn()` function to succeed when called by token owner
*/
uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008;
/**
* @notice Enables approved operators to burn tokens on behalf of their owners,
* including locked tokens which are burnt first
* @dev Feature FEATURE_OWN_BURNS must be enabled in order for
* `burn()` function to succeed when called by approved operator
*/
uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
/**
* @notice Enables delegators to elect delegates
* @dev Feature FEATURE_DELEGATIONS must be enabled in order for
* `delegate()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020;
/**
* @notice Enables delegators to elect delegates on behalf
* (via an EIP712 signature)
* @dev Feature FEATURE_DELEGATIONS must be enabled in order for
* `delegateWithSig()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040;
/**
* @notice Token creator is responsible for creating (minting)
* tokens to an arbitrary address
* @dev Role ROLE_TOKEN_CREATOR allows minting tokens
* (calling `mint` function)
*/
uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000;
/**
* @notice Token destroyer is responsible for destroying (burning)
* tokens owned by an arbitrary address
* @dev Role ROLE_TOKEN_DESTROYER allows burning tokens
* (calling `burn` function)
*/
uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000;
/**
* @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having
* `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER
*/
uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000;
/**
* @notice ERC20 senders are allowed to send tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having
* `ROLE_ERC20_SENDER` permission are allowed to send tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER
*/
uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000;
/**
* @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s)
* @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector`
*/
bytes4 private constant ERC20_RECEIVED = 0x4fc35859;
/**
* @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/**
* @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)");
/**
* @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions
*
* @dev ERC20 `event Transfer(address indexed _from, address indexed _to, uint256 _value)`
*
* @param _from an address tokens were consumed from
* @param _to an address tokens were sent to
* @param _value number of tokens transferred
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Fired in approve() and approveAtomic() functions
*
* @dev ERC20 `event Approval(address indexed _owner, address indexed _spender, uint256 _value)`
*
* @param _owner an address which granted a permission to transfer
* tokens on its behalf
* @param _spender an address which received a permission to transfer
* tokens on behalf of the owner `_owner`
* @param _value amount of tokens granted to transfer on behalf
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @dev Fired in mint() function
*
* @param _by an address which minted some tokens (transaction sender)
* @param _to an address the tokens were minted to
* @param _value an amount of tokens minted
*/
event Minted(address indexed _by, address indexed _to, uint256 _value);
/**
* @dev Fired in burn() function
*
* @param _by an address which burned some tokens (transaction sender)
* @param _from an address the tokens were burnt from
* @param _value an amount of tokens burnt
*/
event Burnt(address indexed _by, address indexed _from, uint256 _value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer
*
* @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions
*
* @param _by an address which performed the transfer
* @param _from an address tokens were consumed from
* @param _to an address tokens were sent to
* @param _value number of tokens transferred
*/
event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Similar to ERC20 Approve event, but also logs old approval value
*
* @dev Fired in approve() and approveAtomic() functions
*
* @param _owner an address which granted a permission to transfer
* tokens on its behalf
* @param _spender an address which received a permission to transfer
* tokens on behalf of the owner `_owner`
* @param _oldValue previously granted amount of tokens to transfer on behalf
* @param _value new granted amount of tokens to transfer on behalf
*/
event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value);
/**
* @dev Notifies that a key-value pair in `votingDelegates` mapping has changed,
* i.e. a delegator address has changed its delegate address
*
* @param _of delegator address, a token owner
* @param _from old delegate, an address which delegate right is revoked
* @param _to new delegate, an address which received the voting power
*/
event DelegateChanged(address indexed _of, address indexed _from, address indexed _to);
/**
* @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed,
* i.e. a delegate's voting power has changed.
*
* @param _of delegate whose voting power has changed
* @param _fromVal previous number of votes delegate had
* @param _toVal new number of votes delegate has
*/
event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal);
/**
* @dev Deploys the token smart contract,
* assigns initial token supply to the address specified
*
* @param _initialHolder owner of the initial token supply
*/
constructor(address _initialHolder) {
// verify initial holder address non-zero (is set)
require(_initialHolder != address(0), "_initialHolder not set (zero address)");
// mint initial supply
mint(_initialHolder, 7_000_000e18);
}
// ===== Start: ERC20/ERC223/ERC777 functions =====
/**
* @notice Gets the balance of a particular address
*
* @dev ERC20 `function balanceOf(address _owner) public view returns (uint256 balance)`
*
* @param _owner the address to query the the balance for
* @return balance an amount of tokens owned by the address specified
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
// read the balance and return
return tokenBalances[_owner];
}
/**
* @notice Transfers some tokens to an external address or a smart contract
*
* @dev ERC20 `function transfer(address _to, uint256 _value) public returns (bool success)`
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * self address or
* * smart contract which doesn't support ERC20
*
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
* @return success true on success, throws otherwise
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
// just delegate call to `transferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
return transferFrom(msg.sender, _to, _value);
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)`
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC20
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
* @return success true on success, throws otherwise
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
// depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default)
// or unsafe transfer
// if `FEATURE_UNSAFE_TRANSFERS` is enabled
// or receiver has `ROLE_ERC20_RECEIVER` permission
// or sender has `ROLE_ERC20_SENDER` permission
if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS)
|| isOperatorInRole(_to, ROLE_ERC20_RECEIVER)
|| isSenderInRole(ROLE_ERC20_SENDER)) {
// we execute unsafe transfer - delegate call to `unsafeTransferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
unsafeTransferFrom(_from, _to, _value);
}
// otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled
// and receiver doesn't have `ROLE_ERC20_RECEIVER` permission
else {
// we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`,
// `FEATURE_TRANSFERS` is verified inside it
safeTransferFrom(_from, _to, _value, "");
}
// both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so
// if we're here - it means operation successful,
// just return true
return true;
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev Inspired by ERC721 safeTransferFrom, this function allows to
* send arbitrary data to the receiver on successful token transfer
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC20Receiver interface
* @dev Returns silently on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
* @param _data [optional] additional data with no specified format,
* sent in onERC20Received call to `_to` in case if its a smart contract
*/
function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public {
// first delegate call to `unsafeTransferFrom`
// to perform the unsafe token(s) transfer
unsafeTransferFrom(_from, _to, _value);
// after the successful transfer - check if receiver supports
// ERC20Receiver and execute a callback handler `onERC20Received`,
// reverting whole transaction on any error:
// check if receiver `_to` supports ERC20Receiver interface
if(AddressUtils.isContract(_to)) {
// if `_to` is a contract - execute onERC20Received
bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data);
// expected response is ERC20_RECEIVED
require(response == ERC20_RECEIVED, "invalid onERC20Received response");
}
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev In contrast to `safeTransferFrom` doesn't check recipient
* smart contract to support ERC20 tokens (ERC20Receiver)
* @dev Designed to be used by developers when the receiver is known
* to support ERC20 tokens but doesn't implement ERC20Receiver interface
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* @dev Returns silently on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
*/
function unsafeTransferFrom(address _from, address _to, uint256 _value) public {
// if `_from` is equal to sender, require transfers feature to be enabled
// otherwise require transfers on behalf feature to be enabled
require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS)
|| _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF),
_from == msg.sender? "transfers are disabled": "transfers on behalf are disabled");
// non-zero source address check - Zeppelin
// obviously, zero source address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
// since for zero value transfer transaction succeeds otherwise
require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg
// non-zero recipient address check
require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg
// sender and recipient cannot be the same
require(_from != _to, "sender and recipient are the same (_from = _to)");
// sending tokens to the token smart contract itself is a client mistake
require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)");
// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20
// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event."
if(_value == 0) {
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
// don't forget to return - we're done
return;
}
// no need to make arithmetic overflow check on the _value - by design of mint()
// in case of transfer on behalf
if(_from != msg.sender) {
// read allowance value - the amount of tokens allowed to transfer - into the stack
uint256 _allowance = transferAllowances[_from][msg.sender];
// verify sender has an allowance to transfer amount of tokens requested
require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][msg.sender] = _allowance;
// emit an improved atomic approve event
emit Approved(_from, msg.sender, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
}
// verify sender has enough tokens to transfer on behalf
require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg
// perform the transfer:
// decrease token owner (sender) balance
tokenBalances[_from] -= _value;
// increase `_to` address (receiver) balance
tokenBalances[_to] += _value;
// move voting power associated with the tokens transferred
__moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value);
// emit an improved transfer event
emit Transferred(msg.sender, _from, _to, _value);
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
}
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner
*
* @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)`
*
* @dev Caller must not necessarily own any tokens to grant the permission
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @return success true on success, throws otherwise
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
// non-zero spender address check - Zeppelin
// obviously, zero spender address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg
// read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9)
uint256 _oldValue = transferAllowances[msg.sender][_spender];
// perform an operation: write value requested into the storage
transferAllowances[msg.sender][_spender] = _value;
// emit an improved atomic approve event (ISBN:978-1-7281-3027-9)
emit Approved(msg.sender, _spender, _oldValue, _value);
// emit an ERC20 approval event
emit Approval(msg.sender, _spender, _value);
// operation successful, return true
return true;
}
/**
* @notice Returns the amount which _spender is still allowed to withdraw from _owner.
*
* @dev ERC20 `function allowance(address _owner, address _spender) public view returns (uint256 remaining)`
*
* @dev A function to check an amount of tokens owner approved
* to transfer on its behalf by some other address called "spender"
*
* @param _owner an address which approves transferring some tokens on its behalf
* @param _spender an address approved to transfer some tokens on behalf
* @return remaining an amount of tokens approved address `_spender` can transfer on behalf
* of token owner `_owner`
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
// read the value from storage and return
return transferAllowances[_owner][_spender];
}
// ===== End: ERC20/ERC223/ERC777 functions =====
// ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) =====
/**
* @notice Increases the allowance granted to `spender` by the transaction sender
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Throws if value to increase by is zero or too big and causes arithmetic overflow
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens to increase by
* @return success true on success, throws otherwise
*/
function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value and arithmetic overflow check on the allowance
require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow");
// delegate call to `approve` with the new value
return approve(_spender, currentVal + _value);
}
/**
* @notice Decreases the allowance granted to `spender` by the caller.
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Throws if value to decrease by is zero or is bigger than currently allowed value
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens to decrease by
* @return success true on success, throws otherwise
*/
function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value check on the allowance
require(_value > 0, "zero value approval decrease");
// verify allowance decrease doesn't underflow
require(currentVal >= _value, "ERC20: decreased allowance below zero");
// delegate call to `approve` with the new value
return approve(_spender, currentVal - _value);
}
// ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) =====
// ===== Start: Minting/burning extension =====
/**
* @dev Mints (creates) some tokens to address specified
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
* @dev Behaves effectively as `mintTo` function, allowing
* to specify an address to mint tokens to
* @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission
*
* @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256
*
* @param _to an address to mint tokens to
* @param _value an amount of tokens to mint (create)
*/
function mint(address _to, uint256 _value) public {
// check if caller has sufficient permissions to mint tokens
require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)");
// non-zero recipient address check
require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg
// non-zero _value and arithmetic overflow check on the total supply
// this check automatically secures arithmetic overflow on the individual balance
require(totalSupply + _value > totalSupply, "zero value mint or arithmetic overflow");
// uint192 overflow check (required by voting delegation)
require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)");
// perform mint:
// increase total amount of tokens value
totalSupply += _value;
// increase `_to` address balance
tokenBalances[_to] += _value;
// create voting power associated with the tokens minted
__moveVotingPower(address(0), votingDelegates[_to], _value);
// fire a minted event
emit Minted(msg.sender, _to, _value);
// emit an improved transfer event
emit Transferred(msg.sender, address(0), _to, _value);
// fire ERC20 compliant transfer event
emit Transfer(address(0), _to, _value);
}
/**
* @dev Burns (destroys) some tokens from the address specified
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
* @dev Behaves effectively as `burnFrom` function, allowing
* to specify an address to burn tokens from
* @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission
*
* @param _from an address to burn some tokens from
* @param _value an amount of tokens to burn (destroy)
*/
function burn(address _from, uint256 _value) public {
// check if caller has sufficient permissions to burn tokens
// and if not - check for possibility to burn own tokens or to burn on behalf
if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) {
// if `_from` is equal to sender, require own burns feature to be enabled
// otherwise require burns on behalf feature to be enabled
require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS)
|| _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF),
_from == msg.sender? "burns are disabled": "burns on behalf are disabled");
// in case of burn on behalf
if(_from != msg.sender) {
// read allowance value - the amount of tokens allowed to be burnt - into the stack
uint256 _allowance = transferAllowances[_from][msg.sender];
// verify sender has an allowance to burn amount of tokens requested
require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][msg.sender] = _allowance;
// emit an improved atomic approve event
emit Approved(msg.sender, _from, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
}
}
// at this point we know that either sender is ROLE_TOKEN_DESTROYER or
// we burn own tokens or on behalf (in latest case we already checked and updated allowances)
// we have left to execute balance checks and burning logic itself
// non-zero burn value check
require(_value != 0, "zero value burn");
// non-zero source address check - Zeppelin
require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg
// verify `_from` address has enough tokens to destroy
// (basically this is a arithmetic overflow check)
require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg
// perform burn:
// decrease `_from` address balance
tokenBalances[_from] -= _value;
// decrease total amount of tokens value
totalSupply -= _value;
// destroy voting power associated with the tokens burnt
__moveVotingPower(votingDelegates[_from], address(0), _value);
// fire a burnt event
emit Burnt(msg.sender, _from, _value);
// emit an improved transfer event
emit Transferred(msg.sender, _from, address(0), _value);
// fire ERC20 compliant transfer event
emit Transfer(_from, address(0), _value);
}
// ===== End: Minting/burning extension =====
// ===== Start: DAO Support (Compound-like voting delegation) =====
/**
* @notice Gets current voting power of the account `_of`
* @param _of the address of account to get voting power of
* @return current cumulative voting power of the account,
* sum of token balances of all its voting delegators
*/
function getVotingPower(address _of) public view returns (uint256) {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// lookup the history and return latest element
return history.length == 0? 0: history[history.length - 1].votingPower;
}
/**
* @notice Gets past voting power of the account `_of` at some block `_blockNum`
* @dev Throws if `_blockNum` is not in the past (not the finalized block)
* @param _of the address of account to get voting power of
* @param _blockNum block number to get the voting power at
* @return past cumulative voting power of the account,
* sum of token balances of all its voting delegators at block number `_blockNum`
*/
function getVotingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) {
// make sure block number is not in the past (not the finalized block)
require(_blockNum < block.number, "not yet determined"); // Compound msg
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// if voting power history for the account provided is empty
if(history.length == 0) {
// than voting power is zero - return the result
return 0;
}
// check latest voting power history record block number:
// if history was not updated after the block of interest
if(history[history.length - 1].blockNumber <= _blockNum) {
// we're done - return last voting power record
return getVotingPower(_of);
}
// check first voting power history record block number:
// if history was never updated before the block of interest
if(history[0].blockNumber > _blockNum) {
// we're done - voting power at the block num of interest was zero
return 0;
}
// `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending;
// apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that
// `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time
// `votingPowerHistory[_of][i + 1].blockNumber > _blockNum`
// return the result - voting power found at index `i`
return history[__binaryLookup(_of, _blockNum)].votingPower;
}
/**
* @dev Reads an entire voting power history array for the delegate specified
*
* @param _of delegate to query voting power history for
* @return voting power history array for the delegate of interest
*/
function getVotingPowerHistory(address _of) public view returns(VotingPowerRecord[] memory) {
// return an entire array as memory
return votingPowerHistory[_of];
}
/**
* @dev Returns length of the voting power history array for the delegate specified;
* useful since reading an entire array just to get its length is expensive (gas cost)
*
* @param _of delegate to query voting power history length for
* @return voting power history array length for the delegate of interest
*/
function getVotingPowerHistoryLength(address _of) public view returns(uint256) {
// read array length and return
return votingPowerHistory[_of].length;
}
/**
* @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to`
*
* @dev Accepts zero value address to delegate voting power to, effectively
* removing the delegate in that case
*
* @param _to address to delegate voting power to
*/
function delegate(address _to) public {
// verify delegations are enabled
require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled");
// delegate call to `__delegate`
__delegate(msg.sender, _to);
}
/**
* @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to`
*
* @dev Accepts zero value address to delegate voting power to, effectively
* removing the delegate in that case
*
* @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing,
* see https://eips.ethereum.org/EIPS/eip-712
*
* @param _to address to delegate voting power to
* @param _nonce nonce used to construct the signature, and used to validate it;
* nonce is increased by one after successful signature validation and vote delegation
* @param _exp signature expiration time
* @param v the recovery byte of the signature
* @param r half of the ECDSA signature pair
* @param s half of the ECDSA signature pair
*/
function delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public {
// verify delegations on behalf are enabled
require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled");
// build the EIP-712 contract domain separator
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this)));
// build the EIP-712 hashStruct of the delegation message
bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp));
// calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message)
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct));
// recover the address who signed the message with v, r, s
address signer = ecrecover(digest, v, r, s);
// perform message integrity and security validations
require(signer != address(0), "invalid signature"); // Compound msg
require(_nonce == nonces[signer], "invalid nonce"); // Compound msg
require(block.timestamp < _exp, "signature expired"); // Compound msg
// update the nonce for that particular signer to avoid replay attack
nonces[signer]++;
// delegate call to `__delegate` - execute the logic required
__delegate(signer, _to);
}
/**
* @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to`
* @dev Writes to `votingDelegates` and `votingPowerHistory` mappings
*
* @param _from delegator who delegates his voting power
* @param _to delegate who receives the voting power
*/
function __delegate(address _from, address _to) private {
// read current delegate to be replaced by a new one
address _fromDelegate = votingDelegates[_from];
// read current voting power (it is equal to token balance)
uint256 _value = tokenBalances[_from];
// reassign voting delegate to `_to`
votingDelegates[_from] = _to;
// update voting power for `_fromDelegate` and `_to`
__moveVotingPower(_fromDelegate, _to, _value);
// emit an event
emit DelegateChanged(_from, _fromDelegate, _to);
}
/**
* @dev Auxiliary function to move voting power `_value`
* from delegate `_from` to the delegate `_to`
*
* @dev Doesn't have any effect if `_from == _to`, or if `_value == 0`
*
* @param _from delegate to move voting power from
* @param _to delegate to move voting power to
* @param _value voting power to move from `_from` to `_to`
*/
function __moveVotingPower(address _from, address _to, uint256 _value) private {
// if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`)
if(_from == _to || _value == 0) {
// return silently with no action
return;
}
// if source address is not zero - decrease its voting power
if(_from != address(0)) {
// read current source address voting power
uint256 _fromVal = getVotingPower(_from);
// calculate decreased voting power
// underflow is not possible by design:
// voting power is limited by token balance which is checked by the callee
uint256 _toVal = _fromVal - _value;
// update source voting power from `_fromVal` to `_toVal`
__updateVotingPower(_from, _fromVal, _toVal);
}
// if destination address is not zero - increase its voting power
if(_to != address(0)) {
// read current destination address voting power
uint256 _fromVal = getVotingPower(_to);
// calculate increased voting power
// overflow is not possible by design:
// max token supply limits the cumulative voting power
uint256 _toVal = _fromVal + _value;
// update destination voting power from `_fromVal` to `_toVal`
__updateVotingPower(_to, _fromVal, _toVal);
}
}
/**
* @dev Auxiliary function to update voting power of the delegate `_of`
* from value `_fromVal` to value `_toVal`
*
* @param _of delegate to update its voting power
* @param _fromVal old voting power of the delegate
* @param _toVal new voting power of the delegate
*/
function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// if there is an existing voting power value stored for current block
if(history.length != 0 && history[history.length - 1].blockNumber == block.number) {
// update voting power which is already stored in the current block
history[history.length - 1].votingPower = uint192(_toVal);
}
// otherwise - if there is no value stored for current block
else {
// add new element into array representing the value for current block
history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal)));
}
// emit an event
emit VotingPowerChanged(_of, _fromVal, _toVal);
}
/**
* @dev Auxiliary function to lookup an element in a sorted (asc) array of elements
*
* @dev This function finds the closest element in an array to the value
* of interest (not exceeding that value) and returns its index within an array
*
* @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`,
* it is sorted in ascending order (blockNumber increases)
*
* @param _to an address of the delegate to get an array for
* @param n value of interest to look for
* @return an index of the closest element in an array to the value
* of interest (not exceeding that value)
*/
function __binaryLookup(address _to, uint256 n) private view returns(uint256) {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_to];
// left bound of the search interval, originally start of the array
uint256 i = 0;
// right bound of the search interval, originally end of the array
uint256 j = history.length - 1;
// the iteration process narrows down the bounds by
// splitting the interval in a half oce per each iteration
while(j > i) {
// get an index in the middle of the interval [i, j]
uint256 k = j - (j - i) / 2;
// read an element to compare it with the value of interest
VotingPowerRecord memory cp = history[k];
// if we've got a strict equal - we're lucky and done
if(cp.blockNumber == n) {
// just return the result - index `k`
return k;
}
// if the value of interest is bigger - move left bound to the middle
else if (cp.blockNumber < n) {
// move left bound `i` to the middle position `k`
i = k;
}
// otherwise, when the value of interest is smaller - move right bound to the middle
else {
// move right bound `j` to the middle position `k - 1`:
// element at position `k` is bigger and cannot be the result
j = k - 1;
}
}
// reaching that point means no exact match found
// since we're interested in the element which is not bigger than the
// element of interest, we return the lower bound `i`
return i;
}
}
// ===== End: DAO Support (Compound-like voting delegation) =====
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/**
* @title Address Utils
*
* @dev Utility library of inline functions on addresses
*
* @author Basil Gorin
*/
library AddressUtils {
/**
* @notice Checks if the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
// a variable to load `extcodesize` to
uint256 size = 0;
// 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.
// solium-disable-next-line security/no-inline-assembly
assembly {
// retrieve the size of the code at address `addr`
size := extcodesize(addr)
}
// positive size indicates a smart contract address
return size > 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/**
* @title Access Control List
*
* @notice Access control smart contract provides an API to check
* if specific operation is permitted globally and/or
* if particular user has a permission to execute it.
*
* @notice It deals with two main entities: features and roles.
*
* @notice Features are designed to be used to enable/disable specific
* functions (public functions) of the smart contract for everyone.
* @notice User roles are designed to restrict access to specific
* functions (restricted functions) of the smart contract to some users.
*
* @notice Terms "role", "permissions" and "set of permissions" have equal meaning
* in the documentation text and may be used interchangeably.
* @notice Terms "permission", "single permission" implies only one permission bit set.
*
* @dev This smart contract is designed to be inherited by other
* smart contracts which require access control management capabilities.
*
* @author Basil Gorin
*/
contract AccessControl {
/**
* @notice Access manager is responsible for assigning the roles to users,
* enabling/disabling global features of the smart contract
* @notice Access manager can add, remove and update user roles,
* remove and update global features
*
* @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features
* @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled
*/
uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000;
/**
* @dev Bitmask representing all the possible permissions (super admin role)
* @dev Has all the bits are enabled (2^256 - 1 value)
*/
uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF...
/**
* @notice Privileged addresses with defined roles/permissions
* @notice In the context of ERC20/ERC721 tokens these can be permissions to
* allow minting or burning tokens, transferring on behalf and so on
*
* @dev Maps user address to the permissions bitmask (role), where each bit
* represents a permission
* @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
* represents all possible permissions
* @dev Zero address mapping represents global features of the smart contract
*/
mapping(address => uint256) public userRoles;
/**
* @dev Fired in updateRole() and updateFeatures()
*
* @param _by operator which called the function
* @param _to address which was granted/revoked permissions
* @param _requested permissions requested
* @param _actual permissions effectively set
*/
event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual);
/**
* @notice Creates an access control instance,
* setting contract creator to have full privileges
*/
constructor() {
// contract creator has full privileges
userRoles[msg.sender] = FULL_PRIVILEGES_MASK;
}
/**
* @notice Retrieves globally set of features enabled
*
* @dev Auxiliary getter function to maintain compatibility with previous
* versions of the Access Control List smart contract, where
* features was a separate uint256 public field
*
* @return 256-bit bitmask of the features enabled
*/
function features() public view returns(uint256) {
// according to new design features are stored in zero address
// mapping of `userRoles` structure
return userRoles[address(0)];
}
/**
* @notice Updates set of the globally enabled features (`features`),
* taking into account sender's permissions
*
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
* @dev Function is left for backward compatibility with older versions
*
* @param _mask bitmask representing a set of features to enable/disable
*/
function updateFeatures(uint256 _mask) public {
// delegate call to `updateRole`
updateRole(address(0), _mask);
}
/**
* @notice Updates set of permissions (role) for a given user,
* taking into account sender's permissions.
*
* @dev Setting role to zero is equivalent to removing an all permissions
* @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to
* copying senders' permissions (role) to the user
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
*
* @param operator address of a user to alter permissions for or zero
* to alter global features of the smart contract
* @param role bitmask representing a set of permissions to
* enable/disable for a user specified
*/
function updateRole(address operator, uint256 role) public {
// caller must have a permission to update user roles
require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)");
// evaluate the role and reassign it
userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);
// fire an event
emit RoleUpdated(msg.sender, operator, role, userRoles[operator]);
}
/**
* @notice Determines the permission bitmask an operator can set on the
* target permission set
* @notice Used to calculate the permission bitmask to be set when requested
* in `updateRole` and `updateFeatures` functions
*
* @dev Calculated based on:
* 1) operator's own permission set read from userRoles[operator]
* 2) target permission set - what is already set on the target
* 3) desired permission set - what do we want set target to
*
* @dev Corner cases:
* 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`:
* `desired` bitset is returned regardless of the `target` permission set value
* (what operator sets is what they get)
* 2) Operator with no permissions (zero bitset):
* `target` bitset is returned regardless of the `desired` value
* (operator has no authority and cannot modify anything)
*
* @dev Example:
* Consider an operator with the permissions bitmask 00001111
* is about to modify the target permission set 01010101
* Operator wants to set that permission set to 00110011
* Based on their role, an operator has the permissions
* to update only lowest 4 bits on the target, meaning that
* high 4 bits of the target set in this example is left
* unchanged and low 4 bits get changed as desired: 01010011
*
* @param operator address of the contract operator which is about to set the permissions
* @param target input set of permissions to operator is going to modify
* @param desired desired set of permissions operator would like to set
* @return resulting set of permissions given operator will set
*/
function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) {
// read operator's permissions
uint256 p = userRoles[operator];
// taking into account operator's permissions,
// 1) enable the permissions desired on the `target`
target |= p & desired;
// 2) disable the permissions desired on the `target`
target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired));
// return calculated result
return target;
}
/**
* @notice Checks if requested set of features is enabled globally on the contract
*
* @param required set of features to check against
* @return true if all the features requested are enabled, false otherwise
*/
function isFeatureEnabled(uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing `features` property
return __hasRole(features(), required);
}
/**
* @notice Checks if transaction sender `msg.sender` has all the permissions required
*
* @param required set of permissions (role) to check against
* @return true if all the permissions requested are enabled, false otherwise
*/
function isSenderInRole(uint256 required) public view returns(bool) {
// delegate call to `isOperatorInRole`, passing transaction sender
return isOperatorInRole(msg.sender, required);
}
/**
* @notice Checks if operator has all the permissions (role) required
*
* @param operator address of the user to check role for
* @param required set of permissions (role) to check
* @return true if all the permissions requested are enabled, false otherwise
*/
function isOperatorInRole(address operator, uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing operator's permissions (role)
return __hasRole(userRoles[operator], required);
}
/**
* @dev Checks if role `actual` contains all the permissions required `required`
*
* @param actual existent role
* @param required required role
* @return true if actual has required role (all permissions), false otherwise
*/
function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) {
// check the bitmask for the role required and return the result
return actual & required == required;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/**
* @title ERC20 token receiver interface
*
* @dev Interface for any contract that wants to support safe transfers
* from ERC20 token smart contracts.
* @dev Inspired by ERC721 and ERC223 token standards
*
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
* @dev See https://github.com/ethereum/EIPs/issues/223
*
* @author Basil Gorin
*/
interface ERC20Receiver {
/**
* @notice Handle the receipt of a ERC20 token(s)
* @dev The ERC20 smart contract calls this function on the recipient
* after a successful transfer (`safeTransferFrom`).
* This function MAY throw to revert and reject the transfer.
* Return of other than the magic value MUST result in the transaction being reverted.
* @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 _value amount of tokens which is being transferred
* @param _data additional data with no specified format
* @return `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))` unless throwing
*/
function onERC20Received(address _operator, address _from, uint256 _value, bytes calldata _data) external returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import "../interfaces/IERC20.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}.
*/
// Copied from Open Zeppelin
contract ERC20 is IERC20 {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @notice Token creator is responsible for creating (minting)
* tokens to an arbitrary address
* @dev Role ROLE_TOKEN_CREATOR allows minting tokens
* (calling `mint` function)
*/
uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000;
/**
* @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_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender] - 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(msg.sender, spender, _allowances[msg.sender][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) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal 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] - amount;
_balances[recipient] = _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 = _totalSupply + amount;
_balances[account] = _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);
_balances[account] = _balances[account] - amount;
_totalSupply = _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 Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/**
* @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.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
* ====
*/
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.3._
*/
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.3._
*/
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);
}
}
}
}
| Gets the balance of a particular address ERC20 `function balanceOf(address _owner) public view returns (uint256 balance)` _owner the address to query the the balance for return balance an amount of tokens owned by the address specified/ read the balance and return | function balanceOf(address _owner) public view returns (uint256 balance) {
return tokenBalances[_owner];
}
| 898,504 |
/**
*Submitted for verification at Etherscan.io on 2021-02-05
*/
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.8;
/*
* @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 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 returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
// Logged when an operator is added or removed.
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function setRecord(
bytes32 node,
address owner,
address resolver,
uint64 ttl
) external;
function setSubnodeRecord(
bytes32 node,
bytes32 label,
address owner,
address resolver,
uint64 ttl
) external;
function setSubnodeOwner(
bytes32 node,
bytes32 label,
address owner
) external returns (bytes32);
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function setApprovalForAll(address operator, bool approved) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
function recordExists(bytes32 node) external view returns (bool);
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
}
interface IENSResolver {
event AddrChanged(bytes32 indexed _node, address _addr);
event NameChanged(bytes32 indexed _node, string _name);
function addr(bytes32 _node) external view returns (address);
function setAddr(bytes32 _node, address _addr) external;
function name(bytes32 _node) external view returns (string memory);
function setName(bytes32 _node, string calldata _name) external;
}
interface IENSReverseRegistrar {
function claim(address _owner) external returns (bytes32);
function claimWithResolver(address _owner, address _resolver)
external
returns (bytes32);
function setName(string calldata _name) external returns (bytes32);
function node(address _addr) external pure returns (bytes32);
}
interface IMirrorENSRegistrar {
function changeRootNodeOwner(address newOwner_) external;
function register(string calldata label_, address owner_) external;
function updateENSReverseRegistrar() external;
}
contract MirrorENSRegistrar is IMirrorENSRegistrar, Ownable {
// ============ Constants ============
/**
* namehash('addr.reverse')
*/
bytes32 public constant ADDR_REVERSE_NODE =
0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
// ============ Immutable Storage ============
/**
* The name of the ENS root, e.g. "mirror.xyz".
* @dev dependency injectable for testnet.
*/
string public rootName;
/**
* The node of the root name (e.g. namehash(mirror.xyz))
*/
bytes32 public immutable rootNode;
/**
* The address of the public ENS registry.
* @dev Dependency-injectable for testing purposes, but otherwise this is the
* canonical ENS registry at 0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e.
*/
IENS public immutable ensRegistry;
/**
* The address of the MirrorWriteToken that gates access to this namespace.
*/
address public immutable writeToken;
/**
* The address of the MirrorENSResolver.
*/
IENSResolver public immutable ensResolver;
// ============ Mutable Storage ============
/**
* Set by anyone to the correct address after configuration,
* to prevent a lookup on each registration.
*/
IENSReverseRegistrar public reverseRegistrar;
// ============ Events ============
event RootNodeOwnerChange(bytes32 indexed node, address indexed owner);
event RegisteredENS(address indexed _owner, string _ens);
// ============ Modifiers ============
/**
* @dev Modifier to check whether the `msg.sender` is the MirrorWriteToken.
* If it is, it will run the function. Otherwise, it will revert.
*/
modifier onlyWriteToken() {
require(
msg.sender == writeToken,
"MirrorENSRegistrar: caller is not the Mirror Write Token"
);
_;
}
// ============ Constructor ============
/**
* @notice Constructor that sets the ENS root name and root node to manage.
* @param rootName_ The root name (e.g. mirror.xyz).
* @param rootNode_ The node of the root name (e.g. namehash(mirror.xyz)).
* @param ensRegistry_ The address of the ENS registry
* @param ensResolver_ The address of the ENS resolver
* @param writeToken_ The address of the Mirror Write Token
*/
constructor(
string memory rootName_,
bytes32 rootNode_,
address ensRegistry_,
address ensResolver_,
address writeToken_
) public {
rootName = rootName_;
rootNode = rootNode_;
writeToken = writeToken_;
// Registrations are cheaper if these are instantiated.
ensRegistry = IENS(ensRegistry_);
ensResolver = IENSResolver(ensResolver_);
}
// ============ Registration ============
/**
* @notice Assigns an ENS subdomain of the root node to a target address.
* Registers both the forward and reverse ENS. Can only be called by writeToken.
* @param label_ The subdomain label.
* @param owner_ The owner of the subdomain.
*/
function register(string calldata label_, address owner_)
external
override
onlyWriteToken
{
bytes32 labelNode = keccak256(abi.encodePacked(label_));
bytes32 node = keccak256(abi.encodePacked(rootNode, labelNode));
require(
ensRegistry.owner(node) == address(0),
"MirrorENSManager: label is already owned"
);
// Forward ENS
ensRegistry.setSubnodeRecord(
rootNode,
labelNode,
owner_,
address(ensResolver),
0
);
ensResolver.setAddr(node, owner_);
// Reverse ENS
string memory name = string(abi.encodePacked(label_, ".", rootName));
bytes32 reverseNode = reverseRegistrar.node(owner_);
ensResolver.setName(reverseNode, name);
emit RegisteredENS(owner_, name);
}
// ============ ENS Management ============
/**
* @notice This function must be called when the ENS Manager contract is replaced
* and the address of the new Manager should be provided.
* @param _newOwner The address of the new ENS manager that will manage the root node.
*/
function changeRootNodeOwner(address _newOwner)
external
override
onlyOwner
{
ensRegistry.setOwner(rootNode, _newOwner);
emit RootNodeOwnerChange(rootNode, _newOwner);
}
/**
* @notice Updates to the reverse registrar.
*/
function updateENSReverseRegistrar() external override onlyOwner {
reverseRegistrar = IENSReverseRegistrar(
ensRegistry.owner(ADDR_REVERSE_NODE)
);
}
} | This function must be called when the ENS Manager contract is replaced and the address of the new Manager should be provided. _newOwner The address of the new ENS manager that will manage the root node./ | function changeRootNodeOwner(address _newOwner)
external
override
onlyOwner
{
ensRegistry.setOwner(rootNode, _newOwner);
emit RootNodeOwnerChange(rootNode, _newOwner);
}
| 2,352,762 |
pragma solidity ^0.5.17;
interface IERC20 {
function TOTALSUPPLY313() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF488(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER197(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE10(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE847(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM795(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER740(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL4(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD959(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB742(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB742(a, b, "SafeMath: subtraction overflow");
}
function SUB742(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL674(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV198(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV198(a, b, "SafeMath: division by zero");
}
function DIV198(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function TOTALSUPPLY313() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF488(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER197(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER102(msg.sender, recipient, amount);
return true;
}
function ALLOWANCE10(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE847(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE525(msg.sender, spender, amount);
return true;
}
function TRANSFERFROM795(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER102(sender, recipient, amount);
_APPROVE525(sender, msg.sender, _allowances[sender][msg.sender].SUB742(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE946(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE525(msg.sender, spender, _allowances[msg.sender][spender].ADD959(addedValue));
return true;
}
function DECREASEALLOWANCE167(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE525(msg.sender, spender, _allowances[msg.sender][spender].SUB742(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER102(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB742(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD959(amount);
emit TRANSFER740(sender, recipient, amount);
}
function _MINT358(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD959(amount);
_balances[account] = _balances[account].ADD959(amount);
emit TRANSFER740(address(0), account, amount);
}
function _BURN576(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB742(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB742(amount);
emit TRANSFER740(account, address(0), amount);
}
function _APPROVE525(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL4(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME516() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL328() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS972() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
interface BondingCurve {
function CALCULATEPURCHASERETURN628(uint _supply, uint _reserveBalance, uint32 _reserveRatio, uint _depositAmount) external view returns (uint); //inject NONSTANDARD NAMING
function CALCULATESALERETURN903(uint _supply, uint _reserveBalance, uint32 _reserveRatio, uint _sellAmount) external view returns (uint); //inject NONSTANDARD NAMING
}
contract ContinuousToken is ERC20 {
using SafeMath for uint;
uint public scale = 10**18;
uint public reserveBalance = 1*10**15;
uint32 public reserveRatio;
BondingCurve constant public curve79 = BondingCurve(0x16F6664c16beDE5d70818654dEfef11769D40983); //inject NONSTANDARD NAMING
function _BUY48(uint _amount) internal returns (uint _bought) { //inject NONSTANDARD NAMING
_bought = _CONTINUOUSMINT40(_amount);
}
function _SELL6(uint _amount) internal returns (uint _sold) { //inject NONSTANDARD NAMING
_sold = _CONTINUOUSBURN983(_amount);
}
function CALCULATECONTINUOUSMINTRETURN393(uint _amount) public view returns (uint mintAmount) { //inject NONSTANDARD NAMING
return curve79.CALCULATEPURCHASERETURN628(TOTALSUPPLY313(), reserveBalance, uint32(reserveRatio), _amount);
}
function CALCULATECONTINUOUSBURNRETURN418(uint _amount) public view returns (uint burnAmount) { //inject NONSTANDARD NAMING
return curve79.CALCULATESALERETURN903(TOTALSUPPLY313(), reserveBalance, uint32(reserveRatio), _amount);
}
function _CONTINUOUSMINT40(uint _deposit) internal returns (uint) { //inject NONSTANDARD NAMING
uint amount = CALCULATECONTINUOUSMINTRETURN393(_deposit);
reserveBalance = reserveBalance.ADD959(_deposit);
return amount;
}
function _CONTINUOUSBURN983(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING
uint reimburseAmount = CALCULATECONTINUOUSBURNRETURN418(_amount);
reserveBalance = reserveBalance.SUB742(reimburseAmount);
return reimburseAmount;
}
}
contract EminenceCurrency is ContinuousToken, ERC20Detailed {
mapping(address => bool) public gamemasters;
mapping(address => bool) public npcs;
event ADDGM365(address indexed newGM, address indexed gm); //inject NONSTANDARD NAMING
event REVOKEGM307(address indexed newGM, address indexed gm); //inject NONSTANDARD NAMING
event ADDNPC414(address indexed newNPC, address indexed gm); //inject NONSTANDARD NAMING
event REVOKENPC62(address indexed newNPC, address indexed gm); //inject NONSTANDARD NAMING
event CASHSHOPBUY855(address _from, uint _amount, uint _deposit); //inject NONSTANDARD NAMING
event CASHSHOPSELL318(address _from, uint _amount, uint _reimbursement); //inject NONSTANDARD NAMING
IERC20 constant public dai417 = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING
constructor (string memory name, string memory symbol, uint32 _reserveRatio) public ERC20Detailed(name, symbol, 18) {
gamemasters[msg.sender] = true;
reserveRatio = _reserveRatio;
_MINT358(msg.sender, 1*scale);
}
function ADDNPC781(address _npc) external { //inject NONSTANDARD NAMING
require(gamemasters[msg.sender], "!gm");
npcs[_npc] = true;
emit ADDNPC414(_npc, msg.sender);
}
function REVOKENPC754(address _npc) external { //inject NONSTANDARD NAMING
require(gamemasters[msg.sender], "!gm");
npcs[_npc] = false;
emit REVOKENPC62(_npc, msg.sender);
}
function ADDGM496(address _gm) external { //inject NONSTANDARD NAMING
require(gamemasters[msg.sender]||gamemasters[tx.origin], "!gm");
gamemasters[_gm] = true;
emit ADDGM365(_gm, msg.sender);
}
function REVOKEGM619(address _gm) external { //inject NONSTANDARD NAMING
require(gamemasters[msg.sender], "!gm");
gamemasters[_gm] = false;
emit REVOKEGM307(_gm, msg.sender);
}
function AWARD423(address _to, uint _amount) external { //inject NONSTANDARD NAMING
require(gamemasters[msg.sender], "!gm");
_MINT358(_to, _amount);
}
function CLAIM181(address _from, uint _amount) external { //inject NONSTANDARD NAMING
require(gamemasters[msg.sender]||npcs[msg.sender], "!gm");
_BURN576(_from, _amount);
}
function BUY665(uint _amount, uint _min) external returns (uint _bought) { //inject NONSTANDARD NAMING
_bought = _BUY48(_amount);
require(_bought >= _min, "slippage");
dai417.TRANSFERFROM795(msg.sender, address(this), _amount);
_MINT358(msg.sender, _bought);
emit CASHSHOPBUY855(msg.sender, _bought, _amount);
}
function SELL118(uint _amount, uint _min) external returns (uint _bought) { //inject NONSTANDARD NAMING
_bought = _SELL6(_amount);
require(_bought >= _min, "slippage");
_BURN576(msg.sender, _amount);
dai417.TRANSFER197(msg.sender, _bought);
emit CASHSHOPSELL318(msg.sender, _amount, _bought);
}
} | inject NONSTANDARD NAMING | function DIV198(uint a, uint b, string memory errorMessage) internal pure returns (uint) { | 13,006,496 |
./full_match/137/0x03aB6c074373e7957e07bF3FEb0629E5323a464B/sources/contracts/CourseContract.sol | Teacher can also boot student which sends student's stake to multisig. | function bootStudent(address _account) external onlyRole(TEACHER){
require(hasRole(STUDENT, _account),"Address is not enrolled :/");
_revokeRole(STUDENT, _account);
require(success, "Failed to boot >:(");
factory.updateBoot(_account, studentStake);
emit DropOut(_account);
}
| 3,775,644 |
pragma solidity ^0.4.18;
import "./TokenInterface.sol";
import "./ClientInterface.sol";
import "./SafeMath.sol";
/**
@title DCourt Arbitration contract
@author Ihab McShea Nour Haridy
*/
contract DCArbitration {
using SafeMath for uint256;
DCTInterface DCToken;
/*
Variables
*/
uint256 round;
uint256 caseCounter;
uint256 RoundReward;
uint256 collateral;
uint256 roundsPerHalving;
uint256 votingPeriod;
uint256 unlockingPeriod;
uint256 minTrialPeriod;
uint256 challengingPeriod;
uint256 roundWeight;
uint256 blocksPerRound;
uint256 genesisBlock;
uint8 witnessCount;
uint8 maxWitnesses;
uint256 courtCouncilPool;
struct Witness {
address addr;
string name;
uint256 reportCount;
uint256[] reports;
}
struct spamReport{
address submitter;
uint256 caseID;
address accuser;
bool verdict;
}
mapping(address => uint256) public delegates;
mapping(address => address) public voters;
mapping (uint => Witness) public witnesses;
mapping(uint256 => mapping(uint256 => bool)) witnessVote;
mapping(uint256 => spamReport) reportedCases;
mapping(uint => uint) reportVotes;
mapping (address => uint) public witnessRanks;
/*
structs
*/
struct Client{
bytes32 ToA;
uint256 trialDuration;
string URL;
}
struct Case{
address accuser;
address defendant;
address client;
uint256 block;
phase _phase;
string title;
evidence[] _evidence;
uint256 voteWeight;
uint256 ayes;
uint256 nayes;
uint256 round;
uint256 trialDuration;
uint256 collateral;
bool decided;
bool spam;
bool verdict;
}
struct evidence{
string body;
address author;
}
struct juror{
uint256 deposit;
uint256 round;
uint256 remaining;
uint256 activeCases;
uint256 caseCount;
uint256[] cases;
}
struct Vote{
bytes32 _hash;
uint256 amount;
string nonce;
bool decision;
uint256 caseID;
bool unlocked;
bool claimed; //Rewarded or penalized.
}
struct Round{
uint256 roundWeight;
uint256 caseCount;
uint256 reportCount;
}
/*
modifiers
*/
modifier onlyWhenOwner(){
require(DCToken.getOwner() == address(this));
_;
}
modifier onlyContract(){
require(isContract(msg.sender));
_;
}
modifier onlyCaseParty(uint256 _caseID){
require(cases[_caseID].defendant == msg.sender || cases[_caseID].accuser == msg.sender);
_;
}
modifier onlyJuror(){
// require(jurors[msg.sender].round.add(2) <= round);
_;
}
modifier onlyWitness {
require(witnessRanks[msg.sender] > 0);
_;
}
/*
Enumerators
*/
enum phase {
TRIAL,
VOTING,
UNLOCKING,
FINAL
}
/*
mappings
*/
mapping (address => Client) clients;
mapping(uint256 => Case) cases;
mapping (address => juror) jurors;
mapping (uint256 => Round) rounds;
mapping (address => mapping(uint256 => Vote)) votes;
mapping (address => uint256) frozenBalance;
/*
events
*/
event Registration(address indexed addr, bytes32 ToA, string URL);
event newCase(address accuser,
address defendant,
address client,
uint256 block,
string title,
string statement
);
event newEvidence(string body, address author, uint256 caseID);
/*
Functions
*/
function DCArbitration(address DCTAddress, uint256 _votingPeriod, uint256 _minTrialPeriod, uint256 _roundReward, uint256 _blocksPerRound, uint256 _roundsPerHalving, uint256 _collateral, uint256 _challengingPeriod, uint8 _maxWitnesses) public{
DCToken = DCTInterface(DCTAddress);
votingPeriod = _votingPeriod;
minTrialPeriod = _minTrialPeriod;
RoundReward = _roundReward;
blocksPerRound = _blocksPerRound;
unlockingPeriod = 5;
roundsPerHalving = _roundsPerHalving;
genesisBlock = block.number;
collateral = _collateral;
challengingPeriod = _challengingPeriod;
maxWitnesses = _maxWitnesses;
}
/**
@notice Register a decentralized application on the Dcourt system, called by the smart contract of the decentralized application.
@dev You must call this function from your dApp smart contract in order to be able to build it on top of Dcourt.
@param _ToA the hash of terms of agreement
@param _URL the address of the dApp.
@return {
"registered": "if registered"
}
*/
function register(bytes32 _ToA, string _URL) public onlyWhenOwner returns(bool registered){
require(clients[msg.sender].trialDuration == 0);
clients[msg.sender].ToA = _ToA;
clients[msg.sender].URL = _URL;
emit Registration(msg.sender, _ToA, _URL);
return true;
}
event Filed(address indexed _accuser, address indexed _defendant, string _statement, string _title);
/**
@notice File a case from a dApp to the Dcourt system
@dev You should implement a "fileCase" function in your smart contract which can be invoked by the accuser
@param _defendant the address of the defendant
@param _statement the opening statement of the case, also considered the first body of evidence
@param _title the title of the case. should be hard-coded in your contract.
@param trialDuration the duration in which case parties can submit evidence, should be at least as long as the global duration
@return {
"_caseID": "the ID of the filed case"
}
*/
function fileCase(address _defendant, uint256 trialDuration, string _statement, string _title) public returns(uint256 _caseID){
require(trialDuration >= minTrialPeriod);
caseCounter++;
Case storage filedCase = cases[caseCounter];
filedCase.client = msg.sender;
filedCase.accuser = tx.origin;
filedCase.defendant = _defendant;
filedCase.block = block.number;
filedCase.trialDuration = trialDuration;
// evidence storage _evidence = filedCase._evidence[0];
// _evidence.body = _statement;
// _evidence.author = tx.origin;
filedCase.title = _title;
filedCase._phase = phase.TRIAL;
filedCase.collateral = collateral;
emit newCase(tx.origin,
_defendant,
msg.sender,
block.number,
_title,
_statement
);
frozenBalance[tx.origin] = frozenBalance[tx.origin].add(collateral);
DCToken.burn(tx.origin, collateral);
return caseCounter;
}
function unfreezeCollateral(uint256 _caseID){
require(block.number > cases[_caseID].block + clients[cases[_caseID].client].trialDuration + votingPeriod + unlockingPeriod + challengingPeriod && cases[_caseID].spam == false);
DCToken.mint(cases[_caseID].accuser, (cases[_caseID].collateral/2));
}
event Delegation(address indexed voter, address indexed delegate, uint256 balance);
function increaseVote(address _voter, uint256 _amount){
delegates[voters[_voter]] = delegates[voters[_voter]].add(_amount);
emit Delegation(_voter, voters[msg.sender], DCToken.balanceOf(msg.sender));
}
function decreaseVote(address _voter, uint256 _amount){
delegates[voters[_voter]] = delegates[voters[_voter]].sub(_amount);
emit Delegation(_voter, voters[_voter], DCToken.balanceOf(msg.sender));
}
function eligibleForWitness(address _delegate) public view returns (bool) {
return delegates[_delegate] > delegates[witnesses[witnessCount].addr];
}
event Stepdown(address indexed _witness, string _name, uint rank);
event NewWitness(address indexed _witness, string _name, uint rank);
function witnessStepdown() public onlyWitness returns (bool) {
uint rank = witnessRanks[msg.sender];
Witness memory thisWitness = witnesses[rank];
delete witnesses[rank];
witnessRanks[msg.sender] = 0;
if(rank == witnessCount) return true; // If this the last rank, skipping the next loop
for (uint i = rank+1; i < witnessCount+1; i++){ // Move up each witness of a lower rank
witnessRanks[witnesses[i-1].addr] = witnessRanks[witnesses[i].addr];
witnesses[i-1] = witnesses[i];
}
witnessRanks[witnesses[witnessCount].addr] = 0; // Last witness seat must become available after witness stepdown
delete witnesses[witnessCount];
emit Stepdown(msg.sender, thisWitness.name, rank);
return true;
}
function becomeWitness(string _name) public returns (bool) {
uint256 weight = delegates[msg.sender];
require(weight > 0 && ( witnessRanks[msg.sender] > 21 || witnessRanks[msg.sender] ==0));
uint rank;
if(witnessCount == 0 ){
rank = 1;
}else{
for (uint i = witnessCount; i > 0 ; i--){ // iterate on the witnesses from the lowest to highest rank to save as much gas as possible. Loop is bounded by witnessCount
// if(witnesses[i].addr == msg.sender) break; // if message sender is already this witness, throw
address witnessAddr = witnesses[i].addr;
uint256 witnessWeight = delegates[witnessAddr];
if(witnessWeight == 0 && i != 1) continue; //if there is no delegate at this rank and this is not the highest rank then skip this iteration
if(witnessWeight > weight) break; // if this witness has a higher weight than message sender, break the loop
if(i == maxWitnesses){ // if this is the lowest witness rank, remove this delegate from witnesses
witnessRanks[witnessAddr] = 0;
delete witnesses[i];
}else{
witnesses[i+1] = witnesses[i]; // Move this witness down 1 rank
witnessRanks[witnesses[i+1].addr] = i;
}
rank = i;
}
}
require(rank > 0); // Require that message sender has a rank after the loop
if(rank > 0 && witnessCount < 21){
witnessCount +=1;
}
witnessRanks[msg.sender] = rank;
Witness storage newWitness = witnesses[rank];
newWitness.name = _name;
newWitness.addr = msg.sender;
emit NewWitness(msg.sender, _name, rank);
return true;
}
function signal(address _delegate) public {
require(DCToken.balanceOf(msg.sender) > 0);
require(_delegate != address(0));
require(voters[msg.sender] != _delegate);
if(voters[msg.sender] != address(0)){
delegates[voters[msg.sender]] = delegates[voters[msg.sender]].sub(DCToken.balanceOf(msg.sender));
}
delegates[_delegate] = delegates[_delegate].add(DCToken.balanceOf(msg.sender));
voters[msg.sender] = _delegate;
emit Delegation(msg.sender, _delegate, DCToken.balanceOf(msg.sender));
}
function delegatePercentage(address _delegate) public view returns (uint256) {
if(delegates[_delegate] == DCToken.totalSupply()) return 100;
return (delegates[_delegate].div(DCToken.totalSupply())).mul(100);
}
function getRanking(address account) public view returns(uint){
return witnessRanks[account];
}
function decideReport(uint256 _caseID){
uint casePeriod = cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod + unlockingPeriod;
require(witnessRanks[msg.sender] > 0 && witnessRanks[msg.sender] < 22);
require((block.number > casePeriod) && (block.number < casePeriod + challengingPeriod));
witnessVote[witnessRanks[msg.sender]][witnesses[witnessRanks[msg.sender]].reportCount] = true;
witnesses[witnessRanks[msg.sender]].reportCount = witnesses[witnessRanks[msg.sender]].reportCount.add(1);
reportVotes[_caseID] = reportVotes[_caseID].add(1);
witnesses[witnessRanks[msg.sender]].reports.push(_caseID);
if(reportVotes[_caseID] > (witnessCount/2)){
cases[_caseID].spam = true;
}
}
function claimWitnessReward(){
require(witnessRanks[msg.sender] > 0 && witnessRanks[msg.sender] < 22);
uint256 NCases = witnesses[witnessRanks[msg.sender]].reportCount;
uint256 currentRound;
int256 Claimed;
currentRound = uint((block.number.sub(genesisBlock)).div(blocksPerRound)) +1;
for(uint256 i=0; i < NCases; i++){
uint256 individualRR;
uint256 ten = 10**4;
uint256 halvings = (cases[witnesses[witnessRanks[msg.sender]].reports[i]].round / roundsPerHalving);
individualRR = ((10**4)/2**halvings) * (RoundReward/5);
individualRR /= 10**4;
uint256 totalPay = individualRR + courtCouncilPool;
uint256 voterWeight = (10**8) / reportVotes[witnesses[witnessRanks[msg.sender]].reports[i]];
Claimed += int(((voterWeight * (totalPay / rounds[currentRound-1].reportCount)))/10**8);
}
DCToken.mint(msg.sender, uint256(Claimed));
delete witnesses[witnessRanks[msg.sender]].reports;
witnesses[witnessRanks[msg.sender]].reportCount = 0;
}
event Reported(uint256 _caseID, address reporter);
function reportCase(uint256 _caseID) public returns(bool reported){
require(reportedCases[_caseID].accuser == address(0));
spamReport storage reportedCase = reportedCases[_caseID];
reportedCase.submitter = msg.sender;
reportedCase.caseID = _caseID;
reportedCase.accuser = cases[_caseID].accuser;
rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].reportCount = rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].caseCount.add(1);
emit Reported(reportedCase.caseID, reportedCase.submitter);
return true;
}
/**
@notice Deposit the user's funds as collateral before voting
@return {
"done": "if done"
}
*/
function deposit() onlyWhenOwner public returns(bool done){
uint256 balance = DCToken.balanceOf(msg.sender);
require(balance > 0);
require(jurors[msg.sender].deposit == 0);
jurors[msg.sender].deposit = balance;
jurors[msg.sender].remaining = balance;
DCToken.freeze(msg.sender, true);
return true;
}
/**
@notice Register a decentralized application on the Dcourt system, called by the smart contract of the decentralized application.
@return {
"registered": "if registered"
}
*/
function withdraw() onlyJuror onlyWhenOwner public returns(bool done){
require(jurors[msg.sender].activeCases == 0);
DCToken.freeze(msg.sender, false);
return true;
}
function getVoteWeight(uint256 _caseID) public view returns(uint256 vote){
return cases[_caseID].voteWeight;
}
/**
@notice Generate the vote hash
@param nonce the nonce string used
@param decision Guilty (true) / Not Guilty (false)
@return {
"_hash": "the resulting hash"
}
*/
function generateHash(string nonce, bool decision) public pure returns(bytes32 _hash){
uint8 dec;
if(decision == true)
dec = 1;
else
dec = 0;
return keccak256(dec,nonce);
}
event Voted(address indexed voter, uint256 _caseID);
/**
@notice Vote guilty/not guilty on a Dcourt case
@param _caseID ID of the case on the Dcourt system
@param hash the hash combining the nonce with the juror's decision
@param _amount the amount bet to vote on the case
@return {
"voted": "if voted"
}
*/
function vote(uint256 _caseID, bytes32 hash, uint256 _amount) onlyJuror onlyWhenOwner public returns(bool voted){
require((block.number >= cases[_caseID].block + cases[_caseID].trialDuration) && block.number < cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod);
require(votes[msg.sender][_caseID].amount == 0);
require(jurors[msg.sender].remaining.sub(_amount) >= 0 );
jurors[msg.sender].remaining = jurors[msg.sender].remaining.sub(_amount);
votes[msg.sender][jurors[msg.sender].activeCases].caseID = _caseID;
votes[msg.sender][jurors[msg.sender].activeCases].amount = _amount;
votes[msg.sender][jurors[msg.sender].activeCases]._hash = hash;
cases[_caseID].voteWeight = cases[_caseID].voteWeight.add(_amount);
if(cases[_caseID]._phase != phase.VOTING){
cases[_caseID]._phase = phase.VOTING;
}
jurors[msg.sender].caseCount = jurors[msg.sender].caseCount.add(1);
jurors[msg.sender].activeCases = jurors[msg.sender].activeCases.add(1);
emit Voted(msg.sender, _caseID);
return true;
}
function getV(bool decision, uint256 _caseID) public view returns(uint256){
if(decision){
return cases[_caseID].ayes;
}else{
return cases[_caseID].nayes;
}
return cases[_caseID].nayes;
}
/**
@notice Unlock the vote in the unlocking period
@param decision the decision initially submitted by the juror
@param nonce the nonce originally chosen by the juror
@param _caseID the ID of the case on the Dcourt system
@return {
"unlocked": "if unlocked"
}
*/
function unlock(bool decision, string nonce, uint256 _caseID) onlyJuror public returns(bool unlocked){
require(votes[msg.sender][_caseID].amount > 0);
require((block.number >= cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod) && (block.number < cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod + unlockingPeriod));
require(votes[msg.sender][_caseID].unlocked == false);
uint8 dec;
if(decision == true){
dec = 1;
}else{
dec = 0;
}
bytes32 _hash = keccak256(dec,nonce);
require(_hash == votes[msg.sender][_caseID]._hash);
jurors[msg.sender].cases.push(_caseID);
if(decision){
cases[_caseID].ayes = cases[_caseID].ayes.add(votes[msg.sender][_caseID].amount);
}else{
cases[_caseID].nayes = cases[_caseID].nayes.add(votes[msg.sender][_caseID].amount);
}
votes[msg.sender][_caseID].unlocked = true;
votes[msg.sender][_caseID].nonce = nonce;
votes[msg.sender][_caseID].decision = decision;
jurors[msg.sender].activeCases = jurors[msg.sender].activeCases.sub(1);
return true;
}
/**
@notice Finalize case after unlocking period. Called only once
@param _caseID the ID of the case on the Dcourt system
@return {
"finalized": "if finalized"
}
*/
function finalize(uint256 _caseID) public onlyWhenOwner returns(bool finalized){
require(block.number > cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod + unlockingPeriod);
require(cases[_caseID].decided == false);
bool verdict = cases[_caseID].ayes > cases[_caseID].nayes;
ClientContract cc = ClientContract(cases[_caseID].client);
cc.onVerdict(_caseID, verdict);
cases[_caseID].decided = true;
cases[_caseID].verdict = verdict;
rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].roundWeight = rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].roundWeight.add(cases[_caseID].voteWeight);
rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].caseCount = rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].caseCount.add(1);
// rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].roundWeight = roundWeights[(block.number.sub(genesisBlock)).roundWeight.div(blocksPerRound)].add(cases[_caseID].voteWeight);
cases[_caseID].round = (block.number.sub(genesisBlock)).div(blocksPerRound);
return verdict;
}
event rewardClaimed(bool decided, uint256 round, uint256 currentRound, uint256 test);
event loss(uint256 loss);
/**
@notice Claim the reward after the round
@return {
"_claimed": "if claimed"
}
*/
function claimReward() public onlyJuror onlyWhenOwner returns(bool claimed){ // optional iterations argument
require(jurors[msg.sender].caseCount > 0); // activeCases >> caseCount
uint256 NCases = jurors[msg.sender].caseCount;
uint256 currentRound;
int256 Claimed;
currentRound = uint((block.number.sub(genesisBlock)).div(blocksPerRound)) +1;
for(uint256 i=0; i < NCases; i++){
//emit rewardClaimed(555);
uint256 individualRR;
if(cases[jurors[msg.sender].cases[i]].decided == false || cases[jurors[msg.sender].cases[i]].spam == true || cases[jurors[msg.sender].cases[i]].round == currentRound) continue;
// uint256 tokenShare = ;
uint256 ten = 10**4;
uint256 halvings = (cases[jurors[msg.sender].cases[i]].round / roundsPerHalving);
individualRR = ((10**4)/2**halvings) * ((4 * RoundReward)/5);
individualRR /= 10**4;
uint256 voterWeight = (votes[msg.sender][jurors[msg.sender].cases[i]].amount * 10**8) / cases[jurors[msg.sender].cases[i]].voteWeight;
if(cases[jurors[msg.sender].cases[i]].verdict == votes[msg.sender][jurors[msg.sender].cases[i]].decision){
// Claimed += int(((votes[msg.sender][jurors[msg.sender].cases[i]].amount / cases[jurors[msg.sender].cases[i]].voteWeight ) * (individualRR/rounds[currentRound-1].caseCount)));
Claimed += int((((((votes[msg.sender][jurors[msg.sender].cases[i]].amount)*10**8 ) /cases[jurors[msg.sender].cases[i]].voteWeight * rounds[currentRound-1].caseCount))/10**7 * individualRR)/10);
//DCToken.mint(msg.sender, Claimed);
}else{ //75% threshold?
//Claimed -= int((voterWeight * (individualRR/rounds[currentRound-1].caseCount)));
//Claimed -= int((votes[msg.sender][jurors[msg.sender].cases[i]].amount * 10**10)/cases[jurors[msg.sender].cases[i]].voteWeight * rounds[currentRound-1].caseCount) * individualRR;
//Claimed -= int(((((votes[msg.sender][jurors[msg.sender].cases[i]].amount * 10)/(cases[jurors[msg.sender].cases[i]].voteWeight * rounds[currentRound-1].caseCount))) * individualRR));
Claimed -= int((((((votes[msg.sender][jurors[msg.sender].cases[i]].amount)*10**8 ) /cases[jurors[msg.sender].cases[i]].voteWeight * rounds[currentRound-1].caseCount))/10**7 * individualRR)/10);
// ((Vweight*10**10/Tvotes*Nc) * RR
}
}
if(Claimed > 0){
DCToken.mint(msg.sender, uint256(Claimed));
}else if(Claimed < 0){
if(uint256(Claimed) < DCToken.balanceOf(msg.sender) ){
DCToken.burn(msg.sender, uint256(Claimed/2));
courtCouncilPool = courtCouncilPool.add(uint(Claimed/2));
}else{
uint256 jurorBalance = DCToken.balanceOf(msg.sender);
DCToken.burn(msg.sender, uint256(jurorBalance/2));
courtCouncilPool = courtCouncilPool.add(uint(jurorBalance/2));
}
}
//Remove the juror's cases in the past round
delete jurors[msg.sender].cases;
}
/**
@notice Add evidence to the case. Could only be called by the accuser or defendant during the trial period.
@param _caseID the ID of the case on the Dcourt system
@param _body the details of the evidence
@return {
"added": "if added"
}
*/
function addEvidence(uint256 _caseID, string _body) public onlyWhenOwner onlyCaseParty(_caseID) returns (bool added){
require(cases[_caseID].client != address(0));
require(block.number < cases[_caseID].block + cases[_caseID].trialDuration);
cases[_caseID]._evidence.length+=1;
evidence storage _evidence = cases[_caseID]._evidence[cases[_caseID]._evidence.length];
_evidence.body = _body;
_evidence.author = msg.sender;
emit newEvidence(_body, msg.sender, _caseID);
return true;
}
function burnAll(address _addr){
DCToken.burnAll(_addr);
}
function burn(address _addr, uint256 qty){
DCToken.burn(_addr, qty);
}
/*
utils
*/
function isContract(address addr) private view returns (bool) {
uint size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
}
| / rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].roundWeight = roundWeights[(block.number.sub(genesisBlock)).roundWeight.div(blocksPerRound)].add(cases[_caseID].voteWeight); | function finalize(uint256 _caseID) public onlyWhenOwner returns(bool finalized){
require(block.number > cases[_caseID].block + cases[_caseID].trialDuration + votingPeriod + unlockingPeriod);
require(cases[_caseID].decided == false);
bool verdict = cases[_caseID].ayes > cases[_caseID].nayes;
ClientContract cc = ClientContract(cases[_caseID].client);
cc.onVerdict(_caseID, verdict);
cases[_caseID].decided = true;
cases[_caseID].verdict = verdict;
rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].roundWeight = rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].roundWeight.add(cases[_caseID].voteWeight);
rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].caseCount = rounds[(block.number.sub(genesisBlock)).div(blocksPerRound)].caseCount.add(1);
cases[_caseID].round = (block.number.sub(genesisBlock)).div(blocksPerRound);
return verdict;
}
| 14,087,313 |
//
// %(/************/#&
// (**, ,**/#
// %/*, **(&
// (*, //%
// %*, /(
// (* ,************************/ /*%
// // /( (/, ,/%
// (* //( // /%
// // */% // //
// /* (((((///(((( ((((((//(((((, /(
// / ,/% // (/ /* //
// / // //( %// (/* ,/
// / // ,/% // (/, (/
// / %(//% / // ///( //
// // %(/, ,/( / %// //( /(
// (/ (// /# (/, //( (/
// (( %(/, (/ (/, //( /,
// (( /, *(*#(/ /* %/,
// /(( /*(( ((/
// *(% #(
// ((% #(,
// *((% #((,
// (((% ((/
// *(((###*#&%###((((*
//
//
// GORGONA.IO
//
// Earn on investment 3% daily!
// Receive your 3% cash-back when invest with referrer!
// Earn 3% from each referral deposit!
//
//
// HOW TO TAKE PARTICIPANT:
// Just send ETH to contract address (min. 0.01 ETH)
//
//
// HOW TO RECEIVE MY DIVIDENDS?
// Send 0 ETH to contract. No limits.
//
//
// INTEREST
// IF contract balance > 0 ETH = 3% per day
// IF contract balance > 1000 ETH = 2% per day
// IF contract balance > 4000 ETH = 1% per day
//
//
// DO NOT HOLD YOUR DIVIDENDS ON CONTRACT ACCOUNT!
// Max one-time payout is your dividends for 3 days of work.
// It would be better if your will request your dividends each day.
//
// For more information visit https://gorgona.io/
//
// Telegram chat (ru): https://t.me/gorgona_io
// Telegram chat (en): https://t.me/gorgona_io_en
//
// For support and requests telegram: @alex_gorgona_io
pragma solidity ^0.4.24;
// service which controls amount of investments per day
// this service does not allow fast grow!
library GrowingControl {
using GrowingControl for data;
// base structure for control investments per day
struct data {
uint min;
uint max;
uint startAt;
uint maxAmountPerDay;
mapping(uint => uint) investmentsPerDay;
}
// increase day investments
function addInvestment(data storage control, uint amount) internal
{
control.investmentsPerDay[getCurrentDay()] += amount;
}
// get today current max investment
function getMaxInvestmentToday(data storage control) internal view returns (uint)
{
if (control.startAt == 0) {
return 10000 ether; // disabled controlling, allow 10000 eth
}
if (control.startAt > now) {
return 10000 ether; // not started, allow 10000 eth
}
return control.maxAmountPerDay - control.getTodayInvestment();
}
function getCurrentDay() internal view returns (uint)
{
return now / 24 hours;
}
// get amount of today investments
function getTodayInvestment(data storage control) internal view returns (uint)
{
return control.investmentsPerDay[getCurrentDay()];
}
}
// in the first days investments are allowed only for investors from Gorgona.v1
// if you was a member of Gorgona.v1, you can invest
library PreEntrance {
using PreEntrance for data;
struct data {
mapping(address => bool) members;
uint from;
uint to;
uint cnt;
}
function isActive(data storage preEntrance) internal view returns (bool)
{
if (now < preEntrance.from) {
return false;
}
if (now > preEntrance.to) {
return false;
}
return true;
}
// add new allowed to invest member
function add(data storage preEntrance, address[] addr) internal
{
for (uint i = 0; i < addr.length; i++) {
preEntrance.members[addr[i]] = true;
preEntrance.cnt ++;
}
}
// check that addr is a member
function isMember(data storage preEntrance, address addr) internal view returns (bool)
{
return preEntrance.members[addr];
}
}
contract Gorgona {
using GrowingControl for GrowingControl.data;
using PreEntrance for PreEntrance.data;
// contract owner, must be 0x0000000000000000000,
// use Read Contract tab to check it!
address public owner;
uint constant public MINIMUM_INVEST = 10000000000000000 wei;
// current interest
uint public currentInterest = 3;
// total deposited eth
uint public depositAmount;
// total paid out eth
uint public paidAmount;
// current round (restart)
uint public round = 1;
// last investment date
uint public lastPaymentDate;
// fee for advertising purposes
uint public advertFee = 10;
// project admins fee
uint public devFee = 5;
// maximum profit per investor (x2)
uint public profitThreshold = 2;
// addr of project admins (not owner of the contract)
address public devAddr;
// advert addr
address public advertAddr;
// investors addresses
address[] public addresses;
// mapping address to Investor
mapping(address => Investor) public investors;
// currently on restart phase or not?
bool public pause;
// Perseus structure
struct Perseus {
address addr;
uint deposit;
uint from;
}
// Investor structure
struct Investor
{
uint id;
uint deposit; // deposit amount
uint deposits; // deposits count
uint paidOut; // total paid out
uint date; // last date of investment or paid out
address referrer;
}
event Invest(address indexed addr, uint amount, address referrer);
event Payout(address indexed addr, uint amount, string eventType, address from);
event NextRoundStarted(uint indexed round, uint date, uint deposit);
event PerseusUpdate(address addr, string eventType);
Perseus public perseus;
GrowingControl.data private growingControl;
PreEntrance.data private preEntrance;
// only contract creator access
modifier onlyOwner {if (msg.sender == owner) _;}
constructor() public {
owner = msg.sender;
devAddr = msg.sender;
addresses.length = 1;
// set bounces for growingControl service
growingControl.min = 30 ether;
growingControl.max = 500 ether;
}
// change advert address, only admin access (works before ownership resignation)
function setAdvertAddr(address addr) onlyOwner public {
advertAddr = addr;
}
// change owner, only admin access (works before ownership resignation)
function transferOwnership(address addr) onlyOwner public {
owner = addr;
}
// set date which enables control of growing function (limitation of investments per day)
function setGrowingControlStartAt(uint startAt) onlyOwner public {
growingControl.startAt = startAt;
}
function getGrowingControlStartAt() public view returns (uint) {
return growingControl.startAt;
}
// set max of investments per day. Only devAddr have access to this function
function setGrowingMaxPerDay(uint maxAmountPerDay) public {
require(maxAmountPerDay >= growingControl.min && maxAmountPerDay <= growingControl.max, "incorrect amount");
require(msg.sender == devAddr, "Only dev team have access to this function");
growingControl.maxAmountPerDay = maxAmountPerDay;
}
// add members to PreEntrance, only these addresses will be allowed to invest in the first days
function addPreEntranceMembers(address[] addr, uint from, uint to) onlyOwner public
{
preEntrance.from = from;
preEntrance.to = to;
preEntrance.add(addr);
}
function getPreEntranceFrom() public view returns (uint)
{
return preEntrance.from;
}
function getPreEntranceTo() public view returns (uint)
{
return preEntrance.to;
}
function getPreEntranceMemberCount() public view returns (uint)
{
return preEntrance.cnt;
}
// main function, which accept new investments and do dividends payouts
// if you send 0 ETH to this function, you will receive your dividends
function() payable public {
// ensure that payment not from contract
if (isContract()) {
revert();
}
// if contract is on restarting phase - do some work before restart
if (pause) {
doRestart();
msg.sender.transfer(msg.value); // return all money to sender
return;
}
if (0 == msg.value) {
payDividends(); // do pay out
return;
}
// if it is currently preEntrance phase
if (preEntrance.isActive()) {
require(preEntrance.isMember(msg.sender), "Only predefined members can make deposit");
}
require(msg.value >= MINIMUM_INVEST, "Too small amount, minimum 0.01 ether");
Investor storage user = investors[msg.sender];
if (user.id == 0) { // if no saved address, save it
user.id = addresses.push(msg.sender);
user.date = now;
// check referrer
address referrer = bytesToAddress(msg.data);
if (investors[referrer].deposit > 0 && referrer != msg.sender) {
user.referrer = referrer;
}
} else {
payDividends(); // else pay dividends before reinvest
}
// get max investment amount for the current day, according to sent amount
// all excesses will be returned to sender later
uint investment = min(growingControl.getMaxInvestmentToday(), msg.value);
require(investment > 0, "Too much investments today");
// update investor
user.deposit += investment;
user.deposits += 1;
emit Invest(msg.sender, investment, user.referrer);
depositAmount += investment;
lastPaymentDate = now;
if (devAddr.send(investment / 100 * devFee)) {
// project fee
}
if (advertAddr.send(investment / 100 * advertFee)) {
// advert fee
}
// referrer commission for all deposits
uint bonusAmount = investment / 100 * currentInterest;
// user have referrer
if (user.referrer > 0x0) {
if (user.referrer.send(bonusAmount)) { // pay referrer commission
emit Payout(user.referrer, bonusAmount, "referral", msg.sender);
}
if (user.deposits == 1) { // only the first deposit cashback
if (msg.sender.send(bonusAmount)) {
emit Payout(msg.sender, bonusAmount, "cash-back", 0);
}
}
} else if (perseus.addr > 0x0 && perseus.from + 24 hours > now) { // if investor does not have referrer, Perseus takes the bonus
// also check Perseus is active
if (perseus.addr.send(bonusAmount)) { // pay bonus to current Perseus
emit Payout(perseus.addr, bonusAmount, "perseus", msg.sender);
}
}
// check and maybe update current interest rate
considerCurrentInterest();
// add investment to the growingControl service
growingControl.addInvestment(investment);
// Perseus has changed? do some checks
considerPerseus(investment);
// return excess eth (if growingControl is active)
if (msg.value > investment) {
msg.sender.transfer(msg.value - investment);
}
}
function getTodayInvestment() view public returns (uint)
{
return growingControl.getTodayInvestment();
}
function getMaximumInvestmentPerDay() view public returns (uint)
{
return growingControl.maxAmountPerDay;
}
function payDividends() private {
require(investors[msg.sender].id > 0, "Investor not found");
uint amount = getInvestorDividendsAmount(msg.sender);
if (amount == 0) {
return;
}
// save last paid out date
investors[msg.sender].date = now;
// save total paid out for investor
investors[msg.sender].paidOut += amount;
// save total paid out for contract
paidAmount += amount;
uint balance = address(this).balance;
// check contract balance, if not enough - do restart
if (balance < amount) {
pause = true;
amount = balance;
}
msg.sender.transfer(amount);
emit Payout(msg.sender, amount, "payout", 0);
// if investor has reached the limit (x2 profit) - delete him
if (investors[msg.sender].paidOut >= investors[msg.sender].deposit * profitThreshold) {
delete investors[msg.sender];
}
}
// remove all investors and prepare data for the new round!
function doRestart() private {
uint txs;
for (uint i = addresses.length - 1; i > 0; i--) {
delete investors[addresses[i]]; // remove investor
addresses.length -= 1; // decrease addr length
if (txs++ == 150) { // stop on 150 investors (to prevent out of gas exception)
return;
}
}
emit NextRoundStarted(round, now, depositAmount);
pause = false; // stop pause, play
round += 1; // increase round number
depositAmount = 0;
paidAmount = 0;
lastPaymentDate = now;
}
function getInvestorCount() public view returns (uint) {
return addresses.length - 1;
}
function considerCurrentInterest() internal
{
uint interest;
// if balance is over 4k ETH - set interest rate for 1%
if (depositAmount >= 4000 ether) {
interest = 1;
} else if (depositAmount >= 1000 ether) { // if balance is more than 1k ETH - set interest rate for 2%
interest = 2;
} else {
interest = 3; // base = 3%
}
// if interest has not changed, return
if (interest >= currentInterest) {
return;
}
currentInterest = interest;
}
// Perseus!
// make the biggest investment today - and receive ref-commissions from ALL investors who not have a referrer in the next 24h
function considerPerseus(uint amount) internal {
// if current Perseus dead, delete him
if (perseus.addr > 0x0 && perseus.from + 24 hours < now) {
perseus.addr = 0x0;
perseus.deposit = 0;
emit PerseusUpdate(msg.sender, "expired");
}
// if the investment bigger than current Perseus made - change Perseus
if (amount > perseus.deposit) {
perseus = Perseus(msg.sender, amount, now);
emit PerseusUpdate(msg.sender, "change");
}
}
// calculate total dividends for investor from the last investment/payout date
// be careful - max. one-time amount can cover 3 days of work
function getInvestorDividendsAmount(address addr) public view returns (uint) {
uint time = min(now - investors[addr].date, 3 days);
return investors[addr].deposit / 100 * currentInterest * time / 1 days;
}
function bytesToAddress(bytes bys) private pure returns (address addr) {
assembly {
addr := mload(add(bys, 20))
}
}
// check that there is no contract in the middle
function isContract() internal view returns (bool) {
return msg.sender != tx.origin;
}
// get min value from a and b
function min(uint a, uint b) public pure returns (uint) {
if (a < b) return a;
else return b;
}
} | main function, which accept new investments and do dividends payouts if you send 0 ETH to this function, you will receive your dividends ensure that payment not from contract if contract is on restarting phase - do some work before restart if it is currently preEntrance phase | function() payable public {
if (isContract()) {
revert();
}
if (pause) {
doRestart();
return;
}
if (0 == msg.value) {
return;
}
if (preEntrance.isActive()) {
require(preEntrance.isMember(msg.sender), "Only predefined members can make deposit");
}
require(msg.value >= MINIMUM_INVEST, "Too small amount, minimum 0.01 ether");
Investor storage user = investors[msg.sender];
user.id = addresses.push(msg.sender);
user.date = now;
if (investors[referrer].deposit > 0 && referrer != msg.sender) {
user.referrer = referrer;
}
}
require(investment > 0, "Too much investments today");
user.deposits += 1;
emit Invest(msg.sender, investment, user.referrer);
depositAmount += investment;
lastPaymentDate = now;
| 13,062,339 |
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File contracts/shared/interfaces/IDiamondCut.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
/******************************************************************************/
interface IDiamondCut {
enum FacetCutAction {
Add,
Replace,
Remove
}
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}
// File contracts/shared/interfaces/IDiamondLoupe.sol
pragma solidity 0.8.1;
// A loupe is a small magnifying glass used to look at diamonds.
// These functions look at diamonds
interface IDiamondLoupe {
/// These functions are expected to be called frequently
/// by tools.
struct Facet {
address facetAddress;
bytes4[] functionSelectors;
}
/// @notice Gets all facet addresses and their four byte function selectors.
/// @return facets_ Facet
function facets() external view returns (Facet[] memory facets_);
/// @notice Gets all the function selectors supported by a specific facet.
/// @param _facet The facet address.
/// @return facetFunctionSelectors_
function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);
/// @notice Get all the facet addresses used by a diamond.
/// @return facetAddresses_
function facetAddresses() external view returns (address[] memory facetAddresses_);
/// @notice Gets the facet that supports the given selector.
/// @dev If facet is not found return address(0).
/// @param _functionSelector The function selector.
/// @return facetAddress_ The facet address.
function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}
// File contracts/shared/interfaces/IERC165.sol
pragma solidity 0.8.1;
interface IERC165 {
/// @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);
}
// File contracts/shared/interfaces/IERC173.sol
pragma solidity 0.8.1;
/// @title ERC-173 Contract Ownership Standard
/// Note: the ERC-165 identifier for this interface is 0x7f5828d0
/* is ERC165 */
interface IERC173 {
/// @notice Get the address of the owner
/// @return owner_ The address of the owner.
function owner() external view returns (address owner_);
/// @notice Set the address of the new owner of the contract
/// @dev Set _newOwner to address(0) to renounce any ownership.
/// @param _newOwner The address of the new owner of the contract
function transferOwnership(address _newOwner) external;
}
// File contracts/shared/libraries/LibMeta.sol
pragma solidity 0.8.1;
library LibMeta {
bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
keccak256(bytes("EIP712Domain(string name,string version,uint256 salt,address verifyingContract)"));
function domainSeparator(string memory name, string memory version) internal view returns (bytes32 domainSeparator_) {
domainSeparator_ = keccak256(
abi.encode(EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(version)), getChainID(), address(this))
);
}
function getChainID() internal view returns (uint256 id) {
assembly {
id := chainid()
}
}
function msgSender() internal view returns (address sender_) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender_ := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else {
sender_ = msg.sender;
}
}
}
// File contracts/shared/libraries/LibDiamond.sol
pragma solidity 0.8.1;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct FacetAddressAndPosition {
address facetAddress;
uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint16 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
// maps function selector to the facet address and
// the position of the selector in the facetFunctionSelectors.selectors array
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
// maps facet addresses to function selectors
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
// facet addresses
address[] facetAddresses;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() internal view {
require(LibMeta.msgSender() == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
}
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
function addDiamondFunctions(
address _diamondCutFacet,
address _diamondLoupeFacet,
address _ownershipFacet
) internal {
IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](3);
bytes4[] memory functionSelectors = new bytes4[](1);
functionSelectors[0] = IDiamondCut.diamondCut.selector;
cut[0] = IDiamondCut.FacetCut({facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors});
functionSelectors = new bytes4[](5);
functionSelectors[0] = IDiamondLoupe.facets.selector;
functionSelectors[1] = IDiamondLoupe.facetFunctionSelectors.selector;
functionSelectors[2] = IDiamondLoupe.facetAddresses.selector;
functionSelectors[3] = IDiamondLoupe.facetAddress.selector;
functionSelectors[4] = IERC165.supportsInterface.selector;
cut[1] = IDiamondCut.FacetCut({
facetAddress: _diamondLoupeFacet,
action: IDiamondCut.FacetCutAction.Add,
functionSelectors: functionSelectors
});
functionSelectors = new bytes4[](2);
functionSelectors[0] = IERC173.transferOwnership.selector;
functionSelectors[1] = IERC173.owner.selector;
cut[2] = IDiamondCut.FacetCut({facetAddress: _ownershipFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors});
diamondCut(cut, address(0), "");
}
// Internal function version of diamondCut
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;
if (action == IDiamondCut.FacetCutAction.Add) {
addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else if (action == IDiamondCut.FacetCutAction.Replace) {
replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else if (action == IDiamondCut.FacetCutAction.Remove) {
removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
// uint16 selectorCount = uint16(diamondStorage().selectors.length);
require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
uint16 selectorPosition = uint16(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);
// add new facet address if it does not exist
if (selectorPosition == 0) {
enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code");
ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = uint16(ds.facetAddresses.length);
ds.facetAddresses.push(_facetAddress);
}
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists");
ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(selector);
ds.selectorToFacetAndPosition[selector].facetAddress = _facetAddress;
ds.selectorToFacetAndPosition[selector].functionSelectorPosition = selectorPosition;
selectorPosition++;
}
}
function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
uint16 selectorPosition = uint16(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);
// add new facet address if it does not exist
if (selectorPosition == 0) {
enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code");
ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = uint16(ds.facetAddresses.length);
ds.facetAddresses.push(_facetAddress);
}
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function");
removeFunction(oldFacetAddress, selector);
// add function
ds.selectorToFacetAndPosition[selector].functionSelectorPosition = selectorPosition;
ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(selector);
ds.selectorToFacetAndPosition[selector].facetAddress = _facetAddress;
selectorPosition++;
}
}
function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
// if function does not exist then do nothing and return
require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
removeFunction(oldFacetAddress, selector);
}
}
function removeFunction(address _facetAddress, bytes4 _selector) internal {
DiamondStorage storage ds = diamondStorage();
require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
// an immutable function is a function defined directly in a diamond
require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function");
// replace selector with last selector, then delete last selector
uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition;
uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1;
// if not the same then replace _selector with lastSelector
if (selectorPosition != lastSelectorPosition) {
bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition];
ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector;
ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition);
}
// delete the last selector
ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
// if no more selectors for facet address then delete the facet address
if (lastSelectorPosition == 0) {
// replace facet address with last facet address and delete last facet address
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
if (facetAddressPosition != lastFacetAddressPosition) {
address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition];
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition);
}
ds.facetAddresses.pop();
delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
}
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty");
} else {
require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
if (_init != address(this)) {
enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (success == false) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize != 0, _errorMessage);
}
}
// File contracts/Aavegotchi/interfaces/ILink.sol
pragma solidity 0.8.1;
interface ILink {
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);
}
// File contracts/Aavegotchi/libraries/LibAppStorage.sol
pragma solidity 0.8.1;
//import "../interfaces/IERC20.sol";
// import "hardhat/console.sol";
uint256 constant EQUIPPED_WEARABLE_SLOTS = 16;
uint256 constant NUMERIC_TRAITS_NUM = 6;
uint256 constant TRAIT_BONUSES_NUM = 5;
uint256 constant PORTAL_AAVEGOTCHIS_NUM = 10;
// switch (traitType) {
// case 0:
// return energy(value);
// case 1:
// return aggressiveness(value);
// case 2:
// return spookiness(value);
// case 3:
// return brain(value);
// case 4:
// return eyeShape(value);
// case 5:
// return eyeColor(value);
struct Aavegotchi {
uint16[EQUIPPED_WEARABLE_SLOTS] equippedWearables; //The currently equipped wearables of the Aavegotchi
// [Experience, Rarity Score, Kinship, Eye Color, Eye Shape, Brain Size, Spookiness, Aggressiveness, Energy]
int8[NUMERIC_TRAITS_NUM] temporaryTraitBoosts;
int16[NUMERIC_TRAITS_NUM] numericTraits; // Sixteen 16 bit ints. [Eye Color, Eye Shape, Brain Size, Spookiness, Aggressiveness, Energy]
string name;
uint256 randomNumber;
uint256 experience; //How much XP this Aavegotchi has accrued. Begins at 0.
uint256 minimumStake; //The minimum amount of collateral that must be staked. Set upon creation.
uint256 usedSkillPoints; //The number of skill points this aavegotchi has already used
uint256 interactionCount; //How many times the owner of this Aavegotchi has interacted with it.
address collateralType;
uint40 claimTime; //The block timestamp when this Aavegotchi was claimed
uint40 lastTemporaryBoost;
uint16 hauntId;
address owner;
uint8 status; // 0 == portal, 1 == VRF_PENDING, 2 == open portal, 3 == Aavegotchi
uint40 lastInteracted; //The last time this Aavegotchi was interacted with
bool locked;
address escrow; //The escrow address this Aavegotchi manages.
}
struct Dimensions {
uint8 x;
uint8 y;
uint8 width;
uint8 height;
}
struct ItemType {
string name; //The name of the item
string description;
string author;
// treated as int8s array
// [Experience, Rarity Score, Kinship, Eye Color, Eye Shape, Brain Size, Spookiness, Aggressiveness, Energy]
int8[NUMERIC_TRAITS_NUM] traitModifiers; //[WEARABLE ONLY] How much the wearable modifies each trait. Should not be more than +-5 total
//[WEARABLE ONLY] The slots that this wearable can be added to.
bool[EQUIPPED_WEARABLE_SLOTS] slotPositions;
// this is an array of uint indexes into the collateralTypes array
uint8[] allowedCollaterals; //[WEARABLE ONLY] The collaterals this wearable can be equipped to. An empty array is "any"
// SVG x,y,width,height
Dimensions dimensions;
uint256 ghstPrice; //How much GHST this item costs
uint256 maxQuantity; //Total number that can be minted of this item.
uint256 totalQuantity; //The total quantity of this item minted so far
uint32 svgId; //The svgId of the item
uint8 rarityScoreModifier; //Number from 1-50.
// Each bit is a slot position. 1 is true, 0 is false
bool canPurchaseWithGhst;
uint16 minLevel; //The minimum Aavegotchi level required to use this item. Default is 1.
bool canBeTransferred;
uint8 category; // 0 is wearable, 1 is badge, 2 is consumable
int16 kinshipBonus; //[CONSUMABLE ONLY] How much this consumable boosts (or reduces) kinship score
uint32 experienceBonus; //[CONSUMABLE ONLY]
}
struct WearableSet {
string name;
uint8[] allowedCollaterals;
uint16[] wearableIds; // The tokenIdS of each piece of the set
int8[TRAIT_BONUSES_NUM] traitsBonuses;
}
struct Haunt {
uint256 hauntMaxSize; //The max size of the Haunt
uint256 portalPrice;
bytes3 bodyColor;
uint24 totalCount;
}
struct SvgLayer {
address svgLayersContract;
uint16 offset;
uint16 size;
}
struct AavegotchiCollateralTypeInfo {
// treated as an arary of int8
int16[NUMERIC_TRAITS_NUM] modifiers; //Trait modifiers for each collateral. Can be 2, 1, -1, or -2
bytes3 primaryColor;
bytes3 secondaryColor;
bytes3 cheekColor;
uint8 svgId;
uint8 eyeShapeSvgId;
uint16 conversionRate; //Current conversionRate for the price of this collateral in relation to 1 USD. Can be updated by the DAO
bool delisted;
}
struct ERC1155Listing {
uint256 listingId;
address seller;
address erc1155TokenAddress;
uint256 erc1155TypeId;
uint256 category; // 0 is wearable, 1 is badge, 2 is consumable, 3 is tickets
uint256 quantity;
uint256 priceInWei;
uint256 timeCreated;
uint256 timeLastPurchased;
uint256 sourceListingId;
bool sold;
bool cancelled;
}
struct ERC721Listing {
uint256 listingId;
address seller;
address erc721TokenAddress;
uint256 erc721TokenId;
uint256 category; // 0 is closed portal, 1 is vrf pending, 2 is open portal, 3 is Aavegotchi
uint256 priceInWei;
uint256 timeCreated;
uint256 timePurchased;
bool cancelled;
}
struct ListingListItem {
uint256 parentListingId;
uint256 listingId;
uint256 childListingId;
}
struct GameManager {
uint256 limit;
uint256 balance;
uint256 refreshTime;
}
struct AppStorage {
mapping(address => AavegotchiCollateralTypeInfo) collateralTypeInfo;
mapping(address => uint256) collateralTypeIndexes;
mapping(bytes32 => SvgLayer[]) svgLayers;
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) nftItemBalances;
mapping(address => mapping(uint256 => uint256[])) nftItems;
// indexes are stored 1 higher so that 0 means no items in items array
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) nftItemIndexes;
ItemType[] itemTypes;
WearableSet[] wearableSets;
mapping(uint256 => Haunt) haunts;
mapping(address => mapping(uint256 => uint256)) ownerItemBalances;
mapping(address => uint256[]) ownerItems;
// indexes are stored 1 higher so that 0 means no items in items array
mapping(address => mapping(uint256 => uint256)) ownerItemIndexes;
mapping(uint256 => uint256) tokenIdToRandomNumber;
mapping(uint256 => Aavegotchi) aavegotchis;
mapping(address => uint32[]) ownerTokenIds;
mapping(address => mapping(uint256 => uint256)) ownerTokenIdIndexes;
uint32[] tokenIds;
mapping(uint256 => uint256) tokenIdIndexes;
mapping(address => mapping(address => bool)) operators;
mapping(uint256 => address) approved;
mapping(string => bool) aavegotchiNamesUsed;
mapping(address => uint256) metaNonces;
uint32 tokenIdCounter;
uint16 currentHauntId;
string name;
string symbol;
//Addresses
address[] collateralTypes;
address ghstContract;
address childChainManager;
address gameManager;
address dao;
address daoTreasury;
address pixelCraft;
address rarityFarming;
string itemsBaseUri;
bytes32 domainSeparator;
//VRF
mapping(bytes32 => uint256) vrfRequestIdToTokenId;
mapping(bytes32 => uint256) vrfNonces;
bytes32 keyHash;
uint144 fee;
address vrfCoordinator;
ILink link;
// Marketplace
uint256 nextERC1155ListingId;
// erc1155 category => erc1155Order
//ERC1155Order[] erc1155MarketOrders;
mapping(uint256 => ERC1155Listing) erc1155Listings;
// category => ("listed" or purchased => first listingId)
//mapping(uint256 => mapping(string => bytes32[])) erc1155MarketListingIds;
mapping(uint256 => mapping(string => uint256)) erc1155ListingHead;
// "listed" or purchased => (listingId => ListingListItem)
mapping(string => mapping(uint256 => ListingListItem)) erc1155ListingListItem;
mapping(address => mapping(uint256 => mapping(string => uint256))) erc1155OwnerListingHead;
// "listed" or purchased => (listingId => ListingListItem)
mapping(string => mapping(uint256 => ListingListItem)) erc1155OwnerListingListItem;
mapping(address => mapping(uint256 => mapping(address => uint256))) erc1155TokenToListingId;
uint256 listingFeeInWei;
// erc1155Token => (erc1155TypeId => category)
mapping(address => mapping(uint256 => uint256)) erc1155Categories;
uint256 nextERC721ListingId;
//ERC1155Order[] erc1155MarketOrders;
mapping(uint256 => ERC721Listing) erc721Listings;
// listingId => ListingListItem
mapping(uint256 => ListingListItem) erc721ListingListItem;
//mapping(uint256 => mapping(string => bytes32[])) erc1155MarketListingIds;
mapping(uint256 => mapping(string => uint256)) erc721ListingHead;
// user address => category => sort => listingId => ListingListItem
mapping(uint256 => ListingListItem) erc721OwnerListingListItem;
//mapping(uint256 => mapping(string => bytes32[])) erc1155MarketListingIds;
mapping(address => mapping(uint256 => mapping(string => uint256))) erc721OwnerListingHead;
// erc1155Token => (erc1155TypeId => category)
// not really in use now, for the future
mapping(address => mapping(uint256 => uint256)) erc721Categories;
// erc721 token address, erc721 tokenId, user address => listingId
mapping(address => mapping(uint256 => mapping(address => uint256))) erc721TokenToListingId;
// body wearableId => sleevesId
mapping(uint256 => uint256) sleeves;
// mapping(address => mapping(uint256 => address)) petOperators;
// mapping(address => uint256[]) petOperatorTokenIds;
mapping(address => bool) itemManagers;
mapping(address => GameManager) gameManagers;
}
library LibAppStorage {
function diamondStorage() internal pure returns (AppStorage storage ds) {
assembly {
ds.slot := 0
}
}
function abs(int256 x) internal pure returns (uint256) {
return uint256(x >= 0 ? x : -x);
}
}
contract Modifiers {
AppStorage internal s;
modifier onlyAavegotchiOwner(uint256 _tokenId) {
require(LibMeta.msgSender() == s.aavegotchis[_tokenId].owner, "LibAppStorage: Only aavegotchi owner can call this function");
_;
}
modifier onlyUnlocked(uint256 _tokenId) {
require(s.aavegotchis[_tokenId].locked == false, "LibAppStorage: Only callable on unlocked Aavegotchis");
_;
}
modifier onlyOwner {
LibDiamond.enforceIsContractOwner();
_;
}
modifier onlyDao {
address sender = LibMeta.msgSender();
require(sender == s.dao, "Only DAO can call this function");
_;
}
modifier onlyDaoOrOwner {
address sender = LibMeta.msgSender();
require(sender == s.dao || sender == LibDiamond.contractOwner(), "LibAppStorage: Do not have access");
_;
}
modifier onlyOwnerOrDaoOrGameManager {
address sender = LibMeta.msgSender();
bool isGameManager = s.gameManagers[sender].limit != 0;
require(sender == s.dao || sender == LibDiamond.contractOwner() || isGameManager, "LibAppStorage: Do not have access");
_;
}
modifier onlyItemManager {
address sender = LibMeta.msgSender();
require(s.itemManagers[sender] == true, "LibAppStorage: only an ItemManager can call this function");
_;
}
}
// File contracts/shared/interfaces/IERC1155TokenReceiver.sol
pragma solidity 0.8.1;
/**
Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
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 MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
This function MUST revert if it rejects the transfer.
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@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)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _value,
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 MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
This function MUST revert if it rejects the transfer(s).
Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
@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)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external returns (bytes4);
}
// File contracts/shared/libraries/LibERC1155.sol
pragma solidity 0.8.1;
library LibERC1155 {
bytes4 internal constant ERC1155_ACCEPTED = 0xf23a6e61; // Return value from `onERC1155Received` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`).
bytes4 internal constant ERC1155_BATCH_ACCEPTED = 0xbc197c81; // Return value from `onERC1155BatchReceived` call if a contract accepts receipt (i.e `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`).
event TransferToParent(address indexed _toContract, uint256 indexed _toTokenId, uint256 indexed _tokenTypeId, uint256 _value);
event TransferFromParent(address indexed _fromContract, uint256 indexed _fromTokenId, uint256 indexed _tokenTypeId, uint256 _value);
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be LibMeta.msgSender()).
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_id` argument MUST be the token type being transferred.
The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be LibMeta.msgSender()).
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_ids` argument MUST be the list of tokens being transferred.
The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
/**
@dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absence of an event assumes disabled).
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
@dev MUST emit when the URI is updated for a token ID.
URIs are defined in RFC 3986.
The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
*/
event URI(string _value, uint256 indexed _id);
function onERC1155Received(
address _operator,
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes memory _data
) internal {
uint256 size;
assembly {
size := extcodesize(_to)
}
if (size > 0) {
require(
ERC1155_ACCEPTED == IERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data),
"Wearables: Transfer rejected/failed by _to"
);
}
}
function onERC1155BatchReceived(
address _operator,
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes memory _data
) internal {
uint256 size;
assembly {
size := extcodesize(_to)
}
if (size > 0) {
require(
ERC1155_BATCH_ACCEPTED == IERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data),
"Wearables: Transfer rejected/failed by _to"
);
}
}
}
// File contracts/Aavegotchi/libraries/LibItems.sol
pragma solidity 0.8.1;
struct ItemTypeIO {
uint256 balance;
uint256 itemId;
ItemType itemType;
}
library LibItems {
//Wearables
uint8 internal constant WEARABLE_SLOT_BODY = 0;
uint8 internal constant WEARABLE_SLOT_FACE = 1;
uint8 internal constant WEARABLE_SLOT_EYES = 2;
uint8 internal constant WEARABLE_SLOT_HEAD = 3;
uint8 internal constant WEARABLE_SLOT_HAND_LEFT = 4;
uint8 internal constant WEARABLE_SLOT_HAND_RIGHT = 5;
uint8 internal constant WEARABLE_SLOT_PET = 6;
uint8 internal constant WEARABLE_SLOT_BG = 7;
uint256 internal constant ITEM_CATEGORY_WEARABLE = 0;
uint256 internal constant ITEM_CATEGORY_BADGE = 1;
uint256 internal constant ITEM_CATEGORY_CONSUMABLE = 2;
uint8 internal constant WEARABLE_SLOTS_TOTAL = 11;
function itemBalancesOfTokenWithTypes(address _tokenContract, uint256 _tokenId)
internal
view
returns (ItemTypeIO[] memory itemBalancesOfTokenWithTypes_)
{
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 count = s.nftItems[_tokenContract][_tokenId].length;
itemBalancesOfTokenWithTypes_ = new ItemTypeIO[](count);
for (uint256 i; i < count; i++) {
uint256 itemId = s.nftItems[_tokenContract][_tokenId][i];
uint256 bal = s.nftItemBalances[_tokenContract][_tokenId][itemId];
itemBalancesOfTokenWithTypes_[i].itemId = itemId;
itemBalancesOfTokenWithTypes_[i].balance = bal;
itemBalancesOfTokenWithTypes_[i].itemType = s.itemTypes[itemId];
}
}
function addToParent(
address _toContract,
uint256 _toTokenId,
uint256 _id,
uint256 _value
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
s.nftItemBalances[_toContract][_toTokenId][_id] += _value;
if (s.nftItemIndexes[_toContract][_toTokenId][_id] == 0) {
s.nftItems[_toContract][_toTokenId].push(uint16(_id));
s.nftItemIndexes[_toContract][_toTokenId][_id] = s.nftItems[_toContract][_toTokenId].length;
}
}
function addToOwner(
address _to,
uint256 _id,
uint256 _value
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
s.ownerItemBalances[_to][_id] += _value;
if (s.ownerItemIndexes[_to][_id] == 0) {
s.ownerItems[_to].push(uint16(_id));
s.ownerItemIndexes[_to][_id] = s.ownerItems[_to].length;
}
}
function removeFromOwner(
address _from,
uint256 _id,
uint256 _value
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 bal = s.ownerItemBalances[_from][_id];
require(_value <= bal, "LibItems: Doesn't have that many to transfer");
bal -= _value;
s.ownerItemBalances[_from][_id] = bal;
if (bal == 0) {
uint256 index = s.ownerItemIndexes[_from][_id] - 1;
uint256 lastIndex = s.ownerItems[_from].length - 1;
if (index != lastIndex) {
uint256 lastId = s.ownerItems[_from][lastIndex];
s.ownerItems[_from][index] = uint16(lastId);
s.ownerItemIndexes[_from][lastId] = index + 1;
}
s.ownerItems[_from].pop();
delete s.ownerItemIndexes[_from][_id];
}
}
function removeFromParent(
address _fromContract,
uint256 _fromTokenId,
uint256 _id,
uint256 _value
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 bal = s.nftItemBalances[_fromContract][_fromTokenId][_id];
require(_value <= bal, "Items: Doesn't have that many to transfer");
bal -= _value;
s.nftItemBalances[_fromContract][_fromTokenId][_id] = bal;
if (bal == 0) {
uint256 index = s.nftItemIndexes[_fromContract][_fromTokenId][_id] - 1;
uint256 lastIndex = s.nftItems[_fromContract][_fromTokenId].length - 1;
if (index != lastIndex) {
uint256 lastId = s.nftItems[_fromContract][_fromTokenId][lastIndex];
s.nftItems[_fromContract][_fromTokenId][index] = uint16(lastId);
s.nftItemIndexes[_fromContract][_fromTokenId][lastId] = index + 1;
}
s.nftItems[_fromContract][_fromTokenId].pop();
delete s.nftItemIndexes[_fromContract][_fromTokenId][_id];
if (_fromContract == address(this)) {
checkWearableIsEquipped(_fromTokenId, _id);
}
}
if (_fromContract == address(this) && bal == 1) {
Aavegotchi storage aavegotchi = s.aavegotchis[_fromTokenId];
if (
aavegotchi.equippedWearables[LibItems.WEARABLE_SLOT_HAND_LEFT] == _id &&
aavegotchi.equippedWearables[LibItems.WEARABLE_SLOT_HAND_RIGHT] == _id
) {
revert("LibItems: Can't hold 1 item in both hands");
}
}
}
function checkWearableIsEquipped(uint256 _fromTokenId, uint256 _id) internal view {
AppStorage storage s = LibAppStorage.diamondStorage();
for (uint256 i; i < EQUIPPED_WEARABLE_SLOTS; i++) {
require(s.aavegotchis[_fromTokenId].equippedWearables[i] != _id, "Items: Cannot transfer wearable that is equipped");
}
}
}
// File contracts/shared/interfaces/IERC20.sol
pragma solidity 0.8.1;
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256 balance);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function transfer(address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
}
// File contracts/shared/libraries/LibERC20.sol
pragma solidity 0.8.1;
/******************************************************************************\
* Author: Nick Mudge
*
/******************************************************************************/
library LibERC20 {
function transferFrom(
address _token,
address _from,
address _to,
uint256 _value
) internal {
uint256 size;
assembly {
size := extcodesize(_token)
}
require(size > 0, "LibERC20: ERC20 token address has no code");
(bool success, bytes memory result) = _token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, _from, _to, _value));
handleReturn(success, result);
}
function transfer(
address _token,
address _to,
uint256 _value
) internal {
uint256 size;
assembly {
size := extcodesize(_token)
}
require(size > 0, "LibERC20: ERC20 token address has no code");
(bool success, bytes memory result) = _token.call(abi.encodeWithSelector(IERC20.transfer.selector, _to, _value));
handleReturn(success, result);
}
function handleReturn(bool _success, bytes memory _result) internal pure {
if (_success) {
if (_result.length > 0) {
require(abi.decode(_result, (bool)), "LibERC20: transfer or transferFrom returned false");
}
} else {
if (_result.length > 0) {
// bubble up any reason for revert
revert(string(_result));
} else {
revert("LibERC20: transfer or transferFrom reverted");
}
}
}
}
// File contracts/shared/interfaces/IERC721.sol
pragma solidity 0.8.1;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
/* is ERC165 */
interface IERC721 {
/// @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 calldata 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);
}
// File contracts/shared/interfaces/IERC721TokenReceiver.sol
pragma solidity 0.8.1;
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface IERC721TokenReceiver {
/// @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 calldata _data
) external returns (bytes4);
}
// File contracts/shared/libraries/LibERC721.sol
pragma solidity 0.8.1;
library LibERC721 {
/// @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);
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
function checkOnERC721Received(
address _operator,
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
) internal {
uint256 size;
assembly {
size := extcodesize(_to)
}
if (size > 0) {
require(
ERC721_RECEIVED == IERC721TokenReceiver(_to).onERC721Received(_operator, _from, _tokenId, _data),
"AavegotchiFacet: Transfer rejected/failed by _to"
);
}
}
}
// File contracts/Aavegotchi/libraries/LibAavegotchi.sol
pragma solidity 0.8.1;
struct AavegotchiCollateralTypeIO {
address collateralType;
AavegotchiCollateralTypeInfo collateralTypeInfo;
}
struct AavegotchiInfo {
uint256 tokenId;
string name;
address owner;
uint256 randomNumber;
uint256 status;
int16[NUMERIC_TRAITS_NUM] numericTraits;
int16[NUMERIC_TRAITS_NUM] modifiedNumericTraits;
uint16[EQUIPPED_WEARABLE_SLOTS] equippedWearables;
address collateral;
address escrow;
uint256 stakedAmount;
uint256 minimumStake;
uint256 kinship; //The kinship value of this Aavegotchi. Default is 50.
uint256 lastInteracted;
uint256 experience; //How much XP this Aavegotchi has accrued. Begins at 0.
uint256 toNextLevel;
uint256 usedSkillPoints; //number of skill points used
uint256 level; //the current aavegotchi level
uint256 hauntId;
uint256 baseRarityScore;
uint256 modifiedRarityScore;
bool locked;
ItemTypeIO[] items;
}
struct PortalAavegotchiTraitsIO {
uint256 randomNumber;
int16[NUMERIC_TRAITS_NUM] numericTraits;
address collateralType;
uint256 minimumStake;
}
struct InternalPortalAavegotchiTraitsIO {
uint256 randomNumber;
int16[NUMERIC_TRAITS_NUM] numericTraits;
address collateralType;
uint256 minimumStake;
}
library LibAavegotchi {
uint8 constant STATUS_CLOSED_PORTAL = 0;
uint8 constant STATUS_VRF_PENDING = 1;
uint8 constant STATUS_OPEN_PORTAL = 2;
uint8 constant STATUS_AAVEGOTCHI = 3;
event AavegotchiInteract(uint256 indexed _tokenId, uint256 kinship);
function toNumericTraits(uint256 _randomNumber, int16[NUMERIC_TRAITS_NUM] memory _modifiers)
internal
pure
returns (int16[NUMERIC_TRAITS_NUM] memory numericTraits_)
{
for (uint256 i; i < NUMERIC_TRAITS_NUM; i++) {
uint256 value = uint8(uint256(_randomNumber >> (i * 8)));
if (value > 99) {
value /= 2;
if (value > 99) {
value = uint256(keccak256(abi.encodePacked(_randomNumber, i))) % 100;
}
}
numericTraits_[i] = int16(int256(value)) + _modifiers[i];
}
}
function rarityMultiplier(int16[NUMERIC_TRAITS_NUM] memory _numericTraits) internal pure returns (uint256 multiplier) {
uint256 rarityScore = LibAavegotchi.baseRarityScore(_numericTraits);
if (rarityScore < 300) return 10;
else if (rarityScore >= 300 && rarityScore < 450) return 10;
else if (rarityScore >= 450 && rarityScore <= 525) return 25;
else if (rarityScore >= 526 && rarityScore <= 580) return 100;
else if (rarityScore >= 581) return 1000;
}
function singlePortalAavegotchiTraits(uint256 _randomNumber, uint256 _option)
internal
view
returns (InternalPortalAavegotchiTraitsIO memory singlePortalAavegotchiTraits_)
{
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 randomNumberN = uint256(keccak256(abi.encodePacked(_randomNumber, _option)));
singlePortalAavegotchiTraits_.randomNumber = randomNumberN;
address collateralType = s.collateralTypes[randomNumberN % s.collateralTypes.length];
singlePortalAavegotchiTraits_.numericTraits = toNumericTraits(randomNumberN, s.collateralTypeInfo[collateralType].modifiers);
singlePortalAavegotchiTraits_.collateralType = collateralType;
AavegotchiCollateralTypeInfo memory collateralInfo = s.collateralTypeInfo[collateralType];
uint256 conversionRate = collateralInfo.conversionRate;
//Get rarity multiplier
uint256 multiplier = rarityMultiplier(singlePortalAavegotchiTraits_.numericTraits);
//First we get the base price of our collateral in terms of DAI
uint256 collateralDAIPrice = ((10**IERC20(collateralType).decimals()) / conversionRate);
//Then multiply by the rarity multiplier
singlePortalAavegotchiTraits_.minimumStake = collateralDAIPrice * multiplier;
}
function portalAavegotchiTraits(uint256 _tokenId)
internal
view
returns (PortalAavegotchiTraitsIO[PORTAL_AAVEGOTCHIS_NUM] memory portalAavegotchiTraits_)
{
AppStorage storage s = LibAppStorage.diamondStorage();
require(s.aavegotchis[_tokenId].status == LibAavegotchi.STATUS_OPEN_PORTAL, "AavegotchiFacet: Portal not open");
uint256 randomNumber = s.tokenIdToRandomNumber[_tokenId];
for (uint256 i; i < portalAavegotchiTraits_.length; i++) {
InternalPortalAavegotchiTraitsIO memory single = singlePortalAavegotchiTraits(randomNumber, i);
portalAavegotchiTraits_[i].randomNumber = single.randomNumber;
portalAavegotchiTraits_[i].collateralType = single.collateralType;
portalAavegotchiTraits_[i].minimumStake = single.minimumStake;
portalAavegotchiTraits_[i].numericTraits = single.numericTraits;
}
}
function getAavegotchi(uint256 _tokenId) internal view returns (AavegotchiInfo memory aavegotchiInfo_) {
AppStorage storage s = LibAppStorage.diamondStorage();
aavegotchiInfo_.tokenId = _tokenId;
aavegotchiInfo_.owner = s.aavegotchis[_tokenId].owner;
aavegotchiInfo_.randomNumber = s.aavegotchis[_tokenId].randomNumber;
aavegotchiInfo_.status = s.aavegotchis[_tokenId].status;
aavegotchiInfo_.hauntId = s.aavegotchis[_tokenId].hauntId;
if (aavegotchiInfo_.status == STATUS_AAVEGOTCHI) {
aavegotchiInfo_.name = s.aavegotchis[_tokenId].name;
aavegotchiInfo_.equippedWearables = s.aavegotchis[_tokenId].equippedWearables;
aavegotchiInfo_.collateral = s.aavegotchis[_tokenId].collateralType;
aavegotchiInfo_.escrow = s.aavegotchis[_tokenId].escrow;
aavegotchiInfo_.stakedAmount = IERC20(aavegotchiInfo_.collateral).balanceOf(aavegotchiInfo_.escrow);
aavegotchiInfo_.minimumStake = s.aavegotchis[_tokenId].minimumStake;
aavegotchiInfo_.kinship = kinship(_tokenId);
aavegotchiInfo_.lastInteracted = s.aavegotchis[_tokenId].lastInteracted;
aavegotchiInfo_.experience = s.aavegotchis[_tokenId].experience;
aavegotchiInfo_.toNextLevel = xpUntilNextLevel(s.aavegotchis[_tokenId].experience);
aavegotchiInfo_.level = aavegotchiLevel(s.aavegotchis[_tokenId].experience);
aavegotchiInfo_.usedSkillPoints = s.aavegotchis[_tokenId].usedSkillPoints;
aavegotchiInfo_.numericTraits = s.aavegotchis[_tokenId].numericTraits;
aavegotchiInfo_.baseRarityScore = baseRarityScore(aavegotchiInfo_.numericTraits);
(aavegotchiInfo_.modifiedNumericTraits, aavegotchiInfo_.modifiedRarityScore) = modifiedTraitsAndRarityScore(_tokenId);
aavegotchiInfo_.locked = s.aavegotchis[_tokenId].locked;
aavegotchiInfo_.items = LibItems.itemBalancesOfTokenWithTypes(address(this), _tokenId);
}
}
//Only valid for claimed Aavegotchis
function modifiedTraitsAndRarityScore(uint256 _tokenId)
internal
view
returns (int16[NUMERIC_TRAITS_NUM] memory numericTraits_, uint256 rarityScore_)
{
AppStorage storage s = LibAppStorage.diamondStorage();
require(s.aavegotchis[_tokenId].status == STATUS_AAVEGOTCHI, "AavegotchiFacet: Must be claimed");
Aavegotchi storage aavegotchi = s.aavegotchis[_tokenId];
numericTraits_ = getNumericTraits(_tokenId);
uint256 wearableBonus;
for (uint256 slot; slot < EQUIPPED_WEARABLE_SLOTS; slot++) {
uint256 wearableId = aavegotchi.equippedWearables[slot];
if (wearableId == 0) {
continue;
}
ItemType storage itemType = s.itemTypes[wearableId];
//Add on trait modifiers
for (uint256 j; j < NUMERIC_TRAITS_NUM; j++) {
numericTraits_[j] += itemType.traitModifiers[j];
}
wearableBonus += itemType.rarityScoreModifier;
}
uint256 baseRarity = baseRarityScore(numericTraits_);
rarityScore_ = baseRarity + wearableBonus;
}
function getNumericTraits(uint256 _tokenId) internal view returns (int16[NUMERIC_TRAITS_NUM] memory numericTraits_) {
AppStorage storage s = LibAppStorage.diamondStorage();
//Check if trait boosts from consumables are still valid
int256 boostDecay = int256((block.timestamp - s.aavegotchis[_tokenId].lastTemporaryBoost) / 24 hours);
for (uint256 i; i < NUMERIC_TRAITS_NUM; i++) {
int256 number = s.aavegotchis[_tokenId].numericTraits[i];
int256 boost = s.aavegotchis[_tokenId].temporaryTraitBoosts[i];
if (boost > 0 && boost > boostDecay) {
number += boost - boostDecay;
} else if ((boost * -1) > boostDecay) {
number += boost + boostDecay;
}
numericTraits_[i] = int16(number);
}
}
function kinship(uint256 _tokenId) internal view returns (uint256 score_) {
AppStorage storage s = LibAppStorage.diamondStorage();
Aavegotchi storage aavegotchi = s.aavegotchis[_tokenId];
uint256 lastInteracted = aavegotchi.lastInteracted;
uint256 interactionCount = aavegotchi.interactionCount;
uint256 interval = block.timestamp - lastInteracted;
uint256 daysSinceInteraction = interval / 24 hours;
if (interactionCount > daysSinceInteraction) {
score_ = interactionCount - daysSinceInteraction;
}
}
function xpUntilNextLevel(uint256 _experience) internal pure returns (uint256 requiredXp_) {
uint256 currentLevel = aavegotchiLevel(_experience);
requiredXp_ = ((currentLevel**2) * 50) - _experience;
}
function aavegotchiLevel(uint256 _experience) internal pure returns (uint256 level_) {
if (_experience > 490050) {
return 99;
}
level_ = (sqrt(2 * _experience) / 10);
return level_ + 1;
}
function interact(uint256 _tokenId) internal returns (bool) {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 lastInteracted = s.aavegotchis[_tokenId].lastInteracted;
// if interacted less than 12 hours ago
if (block.timestamp < lastInteracted + 12 hours) {
return false;
}
uint256 interactionCount = s.aavegotchis[_tokenId].interactionCount;
uint256 interval = block.timestamp - lastInteracted;
uint256 daysSinceInteraction = interval / 1 days;
uint256 l_kinship;
if (interactionCount > daysSinceInteraction) {
l_kinship = interactionCount - daysSinceInteraction;
}
uint256 hateBonus;
if (l_kinship < 40) {
hateBonus = 2;
}
l_kinship += 1 + hateBonus;
s.aavegotchis[_tokenId].interactionCount = l_kinship;
s.aavegotchis[_tokenId].lastInteracted = uint40(block.timestamp);
emit AavegotchiInteract(_tokenId, l_kinship);
return true;
}
//Calculates the base rarity score, including collateral modifier
function baseRarityScore(int16[NUMERIC_TRAITS_NUM] memory _numericTraits) internal pure returns (uint256 _rarityScore) {
for (uint256 i; i < NUMERIC_TRAITS_NUM; i++) {
int256 number = _numericTraits[i];
if (number >= 50) {
_rarityScore += uint256(number) + 1;
} else {
_rarityScore += uint256(int256(100) - number);
}
}
}
// Need to ensure there is no overflow of _ghst
function purchase(address _from, uint256 _ghst) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
//33% to burn address
uint256 burnShare = (_ghst * 33) / 100;
//17% to Pixelcraft wallet
uint256 companyShare = (_ghst * 17) / 100;
//40% to rarity farming rewards
uint256 rarityFarmShare = (_ghst * 2) / 5;
//10% to DAO
uint256 daoShare = (_ghst - burnShare - companyShare - rarityFarmShare);
// Using 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF as burn address.
// GHST token contract does not allow transferring to address(0) address: https://etherscan.io/address/0x3F382DbD960E3a9bbCeaE22651E88158d2791550#code
address ghstContract = s.ghstContract;
LibERC20.transferFrom(ghstContract, _from, address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF), burnShare);
LibERC20.transferFrom(ghstContract, _from, s.pixelCraft, companyShare);
LibERC20.transferFrom(ghstContract, _from, s.rarityFarming, rarityFarmShare);
LibERC20.transferFrom(ghstContract, _from, s.dao, daoShare);
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function validateAndLowerName(string memory _name) internal pure returns (string memory) {
bytes memory name = abi.encodePacked(_name);
uint256 len = name.length;
require(len != 0, "LibAavegotchi: name can't be 0 chars");
require(len < 26, "LibAavegotchi: name can't be greater than 25 characters");
uint256 char = uint256(uint8(name[0]));
require(char != 32, "LibAavegotchi: first char of name can't be a space");
char = uint256(uint8(name[len - 1]));
require(char != 32, "LibAavegotchi: last char of name can't be a space");
for (uint256 i; i < len; i++) {
char = uint256(uint8(name[i]));
require(char > 31 && char < 127, "LibAavegotchi: invalid character in Aavegotchi name.");
if (char < 91 && char > 64) {
name[i] = bytes1(uint8(char + 32));
}
}
return string(name);
}
// function addTokenToUser(address _to, uint256 _tokenId) internal {}
// function removeTokenFromUser(address _from, uint256 _tokenId) internal {}
function transfer(
address _from,
address _to,
uint256 _tokenId
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
// remove
uint256 index = s.ownerTokenIdIndexes[_from][_tokenId];
uint256 lastIndex = s.ownerTokenIds[_from].length - 1;
if (index != lastIndex) {
uint32 lastTokenId = s.ownerTokenIds[_from][lastIndex];
s.ownerTokenIds[_from][index] = lastTokenId;
s.ownerTokenIdIndexes[_from][lastTokenId] = index;
}
s.ownerTokenIds[_from].pop();
delete s.ownerTokenIdIndexes[_from][_tokenId];
if (s.approved[_tokenId] != address(0)) {
delete s.approved[_tokenId];
emit LibERC721.Approval(_from, address(0), _tokenId);
}
// add
s.aavegotchis[_tokenId].owner = _to;
s.ownerTokenIdIndexes[_to][_tokenId] = s.ownerTokenIds[_to].length;
s.ownerTokenIds[_to].push(uint32(_tokenId));
emit LibERC721.Transfer(_from, _to, _tokenId);
}
/* function verify(uint256 _tokenId) internal pure {
// if (_tokenId < 10) {}
// revert("Not verified");
}
*/
}
// File contracts/shared/libraries/LibStrings.sol
pragma solidity 0.8.1;
// From Open Zeppelin contracts: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
/**
* @dev String operations.
*/
library LibStrings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function strWithUint(string memory _str, 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
bytes memory buffer;
unchecked {
if (value == 0) {
return string(abi.encodePacked(_str, "0"));
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
}
return string(abi.encodePacked(_str, buffer));
}
}
// File contracts/shared/interfaces/IERC1155.sol
pragma solidity 0.8.1;
/**
@title ERC-1155 Multi Token Standard
@dev See https://eips.ethereum.org/EIPS/eip-1155
Note: The ERC-165 identifier for this interface is 0xd9b67a26.
*/
/* is ERC165 */
interface IERC1155 {
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _value,
bytes calldata _data
) external;
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external;
/**
@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) external view returns (uint256);
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the tokens
@return The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@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 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) external view returns (bool);
}
// File contracts/Aavegotchi/libraries/LibERC1155Marketplace.sol
pragma solidity 0.8.1;
// import "hardhat/console.sol";
library LibERC1155Marketplace {
event ERC1155ListingCancelled(uint256 indexed listingId, uint256 category, uint256 time);
event ERC1155ListingRemoved(uint256 indexed listingId, uint256 category, uint256 time);
event UpdateERC1155Listing(uint256 indexed listingId, uint256 quantity, uint256 priceInWei, uint256 time);
function cancelERC1155Listing(uint256 _listingId, address _owner) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
ListingListItem storage listingItem = s.erc1155ListingListItem["listed"][_listingId];
if (listingItem.listingId == 0) {
return;
}
ERC1155Listing storage listing = s.erc1155Listings[_listingId];
if (listing.cancelled == true || listing.sold == true) {
return;
}
require(listing.seller == _owner, "Marketplace: owner not seller");
listing.cancelled = true;
emit ERC1155ListingCancelled(_listingId, listing.category, block.number);
removeERC1155ListingItem(_listingId, _owner);
}
function addERC1155ListingItem(
address _owner,
uint256 _category,
string memory _sort,
uint256 _listingId
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 headListingId = s.erc1155OwnerListingHead[_owner][_category][_sort];
if (headListingId != 0) {
ListingListItem storage headListingItem = s.erc1155OwnerListingListItem[_sort][headListingId];
headListingItem.parentListingId = _listingId;
}
ListingListItem storage listingItem = s.erc1155OwnerListingListItem[_sort][_listingId];
listingItem.childListingId = headListingId;
s.erc1155OwnerListingHead[_owner][_category][_sort] = _listingId;
listingItem.listingId = _listingId;
headListingId = s.erc1155ListingHead[_category][_sort];
if (headListingId != 0) {
ListingListItem storage headListingItem = s.erc1155ListingListItem[_sort][headListingId];
headListingItem.parentListingId = _listingId;
}
listingItem = s.erc1155ListingListItem[_sort][_listingId];
listingItem.childListingId = headListingId;
s.erc1155ListingHead[_category][_sort] = _listingId;
listingItem.listingId = _listingId;
}
function removeERC1155ListingItem(uint256 _listingId, address _owner) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
ListingListItem storage listingItem = s.erc1155ListingListItem["listed"][_listingId];
if (listingItem.listingId == 0) {
return;
}
uint256 parentListingId = listingItem.parentListingId;
if (parentListingId != 0) {
ListingListItem storage parentListingItem = s.erc1155ListingListItem["listed"][parentListingId];
parentListingItem.childListingId = listingItem.childListingId;
}
uint256 childListingId = listingItem.childListingId;
if (childListingId != 0) {
ListingListItem storage childListingItem = s.erc1155ListingListItem["listed"][childListingId];
childListingItem.parentListingId = listingItem.parentListingId;
}
ERC1155Listing storage listing = s.erc1155Listings[_listingId];
if (s.erc1155ListingHead[listing.category]["listed"] == _listingId) {
s.erc1155ListingHead[listing.category]["listed"] = listingItem.childListingId;
}
listingItem.listingId = 0;
listingItem.parentListingId = 0;
listingItem.childListingId = 0;
listingItem = s.erc1155OwnerListingListItem["listed"][_listingId];
parentListingId = listingItem.parentListingId;
if (parentListingId != 0) {
ListingListItem storage parentListingItem = s.erc1155OwnerListingListItem["listed"][parentListingId];
parentListingItem.childListingId = listingItem.childListingId;
}
childListingId = listingItem.childListingId;
if (childListingId != 0) {
ListingListItem storage childListingItem = s.erc1155OwnerListingListItem["listed"][childListingId];
childListingItem.parentListingId = listingItem.parentListingId;
}
listing = s.erc1155Listings[_listingId];
if (s.erc1155OwnerListingHead[_owner][listing.category]["listed"] == _listingId) {
s.erc1155OwnerListingHead[_owner][listing.category]["listed"] = listingItem.childListingId;
}
listingItem.listingId = 0;
listingItem.parentListingId = 0;
listingItem.childListingId = 0;
s.erc1155TokenToListingId[listing.erc1155TokenAddress][listing.erc1155TypeId][_owner] = 0;
emit ERC1155ListingRemoved(_listingId, listing.category, block.timestamp);
}
function updateERC1155Listing(
address _erc1155TokenAddress,
uint256 _erc1155TypeId,
address _owner
) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 listingId = s.erc1155TokenToListingId[_erc1155TokenAddress][_erc1155TypeId][_owner];
if (listingId == 0) {
return;
}
ERC1155Listing storage listing = s.erc1155Listings[listingId];
if (listing.timeCreated == 0 || listing.cancelled == true || listing.sold == true) {
return;
}
uint256 quantity = listing.quantity;
if (quantity > 0) {
quantity = IERC1155(listing.erc1155TokenAddress).balanceOf(listing.seller, listing.erc1155TypeId);
if (quantity < listing.quantity) {
listing.quantity = quantity;
emit UpdateERC1155Listing(listingId, quantity, listing.priceInWei, block.timestamp);
}
}
if (quantity == 0) {
cancelERC1155Listing(listingId, listing.seller);
}
}
}
// File contracts/Aavegotchi/facets/ItemsFacet.sol
pragma solidity 0.8.1;
// import "hardhat/console.sol";
contract ItemsFacet is Modifiers {
//using LibAppStorage for AppStorage;
event TransferToParent(address indexed _toContract, uint256 indexed _toTokenId, uint256 indexed _tokenTypeId, uint256 _value);
event EquipWearables(uint256 indexed _tokenId, uint16[EQUIPPED_WEARABLE_SLOTS] _oldWearables, uint16[EQUIPPED_WEARABLE_SLOTS] _newWearables);
event UseConsumables(uint256 indexed _tokenId, uint256[] _itemIds, uint256[] _quantities);
/***********************************|
| Read Functions |
|__________________________________*/
struct ItemIdIO {
uint256 itemId;
uint256 balance;
}
// Returns balance for each item that exists for an account
function itemBalances(address _account) external view returns (ItemIdIO[] memory bals_) {
uint256 count = s.ownerItems[_account].length;
bals_ = new ItemIdIO[](count);
for (uint256 i; i < count; i++) {
uint256 itemId = s.ownerItems[_account][i];
bals_[i].balance = s.ownerItemBalances[_account][itemId];
bals_[i].itemId = itemId;
}
}
function itemBalancesWithTypes(address _owner) external view returns (ItemTypeIO[] memory output_) {
uint256 count = s.ownerItems[_owner].length;
output_ = new ItemTypeIO[](count);
for (uint256 i; i < count; i++) {
uint256 itemId = s.ownerItems[_owner][i];
output_[i].balance = s.ownerItemBalances[_owner][itemId];
output_[i].itemId = itemId;
output_[i].itemType = s.itemTypes[itemId];
}
}
/**
@notice Get the balance of an account's tokens.
@param _owner The address of the token holder
@param _id ID of the token
@return bal_ The _owner's balance of the token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256 bal_) {
bal_ = s.ownerItemBalances[_owner][_id];
}
/// @notice Get the balance of a non-fungible parent token
/// @param _tokenContract The contract tracking the parent token
/// @param _tokenId The ID of the parent token
/// @param _id ID of the token
/// @return value The balance of the token
function balanceOfToken(
address _tokenContract,
uint256 _tokenId,
uint256 _id
) external view returns (uint256 value) {
value = s.nftItemBalances[_tokenContract][_tokenId][_id];
}
// returns the balances for all items for a token
function itemBalancesOfToken(address _tokenContract, uint256 _tokenId) external view returns (ItemIdIO[] memory bals_) {
uint256 count = s.nftItems[_tokenContract][_tokenId].length;
bals_ = new ItemIdIO[](count);
for (uint256 i; i < count; i++) {
uint256 itemId = s.nftItems[_tokenContract][_tokenId][i];
bals_[i].itemId = itemId;
bals_[i].balance = s.nftItemBalances[_tokenContract][_tokenId][itemId];
}
}
function itemBalancesOfTokenWithTypes(address _tokenContract, uint256 _tokenId)
external
view
returns (ItemTypeIO[] memory itemBalancesOfTokenWithTypes_)
{
itemBalancesOfTokenWithTypes_ = LibItems.itemBalancesOfTokenWithTypes(_tokenContract, _tokenId);
}
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the tokens
@return bals The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory bals) {
require(_owners.length == _ids.length, "ItemsFacet: _owners length not same as _ids length");
bals = new uint256[](_owners.length);
for (uint256 i; i < _owners.length; i++) {
uint256 id = _ids[i];
address owner = _owners[i];
bals[i] = s.ownerItemBalances[owner][id];
}
}
function equippedWearables(uint256 _tokenId) external view returns (uint16[EQUIPPED_WEARABLE_SLOTS] memory wearableIds_) {
wearableIds_ = s.aavegotchis[_tokenId].equippedWearables;
}
// Called by off chain software so not too concerned about gas costs
function getWearableSets() external view returns (WearableSet[] memory wearableSets_) {
wearableSets_ = s.wearableSets;
}
function getWearableSet(uint256 _index) public view returns (WearableSet memory wearableSet_) {
uint256 length = s.wearableSets.length;
require(_index < length, "ItemsFacet: Wearable set does not exist");
wearableSet_ = s.wearableSets[_index];
}
function totalWearableSets() external view returns (uint256) {
return s.wearableSets.length;
}
function findWearableSets(uint256[] calldata _wearableIds) external view returns (uint256[] memory wearableSetIds_) {
unchecked {
uint256 length = s.wearableSets.length;
wearableSetIds_ = new uint256[](length);
uint256 count;
for (uint256 i; i < length; i++) {
uint16[] memory setWearableIds = s.wearableSets[i].wearableIds;
bool foundSet = true;
for (uint256 j; j < setWearableIds.length; j++) {
uint256 setWearableId = setWearableIds[j];
bool foundWearableId = false;
for (uint256 k; k < _wearableIds.length; k++) {
if (_wearableIds[k] == setWearableId) {
foundWearableId = true;
break;
}
}
if (foundWearableId == false) {
foundSet = false;
break;
}
}
if (foundSet) {
wearableSetIds_[count] = i;
count++;
}
}
assembly {
mstore(wearableSetIds_, count)
}
}
}
function getItemType(uint256 _itemId) public view returns (ItemType memory itemType_) {
require(_itemId < s.itemTypes.length, "ItemsFacet: Item type doesn't exist");
itemType_ = s.itemTypes[_itemId];
}
function getItemTypes(uint256[] calldata _itemIds) external view returns (ItemType[] memory itemTypes_) {
if (_itemIds.length == 0) {
itemTypes_ = s.itemTypes;
} else {
itemTypes_ = new ItemType[](_itemIds.length);
for (uint256 i; i < _itemIds.length; i++) {
itemTypes_[i] = s.itemTypes[_itemIds[i]];
}
}
}
/**
@notice Get the URI for a voucher type
@return URI for token type
*/
function uri(uint256 _id) external view returns (string memory) {
require(_id < s.itemTypes.length, "ItemsFacet: _id not found for item");
return LibStrings.strWithUint(s.itemsBaseUri, _id);
}
/**
@notice Set the base url for all voucher types
@param _value The new base url
*/
function setBaseURI(string memory _value) external onlyDaoOrOwner {
// require(LibMeta.msgSender() == s.contractOwner, "ItemsFacet: Must be contract owner");
s.itemsBaseUri = _value;
for (uint256 i; i < s.itemTypes.length; i++) {
emit LibERC1155.URI(LibStrings.strWithUint(_value, i), i);
}
}
/***********************************|
| Write Functions |
|__________________________________*/
function equipWearables(uint256 _tokenId, uint16[EQUIPPED_WEARABLE_SLOTS] calldata _equippedWearables) external onlyAavegotchiOwner(_tokenId) {
Aavegotchi storage aavegotchi = s.aavegotchis[_tokenId];
require(aavegotchi.status == LibAavegotchi.STATUS_AAVEGOTCHI, "LibAavegotchi: Only valid for Aavegotchi");
address sender = LibMeta.msgSender();
uint256 aavegotchiLevel = LibAavegotchi.aavegotchiLevel(aavegotchi.experience);
for (uint256 slot; slot < EQUIPPED_WEARABLE_SLOTS; slot++) {
uint256 wearableId = _equippedWearables[slot];
if (wearableId == 0) {
continue;
}
ItemType storage itemType = s.itemTypes[wearableId];
require(aavegotchiLevel >= itemType.minLevel, "ItemsFacet: Aavegotchi level lower than minLevel");
require(itemType.category == LibItems.ITEM_CATEGORY_WEARABLE, "ItemsFacet: Only wearables can be equippped");
require(itemType.slotPositions[slot] == true, "ItemsFacet: Wearable cannot be equipped in this slot");
{
bool canBeEquipped;
uint8[] memory allowedCollaterals = itemType.allowedCollaterals;
if (allowedCollaterals.length > 0) {
uint256 collateralIndex = s.collateralTypeIndexes[aavegotchi.collateralType];
for (uint256 i; i < allowedCollaterals.length; i++) {
if (collateralIndex == allowedCollaterals[i]) {
canBeEquipped = true;
break;
}
}
require(canBeEquipped, "ItemsFacet: Wearable cannot be equipped in this collateral type");
}
}
//Then check if this wearable is in the Aavegotchis inventory
uint256 nftBalance = s.nftItemBalances[address(this)][_tokenId][wearableId];
uint256 neededBalance = 1;
if (slot == LibItems.WEARABLE_SLOT_HAND_LEFT) {
if (_equippedWearables[LibItems.WEARABLE_SLOT_HAND_RIGHT] == wearableId) {
neededBalance = 2;
}
}
if (nftBalance < neededBalance) {
uint256 ownerBalance = s.ownerItemBalances[sender][wearableId];
require(nftBalance + ownerBalance >= neededBalance, "ItemsFacet: Wearable is not in inventories");
uint256 balToTransfer = neededBalance - nftBalance;
//Transfer to Aavegotchi
LibItems.removeFromOwner(sender, wearableId, balToTransfer);
LibItems.addToParent(address(this), _tokenId, wearableId, balToTransfer);
emit TransferToParent(address(this), _tokenId, wearableId, balToTransfer);
emit LibERC1155.TransferSingle(sender, sender, address(this), wearableId, balToTransfer);
LibERC1155Marketplace.updateERC1155Listing(address(this), wearableId, sender);
}
}
emit EquipWearables(_tokenId, aavegotchi.equippedWearables, _equippedWearables);
aavegotchi.equippedWearables = _equippedWearables;
LibAavegotchi.interact(_tokenId);
}
function useConsumables(
uint256 _tokenId,
uint256[] calldata _itemIds,
uint256[] calldata _quantities
) external onlyUnlocked(_tokenId) onlyAavegotchiOwner(_tokenId) {
require(_itemIds.length == _quantities.length, "ItemsFacet: _itemIds length does not match _quantities length");
require(s.aavegotchis[_tokenId].status == LibAavegotchi.STATUS_AAVEGOTCHI, "LibAavegotchi: Only valid for Aavegotchi");
address sender = LibMeta.msgSender();
for (uint256 i; i < _itemIds.length; i++) {
uint256 itemId = _itemIds[i];
uint256 quantity = _quantities[i];
ItemType memory itemType = s.itemTypes[itemId];
require(itemType.category == LibItems.ITEM_CATEGORY_CONSUMABLE, "ItemsFacet: Item must be consumable");
LibItems.removeFromOwner(sender, itemId, quantity);
//Increase kinship
if (itemType.kinshipBonus > 0) {
uint256 kinship = (uint256(int256(itemType.kinshipBonus)) * quantity) + s.aavegotchis[_tokenId].interactionCount;
s.aavegotchis[_tokenId].interactionCount = kinship;
} else if (itemType.kinshipBonus < 0) {
uint256 kinshipBonus = LibAppStorage.abs(itemType.kinshipBonus) * quantity;
if (s.aavegotchis[_tokenId].interactionCount > kinshipBonus) {
s.aavegotchis[_tokenId].interactionCount -= kinshipBonus;
} else {
s.aavegotchis[_tokenId].interactionCount = 0;
}
}
{
// prevent stack too deep error with braces here
//Boost traits and reset clock
bool boost = false;
for (uint256 j; j < NUMERIC_TRAITS_NUM; j++) {
if (itemType.traitModifiers[j] != 0) {
boost = true;
break;
}
}
if (boost) {
s.aavegotchis[_tokenId].lastTemporaryBoost = uint40(block.timestamp);
s.aavegotchis[_tokenId].temporaryTraitBoosts = itemType.traitModifiers;
}
}
//Increase experience
if (itemType.experienceBonus > 0) {
uint256 experience = (uint256(itemType.experienceBonus) * quantity) + s.aavegotchis[_tokenId].experience;
s.aavegotchis[_tokenId].experience = experience;
}
itemType.totalQuantity -= quantity;
LibAavegotchi.interact(_tokenId);
LibERC1155Marketplace.updateERC1155Listing(address(this), itemId, sender);
}
emit UseConsumables(_tokenId, _itemIds, _quantities);
emit LibERC1155.TransferBatch(sender, sender, address(0), _itemIds, _quantities);
}
function setWearableSlotPositions(uint256 _wearableId, bool[EQUIPPED_WEARABLE_SLOTS] calldata _slotPositions) external onlyDaoOrOwner {
require(_wearableId < s.itemTypes.length, "DAOFacet: _wearableId not found for item");
s.itemTypes[_wearableId].slotPositions = _slotPositions;
}
}
| Need to ensure there is no overflow of _ghst33% to burn address17% to Pixelcraft wallet40% to rarity farming rewards10% to DAO Using 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF as burn address. GHST token contract does not allow transferring to address(0) address: https:etherscan.io/address/0x3F382DbD960E3a9bbCeaE22651E88158d2791550code | function purchase(address _from, uint256 _ghst) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
uint256 burnShare = (_ghst * 33) / 100;
uint256 companyShare = (_ghst * 17) / 100;
uint256 rarityFarmShare = (_ghst * 2) / 5;
uint256 daoShare = (_ghst - burnShare - companyShare - rarityFarmShare);
address ghstContract = s.ghstContract;
LibERC20.transferFrom(ghstContract, _from, address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF), burnShare);
LibERC20.transferFrom(ghstContract, _from, s.pixelCraft, companyShare);
LibERC20.transferFrom(ghstContract, _from, s.rarityFarming, rarityFarmShare);
LibERC20.transferFrom(ghstContract, _from, s.dao, daoShare);
}
| 2,501,947 |
// File: contracts/interfaces/IRoyaltySharing.sol
/// @title Interface for IRoyaltySharing.
pragma solidity 0.8.6;
interface IRoyaltySharing {
//TODO: event DefineEvents();
function deposit(
uint256 creators,
uint256 project,
uint256 rewards
) external payable;
}
// File: @openzeppelin/contracts/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 no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Counters.sol
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
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
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
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: contracts/nft/Membership.sol
pragma solidity 0.8.6;
contract NotoriousAlienSpaceAgentsFoundingDAOAgents is ERC721, Ownable {
using Counters for Counters.Counter;
using SafeMath for uint256;
IRoyaltySharing public royaltySharingContract;
mapping(address => bool) public reserveWhitelist;
string public tokenBaseURI;
Counters.Counter private _tokenIdCounter;
uint256 public whitelistMinPrice;
uint256 public balance;
uint256 private maxTokenId;
constructor(
string memory _tokenBaseURI,
address[] memory _whitelistAddresses,
uint256 _minPrice,
uint256 _maxTokenId
) ERC721("NASA Founding Agents", "DAOGENT") {
tokenBaseURI = _tokenBaseURI;
whitelistMinPrice = 0;
maxTokenId = _maxTokenId;
setWhitelist(_whitelistAddresses, _minPrice);
// Start from index 1
_tokenIdCounter.increment();
}
function setWhitelist(
address[] memory _whitelistAddresses,
uint256 _whitelistMinPrice
) public onlyOwner {
for (uint256 i = 0; i < _whitelistAddresses.length; i++) {
require(
_whitelistAddresses[i] != address(0),
"Can't add the null address"
);
reserveWhitelist[_whitelistAddresses[i]] = true;
}
whitelistMinPrice = _whitelistMinPrice;
}
function removeWhitelist(address[] memory _whitelistAddresses)
public
onlyOwner
{
for (uint256 i = 0; i < _whitelistAddresses.length; i++) {
reserveWhitelist[_whitelistAddresses[i]] = false;
}
}
function mintWhitelist() public payable returns (uint256) {
require(reserveWhitelist[msg.sender], "Not on the reserved whitelist");
require(msg.value == whitelistMinPrice, "Incorrect eth");
require(
_tokenIdCounter.current() <= maxTokenId,
"Max token id reached."
);
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
reserveWhitelist[msg.sender] = false;
balance = balance.add(whitelistMinPrice);
return tokenId;
}
function setRoyaltySharingContract(address _royaltySharingContractAddress)
external
onlyOwner
{
royaltySharingContract = IRoyaltySharing(
_royaltySharingContractAddress
);
}
function tokenURI(uint256) public view override returns (string memory) {
// Since all the membership cards are the same, they all point to the same image.
string memory baseURI = _baseURI();
if (bytes(baseURI).length > 0) {
return string(abi.encodePacked(baseURI, Strings.toString(1)));
}
return "";
}
function withdraw() public onlyOwner {
uint256 transferBalance = balance;
balance = 0;
royaltySharingContract.deposit{value: transferBalance}(0, 0, 100);
}
function _baseURI() internal view override returns (string memory) {
return tokenBaseURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
tokenBaseURI = baseURI;
}
} | Since all the membership cards are the same, they all point to the same image. | function tokenURI(uint256) public view override returns (string memory) {
string memory baseURI = _baseURI();
if (bytes(baseURI).length > 0) {
return string(abi.encodePacked(baseURI, Strings.toString(1)));
}
return "";
}
| 14,570,814 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
// NOTE for debugging only
import 'hardhat/console.sol';
// NOTE
// Consider storing a board as an N by M matrix of uint256
// values only. Any operation will modify this map instead
// of storing info to create the map on demand. In other words,
// move logic from getMap to addRoom, addStarts, etc.
// Functions could take arbitrarily long arrays.
contract GameBoard {
struct Room {
uint256 id;
uint256 x;
uint256 y;
uint256 width;
uint256 height;
uint256[4] doors;
uint256[2] passage;
}
// NOTE ¡magic number!
uint256 constant NV = 65535;
uint256 public constant CELL_CORRIDOR = 0;
uint256 public constant CELL_WALL = 1; // for obstructions
uint256 public constant CELL_ROOM = 2;
uint256 public constant CELL_DOOR = 3;
uint256 public constant CELL_START = 4;
uint256 public constant CELL_PASSAGE = 5;
uint256 public constant CELL_QUEUED = 6;
string name;
uint256[8] starts;
Room[] rooms;
uint256 constant rows = 25;
uint256 constant cols = 24;
constructor(string memory _name) {
name = _name;
// TODO initialize starts to NO_VALUE
}
function addStarts(uint256[8] memory _starts) public {
starts = _starts;
}
function getStarts() public view returns (uint256[8] memory) {
return starts;
}
function addRoom(Room memory _room) public {
rooms.push(_room);
}
// NOTE currently unused
function getDimensions() public pure returns (uint256, uint256) {
return (cols, rows);
}
// TODO document bit field here
function getMap() public view returns (uint256[] memory) {
uint256 count = rows * cols;
uint256[] memory map = new uint256[](count);
// starts
for (uint256 i = 0; i < starts.length; ++i) {
uint256 cellId = starts[i];
if (cellId != NV) {
map[cellId] = CELL_START;
}
}
// rooms
for (uint256 i = 0; i < rooms.length; ++i) {
// encode room id
require(rooms[i].id < 16, 'Room ID too large to encode');
uint256 encodedRoomId = rooms[i].id << 4;
// floorplan
uint256 cellId = rooms[i].y * cols + rooms[i].x;
for (uint256 j = 0; j < rooms[i].height; ++j) {
for (uint256 k = 0; k < rooms[i].width; ++k) {
map[cellId + j * cols + k] = encodedRoomId | CELL_ROOM;
}
}
// doors
for (uint256 j = 0; j < 4; ++j) {
uint256 door = rooms[i].doors[j];
if (door != NV) {
uint256 doorX = door % rooms[i].width;
uint256 doorY = door / rooms[i].width;
map[cellId + doorY * cols + doorX] = encodedRoomId | CELL_DOOR;
}
}
// passages
uint256 passage = rooms[i].passage[0];
if (passage != NV) {
uint256 passageX = passage % rooms[i].width;
uint256 passageY = passage / rooms[i].width;
uint256 encodedTargetId = rooms[i].passage[1] << 8;
map[cellId + passageY * cols + passageX] = encodedTargetId | encodedRoomId | CELL_PASSAGE;
}
}
return map;
}
function isValidMove(
uint256 _start,
uint256 _end,
uint256[4] memory _obstructions
) public view returns (bool) {
uint256 numCells = rows * cols;
if (_start >= numCells || _end >= numCells) {
return false;
}
if (_start == _end) {
return false;
}
uint256[] memory map = getMap();
// ensure end location is walkable, start assumed to be OK
if (!_isWalkable(map[_end])) {
return false;
}
// add obstructions
for (uint256 i = 0; i < 4; ++i) {
if (_obstructions[i] != NV) {
map[_obstructions[i]] = CELL_WALL;
}
}
// flood fill for validation
bool isValid = false;
uint256 maxSteps = 6;
// TODO reduce the size of these buffers as much as possible
// NOTE buffer overruns implicitly prevented by step counting
uint256 bufSize = numCells / 2;
uint256[] memory queue = new uint256[](bufSize);
uint256[] memory steps = new uint256[](bufSize);
uint256 rp = 0;
uint256 wp = 0;
queue[wp] = _start;
steps[wp++] = 0;
while (rp < wp) {
uint256 pos = queue[rp];
uint256 dist = steps[rp++];
if (pos == _end) {
isValid = true;
break;
}
if (dist < maxSteps) {
// check adjacent cells
uint256 x = pos % cols;
uint256 y = pos / cols;
if (x > 0) {
uint256 left = _convertXy(x - 1, y);
if (_isWalkable(map[left])) {
queue[wp] = left;
steps[wp++] = dist + 1;
map[left] = CELL_QUEUED;
}
}
if (x < cols - 1) {
uint256 right = _convertXy(x + 1, y);
if (_isWalkable(map[right])) {
queue[wp] = right;
steps[wp++] = dist + 1;
map[right] = CELL_QUEUED;
}
}
if (y > 0) {
uint256 up = _convertXy(x, y - 1);
if (_isWalkable(map[up])) {
queue[wp] = up;
steps[wp++] = dist + 1;
map[up] = CELL_QUEUED;
}
}
if (y < rows - 1) {
uint256 down = _convertXy(x, y + 1);
if (_isWalkable(map[down])) {
queue[wp] = down;
steps[wp++] = dist + 1;
map[down] = CELL_QUEUED;
}
}
}
}
return isValid;
}
function _isWalkable(uint256 _terrain) internal pure returns (bool) {
// strip everything but the cell type
_terrain &= 0x0f;
if (_terrain == CELL_CORRIDOR || _terrain == CELL_DOOR) {
return true;
}
return false;
}
function _convertXy(uint256 x, uint256 y) internal pure returns (uint256) {
return y * cols + x;
}
}
| strip everything but the cell type | function _isWalkable(uint256 _terrain) internal pure returns (bool) {
_terrain &= 0x0f;
if (_terrain == CELL_CORRIDOR || _terrain == CELL_DOOR) {
return true;
}
return false;
}
| 1,055,543 |
./full_match/1/0x57E91a1E8a97864417c49418276D4B17b202123e/sources/contracts/codes/N721Card.sol | Implementing the ERC-2981 royaltyInfo() function | function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) {
return (SYS_ADDRESS, salePrice * royaltyPercent / 10000);
}
| 16,412,658 |
/**
* Created on 2018-06-05 16:37
* @summary: Our NFT Minting Contract which inherits ERC721 capability from LSNFT
* @author: Fazri Zubair & Farhan Khwaja
*/
pragma solidity ^0.4.23;
pragma solidity ^0.4.23;
/* NFT Metadata Schema
{
"title": "Asset Metadata",
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Identifies the asset to which this NFT represents",
},
"description": {
"type": "string",
"description": "Describes the asset to which this NFT represents",
},
"image": {
"type": "string",
"description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.",
}
}
}
*/
/**
* @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;
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 public constant ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require (ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require (isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require (_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require (owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require (_to != owner);
require (msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require (_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require (_from != address(0));
require (_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require (checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require (_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require (ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
require (tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
require (ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev 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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 public constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
contract ERC721Holder is ERC721Receiver {
function onERC721Received(
address,
address,
uint256,
bytes
)
public
returns(bytes4)
{
return ERC721_RECEIVED;
}
}
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Base Server Address for Token MetaData URI
string internal tokenURIBase;
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @notice The user/developper needs to add the tokenID, in the end of URL, to
* use the URI and get all details. Ex. www.<apiURL>.com/token/<tokenID>
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require (exists(_tokenId));
return tokenURIBase;
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require (_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require (_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _uri string URI to assign
*/
function _setTokenURIBase(string _uri) internal {
tokenURIBase = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
ownedTokens[_from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7;
/*
bytes4(keccak256('supportsInterface(bytes4)'));
*/
bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63;
/*
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('tokenByIndex(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f;
/*
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('tokenURI(uint256)'));
*/
bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd;
/*
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('getApproved(uint256)')) ^
bytes4(keccak256('setApprovalForAll(address,bool)')) ^
bytes4(keccak256('isApprovedForAll(address,address)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'));
*/
bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79;
/*
bytes4(keccak256('exists(uint256)'));
*/
/**
* @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
* @dev Returns true for any standardized interfaces implemented by this contract.
* @param _interfaceID bytes4 the interface to check for
* @return true for any standardized interfaces implemented by this contract.
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165)
|| (_interfaceID == InterfaceSignature_ERC721)
|| (_interfaceID == InterfaceSignature_ERC721Enumerable)
|| (_interfaceID == InterfaceSignature_ERC721Metadata));
}
function implementsERC721() public pure returns (bool) {
return true;
}
}
/* Lucid Sight, Inc. ERC-721 Collectibles.
* @title LSNFT - Lucid Sight, Inc. Non-Fungible Token
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
*/
contract LSNFT is ERC721Token {
/*** EVENTS ***/
/// @dev The Created event is fired whenever a new collectible comes into existence.
event Created(address owner, uint256 tokenId);
/*** DATATYPES ***/
struct NFT {
// The sequence of potential attributes a Collectible has and can provide in creation events. Used in Creation logic to spwan new Cryptos
uint256 attributes;
// Current Game Card identifier
uint256 currentGameCardId;
// MLB Game Identifier (if asset generated as a game reward)
uint256 mlbGameId;
// player orverride identifier
uint256 playerOverrideId;
// official MLB Player ID
uint256 mlbPlayerId;
// earnedBy : In some instances we may want to retroactively write which MLB player triggered
// the event that created a Legendary Trophy. This optional field should be able to be written
// to after generation if we determine an event was newsworthy enough
uint256 earnedBy;
// asset metadata
uint256 assetDetails;
// Attach/Detach Flag
uint256 isAttached;
}
NFT[] allNFTs;
function isLSNFT() public view returns (bool) {
return true;
}
/// For creating NFT
function _createNFT (
uint256[5] _nftData,
address _owner,
uint256 _isAttached)
internal
returns(uint256) {
NFT memory _lsnftObj = NFT({
attributes : _nftData[1],
currentGameCardId : 0,
mlbGameId : _nftData[2],
playerOverrideId : _nftData[3],
assetDetails: _nftData[0],
isAttached: _isAttached,
mlbPlayerId: _nftData[4],
earnedBy: 0
});
uint256 newLSNFTId = allNFTs.push(_lsnftObj) - 1;
_mint(_owner, newLSNFTId);
// Created event
emit Created(_owner, newLSNFTId);
return newLSNFTId;
}
/// @dev Gets attributes of NFT
function _getAttributesOfToken(uint256 _tokenId) internal returns(NFT) {
NFT storage lsnftObj = allNFTs[_tokenId];
return lsnftObj;
}
function _approveForSale(address _owner, address _to, uint256 _tokenId) internal {
address owner = ownerOf(_tokenId);
require (_to != owner);
require (_owner == owner || isApprovedForAll(owner, _owner));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(_owner, _to, _tokenId);
}
}
}
/** Controls state and access rights for contract functions
* @title Operational Control
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
* Inspired and adapted from contract created by OpenZeppelin
* Ref: https://github.com/OpenZeppelin/zeppelin-solidity/
*/
contract OperationalControl {
/// Facilitates access & control for the game.
/// Roles:
/// -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw)
/// -The Banker: The Bank can withdraw funds and adjust fees / prices.
/// -otherManagers: Contracts that need access to functions for gameplay
/// @dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
/// @dev The addresses of the accounts (or contracts) that can execute actions within each roles.
address public managerPrimary;
address public managerSecondary;
address public bankManager;
// Contracts that require access for gameplay
mapping(address => uint8) public otherManagers;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
// @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed
bool public error = false;
/**
* @dev Operation modifiers for limiting access only to Managers
*/
modifier onlyManager() {
require (msg.sender == managerPrimary || msg.sender == managerSecondary);
_;
}
/**
* @dev Operation modifiers for limiting access to only Banker
*/
modifier onlyBanker() {
require (msg.sender == bankManager);
_;
}
/**
* @dev Operation modifiers for any Operators
*/
modifier anyOperator() {
require (
msg.sender == managerPrimary ||
msg.sender == managerSecondary ||
msg.sender == bankManager ||
otherManagers[msg.sender] == 1
);
_;
}
/**
* @dev Operation modifier for any Other Manager
*/
modifier onlyOtherManagers() {
require (otherManagers[msg.sender] == 1);
_;
}
/**
* @dev Assigns a new address to act as the Primary Manager.
* @param _newGM New primary manager address
*/
function setPrimaryManager(address _newGM) external onlyManager {
require (_newGM != address(0));
managerPrimary = _newGM;
}
/**
* @dev Assigns a new address to act as the Secondary Manager.
* @param _newGM New Secondary Manager Address
*/
function setSecondaryManager(address _newGM) external onlyManager {
require (_newGM != address(0));
managerSecondary = _newGM;
}
/**
* @dev Assigns a new address to act as the Banker.
* @param _newBK New Banker Address
*/
function setBanker(address _newBK) external onlyManager {
require (_newBK != address(0));
bankManager = _newBK;
}
/// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled)
function setOtherManager(address _newOp, uint8 _state) external onlyManager {
require (_newOp != address(0));
otherManagers[_newOp] = _state;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require (!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require (paused);
_;
}
/// @dev Modifier to allow actions only when the contract has Error
modifier whenError {
require (error);
_;
}
/**
* @dev Called by any Operator role to pause the contract.
* Used only if a bug or exploit is discovered (Here to limit losses / damage)
*/
function pause() external onlyManager whenNotPaused {
paused = true;
}
/**
* @dev Unpauses the smart contract. Can only be called by the Game Master
*/
function unpause() public onlyManager whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
/**
* @dev Errors out the contract thus mkaing the contract non-functionable
*/
function hasError() public onlyManager whenPaused {
error = true;
}
/**
* @dev Removes the Error Hold from the contract and resumes it for working
*/
function noError() public onlyManager whenPaused {
error = false;
}
}
/** Base contract for DodgersNFT Collectibles. Holds all commons, events and base variables.
* @title Lucid Sight MLB NFT 2018
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
*/
contract CollectibleBase is LSNFT {
/*** EVENTS ***/
/// @dev Event emitted when an attribute of the player is updated
event AssetUpdated(uint256 tokenId);
/*** STORAGE ***/
/// @dev A mapping of Team Id to Team Sequence Number to Collectible
mapping (uint256 => mapping (uint32 => uint256) ) public nftTeamIdToSequenceIdToCollectible;
/// @dev A mapping from Team IDs to the Sequqence Number .
mapping (uint256 => uint32) public nftTeamIndexToCollectibleCount;
/// @dev Array to hold details on attachment for each LS NFT Collectible
mapping(uint256 => uint256[]) public nftCollectibleAttachments;
/// @dev Mapping to control the asset generation per season.
mapping(uint256 => uint256) public generationSeasonController;
/// @dev Mapping for generation Season Dict.
mapping(uint256 => uint256) public generationSeasonDict;
/// @dev internal function to update player override id
function _updatePlayerOverrideId(uint256 _tokenId, uint256 _newPlayerOverrideId) internal {
// Get Token Obj
NFT storage lsnftObj = allNFTs[_tokenId];
lsnftObj.playerOverrideId = _newPlayerOverrideId;
// Update Token Data with new updated attributes
allNFTs[_tokenId] = lsnftObj;
emit AssetUpdated(_tokenId);
}
/**
* @dev An internal method that helps in generation of new NFT Collectibles
* @param _teamId teamId of the asset/token/collectible
* @param _attributes attributes of asset/token/collectible
* @param _owner owner of asset/token/collectible
* @param _isAttached State of the asset (attached or dettached)
* @param _nftData Array of data required for creation
*/
function _createNFTCollectible(
uint8 _teamId,
uint256 _attributes,
address _owner,
uint256 _isAttached,
uint256[5] _nftData
)
internal
returns (uint256)
{
uint256 generationSeason = (_attributes % 1000000).div(1000);
require (generationSeasonController[generationSeason] == 1);
uint32 _sequenceId = getSequenceId(_teamId);
uint256 newNFTCryptoId = _createNFT(_nftData, _owner, _isAttached);
nftTeamIdToSequenceIdToCollectible[_teamId][_sequenceId] = newNFTCryptoId;
nftTeamIndexToCollectibleCount[_teamId] = _sequenceId;
return newNFTCryptoId;
}
function getSequenceId(uint256 _teamId) internal returns (uint32) {
return (nftTeamIndexToCollectibleCount[_teamId] + 1);
}
/**
* @dev Internal function, Helps in updating the Creation Stop Time
* @param _season Season UINT Code
* @param _value 0 - Not allowed, 1 - Allowed
*/
function _updateGenerationSeasonFlag(uint256 _season, uint8 _value) internal {
generationSeasonController[_season] = _value;
}
/** @param _owner The owner whose ships tokens we are interested in.
* @dev This method MUST NEVER be called by smart contract code. First, it's fairly
* expensive (it walks the entire Collectibles owners array looking for NFT belonging to owner)
*/
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalItems = balanceOf(_owner);
uint256 resultIndex = 0;
// We count on the fact that all Collectible have IDs starting at 0 and increasing
// sequentially up to the total count.
uint256 _assetId;
for (_assetId = 0; _assetId < totalItems; _assetId++) {
result[resultIndex] = tokenOfOwnerByIndex(_owner,_assetId);
resultIndex++;
}
return result;
}
}
/// @dev internal function to update MLB player id
function _updateMLBPlayerId(uint256 _tokenId, uint256 _newMLBPlayerId) internal {
// Get Token Obj
NFT storage lsnftObj = allNFTs[_tokenId];
lsnftObj.mlbPlayerId = _newMLBPlayerId;
// Update Token Data with new updated attributes
allNFTs[_tokenId] = lsnftObj;
emit AssetUpdated(_tokenId);
}
/// @dev internal function to update asset earnedBy value for an asset/token
function _updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) internal {
// Get Token Obj
NFT storage lsnftObj = allNFTs[_tokenId];
lsnftObj.earnedBy = _earnedBy;
// Update Token Data with new updated attributes
allNFTs[_tokenId] = lsnftObj;
emit AssetUpdated(_tokenId);
}
}
/* Handles creating new Collectibles for promo and seed.
* @title CollectibleMinting Minting
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
* Inspired and adapted from KittyCore.sol created by Axiom Zen
* Ref: ETH Contract - 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d
*/
contract CollectibleMinting is CollectibleBase, OperationalControl {
uint256 public rewardsRedeemed = 0;
/// @dev Counts the number of promo collectibles that can be made per-team
uint256[31] public promoCreatedCount;
/// @dev Counts the number of seed collectibles that can be made in total
uint256 public seedCreatedCount;
/// @dev Bool to toggle batch support
bool public isBatchSupported = true;
/// @dev A mapping of contracts that can trigger functions
mapping (address => bool) public contractsApprovedList;
/**
* @dev Helps to toggle batch supported flag
* @param _flag The flag
*/
function updateBatchSupport(bool _flag) public onlyManager {
isBatchSupported = _flag;
}
modifier canCreate() {
require (contractsApprovedList[msg.sender] ||
msg.sender == managerPrimary ||
msg.sender == managerSecondary);
_;
}
/**
* @dev Add an address to the Approved List
* @param _newAddress The new address to be approved for interaction with the contract
*/
function addToApproveList(address _newAddress) public onlyManager {
require (!contractsApprovedList[_newAddress]);
contractsApprovedList[_newAddress] = true;
}
/**
* @dev Remove an address from Approved List
* @param _newAddress The new address to be approved for interaction with the contract
*/
function removeFromApproveList(address _newAddress) public onlyManager {
require (contractsApprovedList[_newAddress]);
delete contractsApprovedList[_newAddress];
}
/**
* @dev Generates promo collectibles. Only callable by Game Master, with isAttached as 0.
* @notice The generation of an asset if limited via the generationSeasonController
* @param _teamId teamId of the asset/token/collectible
* @param _posId position of the asset/token/collectible
* @param _attributes attributes of asset/token/collectible
* @param _owner owner of asset/token/collectible
* @param _gameId mlb game Identifier
* @param _playerOverrideId player override identifier
* @param _mlbPlayerId official mlb player identifier
*/
function createPromoCollectible(
uint8 _teamId,
uint8 _posId,
uint256 _attributes,
address _owner,
uint256 _gameId,
uint256 _playerOverrideId,
uint256 _mlbPlayerId)
external
canCreate
whenNotPaused
returns (uint256)
{
address nftOwner = _owner;
if (nftOwner == address(0)) {
nftOwner = managerPrimary;
}
if(allNFTs.length > 0) {
promoCreatedCount[_teamId]++;
}
uint32 _sequenceId = getSequenceId(_teamId);
uint256 assetDetails = uint256(uint64(now));
assetDetails |= uint256(_sequenceId)<<64;
assetDetails |= uint256(_teamId)<<96;
assetDetails |= uint256(_posId)<<104;
uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];
return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);
}
/**
* @dev Generaes a new single seed Collectible, with isAttached as 0.
* @notice Helps in creating seed collectible.The generation of an asset if limited via the generationSeasonController
* @param _teamId teamId of the asset/token/collectible
* @param _posId position of the asset/token/collectible
* @param _attributes attributes of asset/token/collectible
* @param _owner owner of asset/token/collectible
* @param _gameId mlb game Identifier
* @param _playerOverrideId player override identifier
* @param _mlbPlayerId official mlb player identifier
*/
function createSeedCollectible(
uint8 _teamId,
uint8 _posId,
uint256 _attributes,
address _owner,
uint256 _gameId,
uint256 _playerOverrideId,
uint256 _mlbPlayerId)
external
canCreate
whenNotPaused
returns (uint256) {
address nftOwner = _owner;
if (nftOwner == address(0)) {
nftOwner = managerPrimary;
}
seedCreatedCount++;
uint32 _sequenceId = getSequenceId(_teamId);
uint256 assetDetails = uint256(uint64(now));
assetDetails |= uint256(_sequenceId)<<64;
assetDetails |= uint256(_teamId)<<96;
assetDetails |= uint256(_posId)<<104;
uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];
return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);
}
/**
* @dev Generate new Reward Collectible and transfer it to the owner, with isAttached as 0.
* @notice Helps in redeeming the Rewards using our Oracle. Creates & transfers the asset to the redeemer (_owner)
* The generation of an asset if limited via the generationSeasonController
* @param _teamId teamId of the asset/token/collectible
* @param _posId position of the asset/token/collectible
* @param _attributes attributes of asset/token/collectible
* @param _owner owner (redeemer) of asset/token/collectible
* @param _gameId mlb game Identifier
* @param _playerOverrideId player override identifier
* @param _mlbPlayerId official mlb player identifier
*/
function createRewardCollectible (
uint8 _teamId,
uint8 _posId,
uint256 _attributes,
address _owner,
uint256 _gameId,
uint256 _playerOverrideId,
uint256 _mlbPlayerId)
external
canCreate
whenNotPaused
returns (uint256) {
address nftOwner = _owner;
if (nftOwner == address(0)) {
nftOwner = managerPrimary;
}
rewardsRedeemed++;
uint32 _sequenceId = getSequenceId(_teamId);
uint256 assetDetails = uint256(uint64(now));
assetDetails |= uint256(_sequenceId)<<64;
assetDetails |= uint256(_teamId)<<96;
assetDetails |= uint256(_posId)<<104;
uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];
return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);
}
/**
* @dev Generate new ETH Card Collectible, with isAttached as 2.
* @notice Helps to generate Collectibles/Tokens/Asset and transfer to ETH Cards,
* which can be redeemed using our web-app.The generation of an asset if limited via the generationSeasonController
* @param _teamId teamId of the asset/token/collectible
* @param _posId position of the asset/token/collectible
* @param _attributes attributes of asset/token/collectible
* @param _owner owner of asset/token/collectible
* @param _gameId mlb game Identifier
* @param _playerOverrideId player override identifier
* @param _mlbPlayerId official mlb player identifier
*/
function createETHCardCollectible (
uint8 _teamId,
uint8 _posId,
uint256 _attributes,
address _owner,
uint256 _gameId,
uint256 _playerOverrideId,
uint256 _mlbPlayerId)
external
canCreate
whenNotPaused
returns (uint256) {
address nftOwner = _owner;
if (nftOwner == address(0)) {
nftOwner = managerPrimary;
}
rewardsRedeemed++;
uint32 _sequenceId = getSequenceId(_teamId);
uint256 assetDetails = uint256(uint64(now));
assetDetails |= uint256(_sequenceId)<<64;
assetDetails |= uint256(_teamId)<<96;
assetDetails |= uint256(_posId)<<104;
uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId];
return _createNFTCollectible(_teamId, _attributes, nftOwner, 2, _nftData);
}
}
/* @title Interface for DodgersNFT Contract
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
*/
contract SaleManager {
function createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _owner) external;
}
/**
* DodgersNFT manages all aspects of the Lucid Sight, Inc. CryptoBaseball.
* @title DodgersNFT
* @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)
*/
contract DodgersNFT is CollectibleMinting {
/// @dev Set in case the DodgersNFT contract requires an upgrade
address public newContractAddress;
string public constant MLB_Legal = "Major League Baseball trademarks and copyrights are used with permission of the applicable MLB entity. All rights reserved.";
// Time LS Oracle has to respond to detach requests
uint32 public detachmentTime = 0;
// Indicates if attached system is Active (Transfers will be blocked if attached and active)
bool public attachedSystemActive;
// Sale Manager Contract
SaleManager public saleManagerAddress;
/**
* @dev DodgersNFT constructor.
*/
constructor() public {
// Starts paused.
paused = true;
managerPrimary = msg.sender;
managerSecondary = msg.sender;
bankManager = msg.sender;
name_ = "LucidSight-DODGERS-NFT";
symbol_ = "DNFTCB";
}
/**
* @dev Sets the address for the NFT Contract
* @param _saleManagerAddress The nft address
*/
function setSaleManagerAddress(address _saleManagerAddress) public onlyManager {
require (_saleManagerAddress != address(0));
saleManagerAddress = SaleManager(_saleManagerAddress);
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
uint256 isAttached = checkIsAttached(_tokenId);
if(isAttached == 2) {
//One-Time Auth for Physical Card Transfers
require (msg.sender == managerPrimary ||
msg.sender == managerSecondary ||
msg.sender == bankManager ||
otherManagers[msg.sender] == 1
);
updateIsAttached(_tokenId, 0);
} else if(attachedSystemActive == true && isAttached >= 1) {
require (msg.sender == managerPrimary ||
msg.sender == managerSecondary ||
msg.sender == bankManager ||
otherManagers[msg.sender] == 1
);
}
else {
require (isApprovedOrOwner(msg.sender, _tokenId));
}
_;
}
/**
* @dev Used to mark the smart contract as upgraded, in case of a issue
* @param _v2Address The new contract address
*/
function setNewAddress(address _v2Address) external onlyManager {
require (_v2Address != address(0));
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/**
* @dev Returns all the relevant information about a specific Collectible.
* @notice Get details about your collectible
* @param _tokenId The token identifier
* @return isAttached Is Object attached
* @return teamId team identifier of the asset/token/collectible
* @return positionId position identifier of the asset/token/collectible
* @return creationTime creation timestamp
* @return attributes attribute of the asset/token/collectible
* @return currentGameCardId current game card of the asset/token/collectible
* @return mlbGameID mlb game identifier in which the asset/token/collectible was generated
* @return playerOverrideId player override identifier of the asset/token/collectible
* @return playerStatus status of the player (Rookie/Veteran/Historical)
* @return playerHandedness handedness of the asset
* @return mlbPlayerId official MLB Player Identifier
*/
function getCollectibleDetails(uint256 _tokenId)
external
view
returns (
uint256 isAttached,
uint32 sequenceId,
uint8 teamId,
uint8 positionId,
uint64 creationTime,
uint256 attributes,
uint256 playerOverrideId,
uint256 mlbGameId,
uint256 currentGameCardId,
uint256 mlbPlayerId,
uint256 earnedBy,
uint256 generationSeason
) {
NFT memory obj = _getAttributesOfToken(_tokenId);
attributes = obj.attributes;
currentGameCardId = obj.currentGameCardId;
mlbGameId = obj.mlbGameId;
playerOverrideId = obj.playerOverrideId;
mlbPlayerId = obj.mlbPlayerId;
creationTime = uint64(obj.assetDetails);
sequenceId = uint32(obj.assetDetails>>64);
teamId = uint8(obj.assetDetails>>96);
positionId = uint8(obj.assetDetails>>104);
isAttached = obj.isAttached;
earnedBy = obj.earnedBy;
generationSeason = generationSeasonDict[(obj.attributes % 1000000) / 1000];
}
/**
* @dev This is public rather than external so we can call super.unpause
* without using an expensive CALL.
*/
function unpause() public onlyManager {
/// Actually unpause the contract.
super.unpause();
}
/**
* @dev Helper function to get the teamID of a collectible.To avoid using getCollectibleDetails
* @notice Returns the teamID associated with the asset/collectible/token
* @param _tokenId The token identifier
*/
function getTeamId(uint256 _tokenId) external view returns (uint256) {
NFT memory obj = _getAttributesOfToken(_tokenId);
uint256 teamId = uint256(uint8(obj.assetDetails>>96));
return uint256(teamId);
}
/**
* @dev Helper function to get the position of a collectible.To avoid using getCollectibleDetails
* @notice Returns the position of the asset/collectible/token
* @param _tokenId The token identifier
*/
function getPositionId(uint256 _tokenId) external view returns (uint256) {
NFT memory obj = _getAttributesOfToken(_tokenId);
uint256 positionId = uint256(uint8(obj.assetDetails>>104));
return positionId;
}
/**
* @dev Helper function to get the game card. To avoid using getCollectibleDetails
* @notice Returns the gameCard associated with the asset/collectible/token
* @param _tokenId The token identifier
*/
function getGameCardId(uint256 _tokenId) public view returns (uint256) {
NFT memory obj = _getAttributesOfToken(_tokenId);
return obj.currentGameCardId;
}
/**
* @dev Returns isAttached property value for an asset/collectible/token
* @param _tokenId The token identifier
*/
function checkIsAttached(uint256 _tokenId) public view returns (uint256) {
NFT memory obj = _getAttributesOfToken(_tokenId);
return obj.isAttached;
}
/**
* @dev Helper function to get the attirbute of the collectible.To avoid using getCollectibleDetails
* @notice Returns the ability of an asset/collectible/token from attributes.
* @param _tokenId The token identifier
* @return ability ability of the asset
*/
function getAbilitiesForCollectibleId(uint256 _tokenId) external view returns (uint256 ability) {
NFT memory obj = _getAttributesOfToken(_tokenId);
uint256 _attributes = uint256(obj.attributes);
ability = (_attributes % 1000);
}
/**
* @dev Only allows trasnctions to go throught if the msg.sender is in the apporved list
* @notice Updates the gameCardID properrty of the asset
* @param _gameCardNumber The game card number
* @param _playerId The player identifier
*/
function updateCurrentGameCardId(uint256 _gameCardNumber, uint256 _playerId) public whenNotPaused {
require (contractsApprovedList[msg.sender]);
NFT memory obj = _getAttributesOfToken(_playerId);
obj.currentGameCardId = _gameCardNumber;
if ( _gameCardNumber == 0 ) {
obj.isAttached = 0;
} else {
obj.isAttached = 1;
}
allNFTs[_playerId] = obj;
}
/**
* @dev Only Manager can add an attachment (special events) to the collectible
* @notice Adds an attachment to collectible.
* @param _tokenId The token identifier
* @param _attachment The attachment
*/
function addAttachmentToCollectible (
uint256 _tokenId,
uint256 _attachment)
external
onlyManager
whenNotPaused {
require (exists(_tokenId));
nftCollectibleAttachments[_tokenId].push(_attachment);
emit AssetUpdated(_tokenId);
}
/**
* @dev It will remove the attachment form the collectible. We will need to re-add all attachment(s) if removed.
* @notice Removes all attachments from collectible.
* @param _tokenId The token identifier
*/
function removeAllAttachmentsFromCollectible(uint256 _tokenId)
external
onlyManager
whenNotPaused {
require (exists(_tokenId));
delete nftCollectibleAttachments[_tokenId];
emit AssetUpdated(_tokenId);
}
/**
* @notice Transfers the ownership of NFT from one address to another address
* @dev responsible for gifting assets to other user.
* @param _to to address
* @param _tokenId The token identifier
*/
function giftAsset(address _to, uint256 _tokenId) public whenNotPaused {
safeTransferFrom(msg.sender, _to, _tokenId);
}
/**
* @dev responsible for setting the tokenURI.
* @notice The user/developper needs to add the tokenID, in the end of URL, to
* use the URI and get all details. Ex. www.<apiURL>.com/token/<tokenID>
* @param _tokenURI The token uri
*/
function setTokenURIBase (string _tokenURI) public anyOperator {
_setTokenURIBase(_tokenURI);
}
/**
* @dev Allowed to be called by onlyGameManager to update a certain collectible playerOverrideID
* @notice Sets the player override identifier.
* @param _tokenId The token identifier
* @param _newOverrideId The new player override identifier
*/
function setPlayerOverrideId(uint256 _tokenId, uint256 _newOverrideId) public onlyManager whenNotPaused {
require (exists(_tokenId));
_updatePlayerOverrideId(_tokenId, _newOverrideId);
}
/**
* @notice Updates the Generation Season Controller.
* @dev Allowed to be called by onlyGameManager to update the generation season.
* this helps to control the generation of collectible.
* @param _season Season UINT representation
* @param _value 0-Not allowed, 1-open, >=2 Locked Forever
*/
function updateGenerationStopTime(uint256 _season, uint8 _value ) public onlyManager whenNotPaused {
require (generationSeasonController[_season] == 1 && _value != 0);
_updateGenerationSeasonFlag(_season, _value);
}
/**
* @dev set Generation Season Controller, can only be called by Managers._season can be [0,1,2,3..] and
* _value can be [0,1,N].
* @notice _value of 1: means generation of collectible is allowed. anything, apart from 1, wont allow generating assets for that season.
* @param _season Season UINT representation
*/
function setGenerationSeasonController(uint256 _season) public onlyManager whenNotPaused {
require (generationSeasonController[_season] == 0);
_updateGenerationSeasonFlag(_season, 1);
}
/**
* @dev Adding value to DICT helps in showing the season value in getCollectibleDetails
* @notice Updates the Generation Season Dict.
* @param _season Season UINT representation
* @param _value 0-Not allowed,1-allowed
*/
function updateGenerationDict(uint256 _season, uint64 _value) public onlyManager whenNotPaused {
require (generationSeasonDict[_season] <= 1);
generationSeasonDict[_season] = _value;
}
/**
* @dev Helper function to avoid calling getCollectibleDetails
* @notice Gets the MLB player Id from the player attributes
* @param _tokenId The token identifier
* @return playerId MLB Player Identifier
*/
function getPlayerId(uint256 _tokenId) external view returns (uint256 playerId) {
NFT memory obj = _getAttributesOfToken(_tokenId);
playerId = ((obj.attributes.div(100000000000000000)) % 1000);
}
/**
* @dev Helper function to avoid calling getCollectibleDetails
* @notice Gets the attachments for an asset
* @param _tokenId The token identifier
* @return attachments
*/
function getAssetAttachment(uint256 _tokenId) external view returns (uint256[]) {
uint256[] _attachments = nftCollectibleAttachments[_tokenId];
uint256[] attachments;
for(uint i=0;i<_attachments.length;i++){
attachments.push(_attachments[i]);
}
return attachments;
}
/**
* @dev Can only be trigerred by Managers. Updates the earnedBy property of the NFT
* @notice Helps in updating the earned _by property of an asset/token.
* @param _tokenId asser/token identifier
* @param _earnedBy New asset/token DNA
*/
function updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) public onlyManager whenNotPaused {
require (exists(_tokenId));
_updateEarnedBy(_tokenId, _earnedBy);
}
/**
* @dev A batch function to facilitate batching of asset creation. canCreate modifier
* helps in controlling who can call the function
* @notice Batch Function to Create Assets
* @param _teamId The team identifier
* @param _attributes The attributes
* @param _playerOverrideId The player override identifier
* @param _mlbPlayerId The mlb player identifier
* @param _to To Address
*/
function batchCreateAsset(
uint8[] _teamId,
uint256[] _attributes,
uint256[] _playerOverrideId,
uint256[] _mlbPlayerId,
address[] _to)
external
canCreate
whenNotPaused {
require (isBatchSupported);
require (_teamId.length > 0 && _attributes.length > 0 &&
_playerOverrideId.length > 0 && _mlbPlayerId.length > 0 &&
_to.length > 0);
uint256 assetDetails;
uint256[5] memory _nftData;
for(uint ii = 0; ii < _attributes.length; ii++){
require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 &&
_mlbPlayerId[ii] != 0);
assetDetails = uint256(uint64(now));
assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64;
assetDetails |= uint256(_teamId[ii])<<96;
assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104;
_nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]];
_createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 0, _nftData);
}
}
/**
* @dev A batch function to facilitate batching of asset creation for ETH Cards. canCreate modifier
* helps in controlling who can call the function
* @notice Batch Function to Create Assets
* @param _teamId The team identifier
* @param _attributes The attributes
* @param _playerOverrideId The player override identifier
* @param _mlbPlayerId The mlb player identifier
* @param _to { parameter_description }
*/
function batchCreateETHCardAsset(
uint8[] _teamId,
uint256[] _attributes,
uint256[] _playerOverrideId,
uint256[] _mlbPlayerId,
address[] _to)
external
canCreate
whenNotPaused {
require (isBatchSupported);
require (_teamId.length > 0 && _attributes.length > 0
&& _playerOverrideId.length > 0 &&
_mlbPlayerId.length > 0 && _to.length > 0);
uint256 assetDetails;
uint256[5] memory _nftData;
for(uint ii = 0; ii < _attributes.length; ii++){
require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 &&
_mlbPlayerId[ii] != 0);
assetDetails = uint256(uint64(now));
assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64;
assetDetails |= uint256(_teamId[ii])<<96;
assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104;
_nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]];
_createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 2, _nftData);
}
}
/**
* @dev Overriden TransferFrom, with the modifier canTransfer which uses our attachment system
* @notice Helps in trasnferring assets
* @param _from the address sending from
* @param _to the address sending to
* @param _tokenId The token identifier
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// Asset should not be in play
require (checkIsAttached(_tokenId) == 0);
require (_from != address(0));
require (_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Facilitates batch trasnfer of collectible with multiple TO Address, depending if batch is supported on contract.
* @notice Batch Trasnfer with multpple TO addresses
* @param _tokenIds The token identifiers
* @param _fromB the address sending from
* @param _toB the address sending to
*/
function multiBatchTransferFrom(
uint256[] _tokenIds,
address[] _fromB,
address[] _toB)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0);
uint256 _id;
address _to;
address _from;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0);
_id = _tokenIds[i];
_to = _toB[i];
_from = _fromB[i];
transferFrom(_from, _to, _id);
}
}
/**
* @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract
* @notice Batch TransferFrom with the same to & from address
* @param _tokenIds The asset identifiers
* @param _from the address sending from
* @param _to the address sending to
*/
function batchTransferFrom(uint256[] _tokenIds, address _from, address _to)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _from != address(0) && _to != address(0));
uint256 _id;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0);
_id = _tokenIds[i];
transferFrom(_from, _to, _id);
}
}
/**
* @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract.
* Checks for collectible 0,address 0 and then performs the transfer
* @notice Batch SafeTransferFrom with multiple From and to Addresses
* @param _tokenIds The asset identifiers
* @param _fromB the address sending from
* @param _toB the address sending to
*/
function multiBatchSafeTransferFrom(
uint256[] _tokenIds,
address[] _fromB,
address[] _toB
)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0);
uint256 _id;
address _to;
address _from;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0);
_id = _tokenIds[i];
_to = _toB[i];
_from = _fromB[i];
safeTransferFrom(_from, _to, _id);
}
}
/**
* @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract.
* Checks for collectible 0,address 0 and then performs the transfer
* @notice Batch SafeTransferFrom from a single address to another address
* @param _tokenIds The asset identifiers
* @param _from the address sending from
* @param _to the address sending to
*/
function batchSafeTransferFrom(
uint256[] _tokenIds,
address _from,
address _to
)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _from != address(0) && _to != address(0));
uint256 _id;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0);
_id = _tokenIds[i];
safeTransferFrom(_from, _to, _id);
}
}
/**
* @notice Batch Function to approve the spender
* @dev Helps to approve a batch of collectibles
* @param _tokenIds The asset identifiers
* @param _spender The spender
*/
function batchApprove(
uint256[] _tokenIds,
address _spender
)
public
{
require (isBatchSupported);
require (_tokenIds.length > 0 && _spender != address(0));
uint256 _id;
for (uint256 i = 0; i < _tokenIds.length; ++i) {
require (_tokenIds[i] != 0);
_id = _tokenIds[i];
approve(_spender, _id);
}
}
/**
* @dev Batch Function to mark spender for approved for all. Does a check
* for address(0) and throws if true
* @notice Facilitates batch approveAll
* @param _spenders The spenders
* @param _approved The approved
*/
function batchSetApprovalForAll(
address[] _spenders,
bool _approved
)
public
{
require (isBatchSupported);
require (_spenders.length > 0);
address _spender;
for (uint256 i = 0; i < _spenders.length; ++i) {
require (address(_spenders[i]) != address(0));
_spender = _spenders[i];
setApprovalForAll(_spender, _approved);
}
}
/**
* @dev Function to request Detachment from our Contract
* @notice a wallet can request to detach it collectible, so, that it can be used in other third-party contracts.
* @param _tokenId The token identifier
*/
function requestDetachment(
uint256 _tokenId
)
public
{
//Request can only be made by owner or approved address
require (isApprovedOrOwner(msg.sender, _tokenId));
uint256 isAttached = checkIsAttached(_tokenId);
//If collectible is on a gamecard prevent detachment
require(getGameCardId(_tokenId) == 0);
require (isAttached >= 1);
if(attachedSystemActive == true) {
//Checks to see if request was made and if time elapsed
if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) {
isAttached = 0;
} else if(isAttached > 1) {
//Forces Tx Fail if time is already set for attachment and not less than detachmentTime
require (isAttached == 1);
} else {
//Is attached, set detachment time and make request to detach
// emit AssetUpdated(_tokenId);
isAttached = block.timestamp;
}
} else {
isAttached = 0;
}
updateIsAttached(_tokenId, isAttached);
}
/**
* @dev Function to attach the asset, thus, restricting transfer
* @notice Attaches the collectible to our contract
* @param _tokenId The token identifier
*/
function attachAsset(
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
uint256 isAttached = checkIsAttached(_tokenId);
require (isAttached == 0);
isAttached = 1;
updateIsAttached(_tokenId, isAttached);
emit AssetUpdated(_tokenId);
}
/**
* @dev Batch attach function
* @param _tokenIds The identifiers
*/
function batchAttachAssets(uint256[] _tokenIds) public {
require (isBatchSupported);
for(uint i = 0; i < _tokenIds.length; i++) {
attachAsset(_tokenIds[i]);
}
}
/**
* @dev Batch detach function
* @param _tokenIds The identifiers
*/
function batchDetachAssets(uint256[] _tokenIds) public {
require (isBatchSupported);
for(uint i = 0; i < _tokenIds.length; i++) {
requestDetachment(_tokenIds[i]);
}
}
/**
* @dev Function to facilitate detachment when contract is paused
* @param _tokenId The identifiers
*/
function requestDetachmentOnPause (uint256 _tokenId) public whenPaused {
//Request can only be made by owner or approved address
require (isApprovedOrOwner(msg.sender, _tokenId));
updateIsAttached(_tokenId, 0);
}
/**
* @dev Toggle the Attachment Switch
* @param _state The state
*/
function toggleAttachedEnforcement (bool _state) public onlyManager {
attachedSystemActive = _state;
}
/**
* @dev Set Attachment Time Period (this restricts user from continuously trigger detachment)
* @param _time The time
*/
function setDetachmentTime (uint256 _time) public onlyManager {
//Detactment Time can not be set greater than 2 weeks.
require (_time <= 1209600);
detachmentTime = uint32(_time);
}
/**
* @dev Detach Asset From System
* @param _tokenId The token iddentifier
*/
function setNFTDetached(uint256 _tokenId) public anyOperator {
require (checkIsAttached(_tokenId) > 0);
updateIsAttached(_tokenId, 0);
}
/**
* @dev Batch function to detach multiple assets
* @param _tokenIds The token identifiers
*/
function setBatchDetachCollectibles(uint256[] _tokenIds) public anyOperator {
uint256 _id;
for(uint i = 0; i < _tokenIds.length; i++) {
_id = _tokenIds[i];
setNFTDetached(_id);
}
}
/**
* @dev Function to update attach value
* @param _tokenId The asset id
* @param _isAttached Indicates if attached
*/
function updateIsAttached(uint256 _tokenId, uint256 _isAttached) internal {
NFT memory obj = _getAttributesOfToken(_tokenId);
obj.isAttached = _isAttached;
allNFTs[_tokenId] = obj;
emit AssetUpdated(_tokenId);
}
/**
* @dev Facilitates Creating Sale using the Sale Contract. Forces owner check & collectibleId check
* @notice Helps a wallet to create a sale using our Sale Contract
* @param _tokenId The token identifier
* @param _startingPrice The starting price
* @param _endingPrice The ending price
* @param _duration The duration
*/
function initiateCreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external {
require (_tokenId != 0);
// If DodgersNFT is already on any sale, this will throw
// because it will be owned by the sale contract.
address owner = ownerOf(_tokenId);
require (owner == msg.sender);
// Sale contract checks input sizes
require (_startingPrice == _startingPrice);
require (_endingPrice == _endingPrice);
require (_duration == _duration);
require (checkIsAttached(_tokenId) == 0);
// One time approval for the tokenID
_approveForSale(msg.sender, address(saleManagerAddress), _tokenId);
saleManagerAddress.createSale(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender);
}
/**
* @dev Facilitates batch auction of collectibles, and enforeces strict checking on the collectibleId,starting/ending price, duration.
* @notice Batch function to put 10 or less collectibles on sale
* @param _tokenIds The token identifier
* @param _startingPrices The starting price
* @param _endingPrices The ending price
* @param _durations The duration
*/
function batchCreateAssetSale(uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256[] _durations) external whenNotPaused {
require (_tokenIds.length > 0 && _startingPrices.length > 0 && _endingPrices.length > 0 && _durations.length > 0);
// Sale contract checks input sizes
for(uint ii = 0; ii < _tokenIds.length; ii++){
// Do not process for tokenId 0
require (_tokenIds[ii] != 0);
require (_startingPrices[ii] == _startingPrices[ii]);
require (_endingPrices[ii] == _endingPrices[ii]);
require (_durations[ii] == _durations[ii]);
// If DodgersNFT is already on any sale, this will throw
// because it will be owned by the sale contract.
address _owner = ownerOf(_tokenIds[ii]);
address _msgSender = msg.sender;
require (_owner == _msgSender);
// Check whether the collectible is inPlay. If inPlay cant put it on Sale
require (checkIsAttached(_tokenIds[ii]) == 0);
// approve token to for Sale creation
_approveForSale(msg.sender, address(saleManagerAddress), _tokenIds[ii]);
saleManagerAddress.createSale(_tokenIds[ii], _startingPrices[ii], _endingPrices[ii], _durations[ii], msg.sender);
}
}
} | Gets the token ID at a given index of all the tokens in this contract Reverts if the index is greater or equal to the total number of tokens _index uint256 representing the index to be accessed of the tokens list return uint256 token ID at the given index of the tokens list/ | function tokenByIndex(uint256 _index) public view returns (uint256) {
require (_index < totalSupply());
return allTokens[_index];
}
| 7,722,416 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// >>>>>>>>>> !IMPORTANT! <<<<<<<<<<<
// this is an invalid token sale contract which requrie more gas with each allocation, why though ?
// i managed to fix the above by performing checks on mapping instead of array
import "@openzeppelin/contracts/access/Ownable.sol";
/*
* @dev Allows to create allocations for token sale.
*/
contract InvalidPresale is Ownable {
uint256 constant EVERYONE_ALLOCATION_DELAY = 1 hours;
uint256 constant OWNER_PAYOUT_DELAY = 30 days;
uint256 private _closingAllocationsRemainder;
uint256 private _minimumAllocation;
uint256 private _maximumAllocation;
uint256 private _totalAllocationsLimit;
uint256 private _totalAllocated;
uint256 private _saleStart;
bool private _isEveryoneAllowedToParticipateAfterDelay;
bool private _wasClosed;
bool private _wasStarted;
mapping(address => uint256) private _allocations;
mapping(address => bool) private _allowedParticipants;
address[] _allowedParticipantList;
address[] private _participants;
event SaleStarted();
event SaleClosed();
event Allocated(address indexed participant, uint256 allocation);
/**
* @dev Initializes sale contract with minimum and maximum amount that can be allocated and total allocation limit.
* @param _initialAllowedParticipants List of addresses allowed to participate.
* @param _initialIsEveryoneAllowedToParticipateAfterDelayValue Decides if everyone should be allowed to participate after delay.
*/
constructor(address[] memory _initialAllowedParticipants, bool _initialIsEveryoneAllowedToParticipateAfterDelayValue)
{
_closingAllocationsRemainder = 0;
_minimumAllocation = 0;
_maximumAllocation = 0;
_totalAllocationsLimit = 0;
_totalAllocated = 0;
_saleStart = 0;
_isEveryoneAllowedToParticipateAfterDelay = _initialIsEveryoneAllowedToParticipateAfterDelayValue;
_wasClosed = false;
_wasStarted = false;
for (uint256 i = 0; i < _initialAllowedParticipants.length; ++i) {
address _selectedAddress = _initialAllowedParticipants[i];
_allowedParticipants[_selectedAddress] = true;
}
_allowedParticipantList = _initialAllowedParticipants;
}
/**
* @dev Setups and starts the sale.
* @param minimumAllocationValue Minimum allocation value.
* @param maximumAllocationValue Maximum allocation value.
* @param totalAllocationsLimitValue Total allocations limit.
* @param closingAllocationsRemainderValue Remaining amount of allocations allowing to close sale before reaching total allocations limit.
*/
function startSale(
uint256 minimumAllocationValue,
uint256 maximumAllocationValue,
uint256 totalAllocationsLimitValue,
uint256 closingAllocationsRemainderValue
) public onlyOwner {
require(!_wasStarted, "PresalePublic: Sale was already started");
_closingAllocationsRemainder = closingAllocationsRemainderValue;
_minimumAllocation = minimumAllocationValue;
_maximumAllocation = maximumAllocationValue;
_totalAllocationsLimit = totalAllocationsLimitValue;
_saleStart = block.timestamp;
_wasStarted = true;
emit SaleStarted();
}
/**
* @dev Allows to allocate currency for the sale.
*/
function allocate() public payable {
require(wasStarted(), "PresalePublic: Cannot allocate yet");
require(areAllocationsAccepted(), "PresalePublic: Cannot allocate anymore");
require((msg.value >= _minimumAllocation), "PresalePublic: Allocation is too small");
require(((msg.value + _allocations[msg.sender]) <= _maximumAllocation), "PresalePublic: Allocation is too big");
require(canAllocate(msg.sender), "PresalePublic: Not allowed to participate");
_totalAllocated += msg.value;
if (_allocations[msg.sender] == 0) {
_participants.push(msg.sender);
}
_allocations[msg.sender] += msg.value;
emit Allocated(msg.sender, msg.value);
}
/**
* @dev Allows the owner to close sale and payout all currency.
*/
function closeSale() public onlyOwner {
require(canCloseSale(), "PresalePublic: Cannot payout yet");
payable(owner()).transfer(address(this).balance);
_wasClosed = true;
emit SaleClosed();
}
/**
* @dev Extend the allowed participants list.
*/
function addAllowedParticipants(address[] memory participantsValue) public onlyOwner {
require(areAllocationsAccepted(), "PresalePublic: Allocations were already closed");
for (uint256 i = 0; i < participantsValue.length; ++i) {
address _selectedAddress = participantsValue[i];
if (!_allowedParticipants[_selectedAddress]) {
_allowedParticipantList.push(_selectedAddress);
}
_allowedParticipants[_selectedAddress] = true;
}
}
/**
* @dev Returns amount allocated from given address.
* @param participant Address to check.
*/
function allocation(address participant) public view returns (uint256) {
return _allocations[participant];
}
/**
* @dev Return the allowed participants list.
*/
function allowedParticipants() public view returns (address[] memory) {
return _allowedParticipantList;
}
/**
* @dev Checks if allocations are still accepted.
*/
function areAllocationsAccepted() public view returns (bool) {
return (isActive() && (_totalAllocationsLimit - _totalAllocated) >= _minimumAllocation);
}
/**
* @dev Checks if given address can still allocate.
*/
function canAllocate(address participant) public view returns (bool) {
if (!areAllocationsAccepted() || !isAllowedToParticipate(participant)) {
return false;
}
return ((_allocations[participant] + _minimumAllocation) <= _maximumAllocation);
}
/**
* @dev Checks if owner can close sale and payout the currency.
*/
function canCloseSale() public view returns (bool) {
return (isActive() &&
(!areAllocationsAccepted() ||
_closingAllocationsRemainder >= (_totalAllocationsLimit - _totalAllocated) ||
block.timestamp >= (_saleStart + OWNER_PAYOUT_DELAY)));
}
/**
* @dev Returns remaining amount of allocations allowing to close sale before reaching total allocations limit.
*/
function closingAllocationsRemainder() public view returns (uint256) {
return _closingAllocationsRemainder;
}
/**
* @dev Checks if given address is allowed to participate.
*/
function isAllowedToParticipate(address participant) public view returns (bool) {
if (
_isEveryoneAllowedToParticipateAfterDelay &&
_wasStarted &&
block.timestamp >= (_saleStart + EVERYONE_ALLOCATION_DELAY)
) {
return true;
}
return bool(_allowedParticipants[participant]);
}
/**
* @dev Checks if sale is active.
*/
function isActive() public view returns (bool) {
return (_wasStarted && !_wasClosed);
}
/**
* @dev Checks if everyone is allowed to participate after delay.
*/
function isEveryoneAllowedToParticipateAfterDelay() public view returns (bool) {
return _isEveryoneAllowedToParticipateAfterDelay;
}
/**
* @dev Returns minimum allocation amount.
*/
function minimumAllocation() public view returns (uint256) {
return _minimumAllocation;
}
/**
* @dev Returns maximum allocation amount.
*/
function maximumAllocation() public view returns (uint256) {
return _maximumAllocation;
}
/**
* @dev Returns the participants list.
*/
function participants() public view returns (address[] memory) {
return _participants;
}
/**
* @dev Returns sale start timestamp.
*/
function saleStart() public view returns (uint256) {
return _saleStart;
}
/**
* @dev Returns total allocations limit.
*/
function totalAllocationsLimit() public view returns (uint256) {
return _totalAllocationsLimit;
}
/**
* @dev Returns allocated amount.
*/
function totalAllocated() public view returns (uint256) {
return _totalAllocated;
}
/**
* @dev Checks if sale was already started.
*/
function wasStarted() public view returns (bool) {
return _wasStarted;
}
/**
* @dev Checks if sale was already closed.
*/
function wasClosed() public view returns (bool) {
return _wasClosed;
}
/**
* @dev Fallback receive method.
*/
receive() external payable {
allocate();
}
}
| Setups and starts the sale. minimumAllocationValue Minimum allocation value. maximumAllocationValue Maximum allocation value. totalAllocationsLimitValue Total allocations limit. closingAllocationsRemainderValue Remaining amount of allocations allowing to close sale before reaching total allocations limit./ | function startSale(
uint256 minimumAllocationValue,
uint256 maximumAllocationValue,
uint256 totalAllocationsLimitValue,
uint256 closingAllocationsRemainderValue
) public onlyOwner {
require(!_wasStarted, "PresalePublic: Sale was already started");
_closingAllocationsRemainder = closingAllocationsRemainderValue;
_minimumAllocation = minimumAllocationValue;
_maximumAllocation = maximumAllocationValue;
_totalAllocationsLimit = totalAllocationsLimitValue;
_saleStart = block.timestamp;
_wasStarted = true;
emit SaleStarted();
}
| 983,032 |
./full_match/80001/0xD4b7bd77B3a04c4000387dBF711040f23C31Ef4b/sources/contracts/ERC721A.sol | Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the call return bool whether the call correctly returned the expected magic value/ | ) private returns (bool) {
function _approve(
address to,
uint256 tokenId,
address owner
}
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} catch (bytes memory reason) {
function _approve(
address to,
uint256 tokenId,
address owner
}
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
function _approve(
address to,
uint256 tokenId,
address owner
}
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
| 5,568,985 |
pragma solidity ^0.4.13;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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 constant 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 constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title 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 constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/////////////////////////////////////////////////////////
//////////////// Token contract start////////////////////
/////////////////////////////////////////////////////////
contract CryptoGripInitiative is StandardToken, Ownable {
string public constant name = "Crypto Grip Initiative";
string public constant symbol = "CGI";
uint public constant decimals = 18;
uint public saleStartTime;
uint public saleEndTime;
address public tokenSaleContract;
modifier onlyWhenTransferEnabled() {
if (now <= saleEndTime && now >= saleStartTime) {
require(msg.sender == tokenSaleContract || msg.sender == owner);
}
_;
}
modifier validDestination(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function CryptoGripInitiative(uint tokenTotalAmount, uint startTime, uint endTime, address admin) {
// Mint all tokens. Then disable minting forever.
balances[msg.sender] = tokenTotalAmount;
totalSupply = tokenTotalAmount;
Transfer(address(0x0), msg.sender, tokenTotalAmount);
saleStartTime = startTime;
saleEndTime = endTime;
tokenSaleContract = msg.sender;
transferOwnership(admin);
// admin could drain tokens that were sent here by mistake
}
function transfer(address _to, uint _value)
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value)
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transferFrom(_from, _to, _value);
}
event Burn(address indexed _burner, uint _value);
function burn(uint _value) onlyWhenTransferEnabled
returns (bool){
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
Transfer(msg.sender, address(0x0), _value);
return true;
}
// // save some gas by making only one contract call
// function burnFrom(address _from, uint256 _value) onlyWhenTransferEnabled
// returns (bool) {
// assert(transferFrom(_from, msg.sender, _value));
// return burn(_value);
// }
function emergencyERC20Drain(ERC20 token, uint amount) onlyOwner {
token.transfer(owner, amount);
}
}
/////////////////////////////////////////////////////////
/////////////// Whitelist contract start/////////////////
/////////////////////////////////////////////////////////
contract Whitelist {
address public owner;
address public sale;
mapping (address => uint) public accepted;
function Whitelist(address _owner, address _sale) {
owner = _owner;
sale = _sale;
}
function accept(address a, uint amountInWei) {
assert(msg.sender == owner || msg.sender == sale);
accepted[a] = amountInWei * 10 ** 18;
}
function setSale(address sale_) {
assert(msg.sender == owner);
sale = sale_;
}
function getCap(address _user) constant returns (uint) {
uint cap = accepted[_user];
return cap;
}
}
/////////////////////////////////////////////////////////
///////// Contributor Approver contract start////////////
/////////////////////////////////////////////////////////
contract ContributorApprover {
Whitelist public list;
mapping (address => uint) public participated;
uint public presaleStartTime;
uint public remainingPresaleCap;
uint public remainingPublicSaleCap;
uint public openSaleStartTime;
uint public openSaleEndTime;
using SafeMath for uint;
function ContributorApprover(
Whitelist _whitelistContract,
uint preIcoCap,
uint IcoCap,
uint _presaleStartTime,
uint _openSaleStartTime,
uint _openSaleEndTime) {
list = _whitelistContract;
openSaleStartTime = _openSaleStartTime;
openSaleEndTime = _openSaleEndTime;
presaleStartTime = _presaleStartTime;
remainingPresaleCap = preIcoCap * 10 ** 18;
remainingPublicSaleCap = IcoCap * 10 ** 18;
// Check that presale is earlier than opensale
require(presaleStartTime < openSaleStartTime);
// Check that open sale start is earlier than end
require(openSaleStartTime < openSaleEndTime);
}
// this is a seperate function so user could query it before crowdsale starts
function contributorCap(address contributor) constant returns (uint) {
return list.getCap(contributor);
}
function eligible(address contributor, uint amountInWei) constant returns (uint) {
// Presale not started yet
if (now < presaleStartTime) return 0;
// Both presale and public sale have ended
if (now >= openSaleEndTime) return 0;
// Presale
if (now < openSaleStartTime) {
// Presale cap limit reached
if (remainingPresaleCap <= 0) {
return 0;
}
// Get initial cap
uint cap = contributorCap(contributor);
// Account for already invested amount
uint remainedCap = cap.sub(participated[contributor]);
// Presale cap almost reached
if (remainedCap > remainingPresaleCap) {
remainedCap = remainingPresaleCap;
}
// Remaining cap is bigger than contribution
if (remainedCap > amountInWei) return amountInWei;
// Remaining cap is smaller than contribution
else return remainedCap;
}
// Public sale
else {
// Public sale cap limit reached
if (remainingPublicSaleCap <= 0) {
return 0;
}
// Public sale cap almost reached
if (amountInWei > remainingPublicSaleCap) {
return remainingPublicSaleCap;
}
// Public sale cap is bigger than contribution
else {
return amountInWei;
}
}
}
function eligibleTestAndIncrement(address contributor, uint amountInWei) internal returns (uint) {
uint result = eligible(contributor, amountInWei);
participated[contributor] = participated[contributor].add(result);
// Presale
if (now < openSaleStartTime) {
// Decrement presale cap
remainingPresaleCap = remainingPresaleCap.sub(result);
}
// Publicsale
else {
// Decrement publicsale cap
remainingPublicSaleCap = remainingPublicSaleCap.sub(result);
}
return result;
}
function saleEnded() constant returns (bool) {
return now > openSaleEndTime;
}
function saleStarted() constant returns (bool) {
return now >= presaleStartTime;
}
function publicSaleStarted() constant returns (bool) {
return now >= openSaleStartTime;
}
}
/////////////////////////////////////////////////////////
///////// Token Sale contract start /////////////////////
/////////////////////////////////////////////////////////
contract CryptoGripTokenSale is ContributorApprover {
uint public constant tokensPerEthPresale = 1055;
uint public constant tokensPerEthPublicSale = 755;
address public admin;
address public gripWallet;
CryptoGripInitiative public token;
uint public raisedWei;
bool public haltSale;
function CryptoGripTokenSale(address _admin,
address _gripWallet,
Whitelist _whiteListContract,
uint _totalTokenSupply,
uint _premintedTokenSupply,
uint _presaleStartTime,
uint _publicSaleStartTime,
uint _publicSaleEndTime,
uint _presaleCap,
uint _publicSaleCap)
ContributorApprover(_whiteListContract,
_presaleCap,
_publicSaleCap,
_presaleStartTime,
_publicSaleStartTime,
_publicSaleEndTime)
{
admin = _admin;
gripWallet = _gripWallet;
token = new CryptoGripInitiative(_totalTokenSupply * 10 ** 18, _presaleStartTime, _publicSaleEndTime, _admin);
// transfer preminted tokens to company wallet
token.transfer(gripWallet, _premintedTokenSupply * 10 ** 18);
}
function setHaltSale(bool halt) {
require(msg.sender == admin);
haltSale = halt;
}
function() payable {
buy(msg.sender);
}
event Buy(address _buyer, uint _tokens, uint _payedWei);
function buy(address recipient) payable returns (uint){
require(tx.gasprice <= 50000000000 wei);
require(!haltSale);
require(saleStarted());
require(!saleEnded());
uint weiPayment = eligibleTestAndIncrement(recipient, msg.value);
require(weiPayment > 0);
// send to msg.sender, not to recipient
if (msg.value > weiPayment) {
msg.sender.transfer(msg.value.sub(weiPayment));
}
// send payment to wallet
sendETHToMultiSig(weiPayment);
raisedWei = raisedWei.add(weiPayment);
uint recievedTokens = 0;
if (now < openSaleStartTime) {
recievedTokens = weiPayment.mul(tokensPerEthPresale);
}
else {
recievedTokens = weiPayment.mul(tokensPerEthPublicSale);
}
assert(token.transfer(recipient, recievedTokens));
Buy(recipient, recievedTokens, weiPayment);
return weiPayment;
}
function sendETHToMultiSig(uint value) internal {
gripWallet.transfer(value);
}
event FinalizeSale();
// function is callable by everyone
function finalizeSale() {
require(saleEnded());
require(msg.sender == admin);
// burn remaining tokens
token.burn(token.balanceOf(this));
FinalizeSale();
}
// ETH balance is always expected to be 0.
// but in case something went wrong, we use this function to extract the eth.
function emergencyDrain(ERC20 anyToken) returns (bool){
require(msg.sender == admin);
require(saleEnded());
if (this.balance > 0) {
sendETHToMultiSig(this.balance);
}
if (anyToken != address(0x0)) {
assert(anyToken.transfer(gripWallet, anyToken.balanceOf(this)));
}
return true;
}
// just to check that funds goes to the right place
// tokens are not given in return
function debugBuy() payable {
require(msg.value == 123);
sendETHToMultiSig(msg.value);
}
} | this is a seperate function so user could query it before crowdsale starts | function contributorCap(address contributor) constant returns (uint) {
return list.getCap(contributor);
}
| 12,633,516 |
./partial_match/1/0x36888C29a7DcF91D3102a5B3E515bd355cBf75d4/sources/contracts/SpreadSheet.sol | Set the Merkle root of the BOTS -> SHEET transition Merkle tree. Emits a {SetTransitionMerkleRoot} event. Requirements: - The caller must be the owner. newTransitionMerkleRoot The new transition Merkle root. | function setTransitionMerkleRoot(bytes32 newTransitionMerkleRoot) external onlyOwner {
transitionMerkleRoot = newTransitionMerkleRoot;
emit SetTransitionMerkleRoot(newTransitionMerkleRoot);
}
| 3,982,119 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/ISinglePlus.sol";
import "../interfaces/ICompositePlus.sol";
import "../interfaces/venus/IVToken.sol";
import "../interfaces/fortube/IForTubeBank.sol";
import "../interfaces/yfi/IVault.sol";
import "../interfaces/autofarm/IAutoBTC.sol";
/**
* @dev Zap for BTC plus on BSC.
*/
contract BTCZapBsc is Initializable {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeMathUpgradeable for uint256;
event Minted(address indexed account, address indexed target, uint256 amount, uint256 mintAmount);
event Redeemed(address indexed account, address indexed source, uint256 amount, uint256 redeemAmount);
address public constant BTCB = address(0x7130d2A12B9BCbFAe4f2634d864A1Ee1Ce3Ead9c);
address public constant VENUS_BTC = address(0x882C173bC7Ff3b7786CA16dfeD3DFFfb9Ee7847B);
address public constant VENUS_BTC_PLUS = address(0xcf8D1D3Fce7C2138F85889068e50F0e7a18b5321);
address public constant FORTUBE_BTCB = address(0xb5C15fD55C73d9BeeC046CB4DAce1e7975DcBBBc);
address public constant FORTUBE_BANK = address(0x0cEA0832e9cdBb5D476040D58Ea07ecfbeBB7672);
address public constant FORTUBE_CONTROLLER = address(0xc78248D676DeBB4597e88071D3d889eCA70E5469);
address public constant FORTUBE_BTCB_PLUS = address(0x73FddFb941c11d16C827169Bb94aCC227841C396);
address public constant ACS_BTCB = address(0x0395fCC8E1a1E30A1427D4079aF6E23c805E3eeF);
address public constant ACS_BTCB_PLUS = address(0xD7806143A4206aa9A816b964e4c994F533b830b0);
address public constant AUTO_BTC = address(0x6B7Ea9F1EF1E6c662761201998Dc876b88Ed7414);
address public constant AUTO_BTC_PLUS = address(0x02827D495B2bBe37e1C021eB91BCdCc92cD3b604);
address public constant AUTO_BTC_V2 = address(0x5AA676577F7A69F8761F5A19ae6057A386D6a48e);
address public constant AUTO_BTC_V2_PLUS = address(0x7780b26aB2586Ad0e0192CafAAE93BfA09a106F3);
address public constant BTCB_PLUS = address(0xe884E6695C4cB3c8DEFFdB213B50f5C2a1a9E0A2);
uint256 public constant WAD = 10 ** 18;
address public governance;
/**
* @dev Initializes the Zap contract.
*/
function initialize() public initializer {
governance = msg.sender;
IERC20Upgradeable(BTCB).safeApprove(VENUS_BTC, uint256(int256(-1)));
IERC20Upgradeable(VENUS_BTC).safeApprove(VENUS_BTC_PLUS, uint256(int256(-1)));
IERC20Upgradeable(BTCB).safeApprove(FORTUBE_CONTROLLER, uint256(int256(-1)));
IERC20Upgradeable(FORTUBE_BTCB).safeApprove(FORTUBE_BTCB_PLUS, uint256(int256(-1)));
IERC20Upgradeable(BTCB).safeApprove(ACS_BTCB, uint256(int256(-1)));
IERC20Upgradeable(ACS_BTCB).safeApprove(ACS_BTCB_PLUS, uint256(int256(-1)));
IERC20Upgradeable(BTCB).safeApprove(AUTO_BTC, uint256(int256(-1)));
IERC20Upgradeable(AUTO_BTC).safeApprove(AUTO_BTC_PLUS, uint256(int256(-1)));
IERC20Upgradeable(BTCB).safeApprove(AUTO_BTC_V2, uint256(int256(-1)));
IERC20Upgradeable(AUTO_BTC_V2).safeApprove(AUTO_BTC_V2_PLUS, uint256(int256(-1)));
IERC20Upgradeable(VENUS_BTC_PLUS).safeApprove(BTCB_PLUS, uint256(int256(-1)));
IERC20Upgradeable(ACS_BTCB_PLUS).safeApprove(BTCB_PLUS, uint256(int256(-1)));
}
/**
* @dev Mints vBTC+ with BTCB.
* @param _amount Amount of BTCB used to mint vBTC+
*/
function mintVBTCPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount);
IVToken(VENUS_BTC).mint(_amount);
uint256 _vbtc = IERC20Upgradeable(VENUS_BTC).balanceOf(address(this));
ISinglePlus(VENUS_BTC_PLUS).mint(_vbtc);
uint256 _vbtcPlus = IERC20Upgradeable(VENUS_BTC_PLUS).balanceOf(address(this));
IERC20Upgradeable(VENUS_BTC_PLUS).safeTransfer(msg.sender, _vbtcPlus);
emit Minted(msg.sender, VENUS_BTC_PLUS, _amount, _vbtcPlus);
}
/**
* @dev Redeems vBTC+ to BTCB.
* @param _amount Amount of vTCB+ to redeem.
*/
function redeemVBTCPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(VENUS_BTC_PLUS).safeTransferFrom(msg.sender, address(this), _amount);
ISinglePlus(VENUS_BTC_PLUS).redeem(_amount);
uint256 _vbtc = IERC20Upgradeable(VENUS_BTC).balanceOf(address(this));
IVToken(VENUS_BTC).redeem(_vbtc);
uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this));
IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb);
emit Redeemed(msg.sender, VENUS_BTC_PLUS, _btcb, _amount);
}
/**
* @dev Mints fBTCB+ with BTCB.
* @param _amount Amount of BTCB used to mint fBTCB+
*/
function mintFBTCBPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount);
IForTubeBank(FORTUBE_BANK).deposit(BTCB, _amount);
uint256 _fbtcb = IERC20Upgradeable(FORTUBE_BTCB).balanceOf(address(this));
ISinglePlus(FORTUBE_BTCB_PLUS).mint(_fbtcb);
uint256 _fbtcbPlus = IERC20Upgradeable(FORTUBE_BTCB_PLUS).balanceOf(address(this));
IERC20Upgradeable(FORTUBE_BTCB_PLUS).safeTransfer(msg.sender, _fbtcbPlus);
emit Minted(msg.sender, FORTUBE_BTCB_PLUS, _amount, _fbtcbPlus);
}
/**
* @dev Redeems fBTC+ to BTCB.
* @param _amount Amount of fTCB+ to redeem.
*/
function redeemFBTCBPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(FORTUBE_BTCB_PLUS).safeTransferFrom(msg.sender, address(this), _amount);
ISinglePlus(FORTUBE_BTCB_PLUS).redeem(_amount);
uint256 _fbtcb = IERC20Upgradeable(FORTUBE_BTCB).balanceOf(address(this));
IForTubeBank(FORTUBE_BANK).withdraw(BTCB, _fbtcb);
uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this));
IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb);
emit Redeemed(msg.sender, FORTUBE_BTCB_PLUS, _btcb, _amount);
}
/**
* @dev Mints acsBTCB+ with BTCB.
* @param _amount Amount of BTCB used to mint acsBTCB+
*/
function mintAcsBTCBPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount);
IVault(ACS_BTCB).deposit(_amount);
uint256 _acsBtcb = IERC20Upgradeable(ACS_BTCB).balanceOf(address(this));
ISinglePlus(ACS_BTCB_PLUS).mint(_acsBtcb);
uint256 _acsBtcbPlus = IERC20Upgradeable(ACS_BTCB_PLUS).balanceOf(address(this));
IERC20Upgradeable(ACS_BTCB_PLUS).safeTransfer(msg.sender, _acsBtcbPlus);
emit Minted(msg.sender, ACS_BTCB_PLUS, _amount, _acsBtcbPlus);
}
/**
* @dev Redeems acsBTC+ to BTCB.
* @param _amount Amount of acsTCB+ to redeem.
*/
function redeemAcsBTCBPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(ACS_BTCB_PLUS).safeTransferFrom(msg.sender, address(this), _amount);
ISinglePlus(ACS_BTCB_PLUS).redeem(_amount);
uint256 _acsBtcb = IERC20Upgradeable(ACS_BTCB).balanceOf(address(this));
IVault(ACS_BTCB).withdraw(_acsBtcb);
uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this));
IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb);
emit Redeemed(msg.sender, ACS_BTCB_PLUS, _btcb, _amount);
}
/**
* @dev Mints autoBTC+ with BTCB.
* @param _amount Amount of BTCB used to mint autoBTC+
*/
function mintAutoBTCPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount);
IAutoBTC(AUTO_BTC).mint(_amount);
uint256 _autoBtc = IERC20Upgradeable(AUTO_BTC).balanceOf(address(this));
ISinglePlus(AUTO_BTC_PLUS).mint(_autoBtc);
uint256 _autoBtcPlus = IERC20Upgradeable(AUTO_BTC_PLUS).balanceOf(address(this));
IERC20Upgradeable(AUTO_BTC_PLUS).safeTransfer(msg.sender, _autoBtcPlus);
emit Minted(msg.sender, AUTO_BTC_PLUS, _amount, _autoBtcPlus);
}
/**
* @dev Redeems autoBTC+ to BTCB.
* @param _amount Amount of autoTCB+ to redeem.
*/
function redeemAutoBTCPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(AUTO_BTC_PLUS).safeTransferFrom(msg.sender, address(this), _amount);
ISinglePlus(AUTO_BTC_PLUS).redeem(_amount);
uint256 _autoBtc = IERC20Upgradeable(AUTO_BTC).balanceOf(address(this));
IAutoBTC(AUTO_BTC).redeem(_autoBtc);
uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this));
IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb);
emit Redeemed(msg.sender, AUTO_BTC_PLUS, _btcb, _amount);
}
/**
* @dev Mints autoBTCv2+ with BTCB.
* @param _amount Amount of BTCB used to mint autoBTCv2+
*/
function mintAutoBTCV2Plus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount);
IAutoBTC(AUTO_BTC_V2).mint(_amount);
uint256 _autoBtcV2 = IERC20Upgradeable(AUTO_BTC_V2).balanceOf(address(this));
ISinglePlus(AUTO_BTC_V2_PLUS).mint(_autoBtcV2);
uint256 _autoBtcV2Plus = IERC20Upgradeable(AUTO_BTC_V2_PLUS).balanceOf(address(this));
IERC20Upgradeable(AUTO_BTC_V2_PLUS).safeTransfer(msg.sender, _autoBtcV2Plus);
emit Minted(msg.sender, AUTO_BTC_V2_PLUS, _amount, _autoBtcV2Plus);
}
/**
* @dev Redeems autoBTCv2+ to BTCB.
* @param _amount Amount of autoTCBv2+ to redeem.
*/
function redeemAutoBTCV2Plus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(AUTO_BTC_V2_PLUS).safeTransferFrom(msg.sender, address(this), _amount);
ISinglePlus(AUTO_BTC_V2_PLUS).redeem(_amount);
uint256 _autoBtcV2 = IERC20Upgradeable(AUTO_BTC_V2).balanceOf(address(this));
IAutoBTC(AUTO_BTC_V2).redeem(_autoBtcV2);
uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this));
IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb);
emit Redeemed(msg.sender, AUTO_BTC_V2_PLUS, _btcb, _amount);
}
/**
* @dev Mints BTCB+ with BTCB.
* @param _amount Amount of BTCB used to mint BTCB+
*/
function mintBTCBPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
// Always starts with vBTC+!
IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount);
IVToken(VENUS_BTC).mint(_amount);
uint256 _vbtc = IERC20Upgradeable(VENUS_BTC).balanceOf(address(this));
ISinglePlus(VENUS_BTC_PLUS).mint(_vbtc);
uint256 _vbtcPlus = IERC20Upgradeable(VENUS_BTC_PLUS).balanceOf(address(this));
address[] memory _tokens = new address[](1);
_tokens[0] = VENUS_BTC_PLUS;
uint256[] memory _amounts = new uint256[](1);
_amounts[0] = _vbtcPlus;
ICompositePlus(BTCB_PLUS).mint(_tokens, _amounts);
uint256 _btcbPlus = IERC20Upgradeable(BTCB_PLUS).balanceOf(address(this));
IERC20Upgradeable(BTCB_PLUS).safeTransfer(msg.sender, _btcbPlus);
emit Minted(msg.sender, BTCB_PLUS, _amount, _btcbPlus);
}
/**
* @dev Redeems BTCB+ to BTCB.
* @param _amount Amount of BTCB+ to redeem.
*/
function redeemBTCBPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(BTCB_PLUS).safeTransferFrom(msg.sender, address(this), _amount);
ICompositePlus(BTCB_PLUS).redeem(_amount);
uint256 _vbtcPlus = IERC20Upgradeable(VENUS_BTC_PLUS).balanceOf(address(this));
ISinglePlus(VENUS_BTC_PLUS).redeem(_vbtcPlus);
uint256 _vbtc = IERC20Upgradeable(VENUS_BTC).balanceOf(address(this));
IVToken(VENUS_BTC).redeem(_vbtc);
uint256 _acsBtcbPlus = IERC20Upgradeable(ACS_BTCB_PLUS).balanceOf(address(this));
ISinglePlus(ACS_BTCB_PLUS).redeem(_acsBtcbPlus);
uint256 _acsBtcb = IERC20Upgradeable(ACS_BTCB).balanceOf(address(this));
IVault(ACS_BTCB).withdraw(_acsBtcb);
uint256 _btcb = IERC20Upgradeable(BTCB).balanceOf(address(this));
IERC20Upgradeable(BTCB).safeTransfer(msg.sender, _btcb);
emit Redeemed(msg.sender, BTCB_PLUS, _btcb, _amount);
}
} | Mints fBTCB+ with BTCB. _amount Amount of BTCB used to mint fBTCB+/ | function mintFBTCBPlus(uint256 _amount) public {
require(_amount > 0, "zero amount");
IERC20Upgradeable(BTCB).safeTransferFrom(msg.sender, address(this), _amount);
IForTubeBank(FORTUBE_BANK).deposit(BTCB, _amount);
uint256 _fbtcb = IERC20Upgradeable(FORTUBE_BTCB).balanceOf(address(this));
ISinglePlus(FORTUBE_BTCB_PLUS).mint(_fbtcb);
uint256 _fbtcbPlus = IERC20Upgradeable(FORTUBE_BTCB_PLUS).balanceOf(address(this));
IERC20Upgradeable(FORTUBE_BTCB_PLUS).safeTransfer(msg.sender, _fbtcbPlus);
emit Minted(msg.sender, FORTUBE_BTCB_PLUS, _amount, _fbtcbPlus);
}
| 5,536,490 |
./partial_match/1/0xa22cf004eD5105608b39c48bE688BD9B9026a046/sources/FeePool.sol | A function that lets you easily convert an amount in a source currency to an amount in the destination currency sourceCurrencyKey The currency the amount is specified in sourceAmount The source amount, specified in UNIT base destinationCurrencyKey The destination currency/ If there's no change in the currency, then just return the amount they gave us Calculate the effective value by going from source -> USD -> destination | function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey)
public
view
rateNotStale(sourceCurrencyKey)
rateNotStale(destinationCurrencyKey)
returns (uint)
{
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey))
.divideDecimalRound(rateForCurrency(destinationCurrencyKey));
}
| 4,057,242 |
./full_match/11155111/0xbb15f061FA7070C8CbB1584A25997D7A06bc732f/sources/project_/contracts/Raffle.sol | when is the winner supposed to be picked? This is the function that the ChainLink Automation nodes call to see if it is time to perform an upkeep. The following should be true for this to return true: 1. The time interval has passed between raffle runs 2. The raffle is in the OPEN state. 3. The contract has ETH. 4. The subscription is funded with LINK/ | function checkUpkeep (bytes memory /* checkData */) public view returns (bool upkeepNeeded, bytes memory /* performData */) {
bool timeHasPassed = (block.timestamp - s_lastTimeStamp) >= i_interval;
bool isOpen = s_raffleState == RaffleState.OPEN;
bool hasBalance = address(this).balance > 0;
bool hasPlayers = s_players.length > 0;
upkeepNeeded = (timeHasPassed && isOpen && hasBalance && hasPlayers);
return(upkeepNeeded, "0x0");
}
| 3,823,759 |
pragma solidity 0.4.19;
contract ERC20Interface {
function transfer(address to, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function balanceOf(address who) public view returns (uint256);
}
/* 1. Contract is initiated by storing sender as OWNER and with following arguments:
* deadline : block.number which defines deadline of users authorisation and funds processing
* extendedTime : number of blocks which defines extension of deadline
* maxTime : block.number which defines maximum period for deadline extension
* manager : address which is set as MANAGER.
* Only MANAGER is allowed to perform operational functions:
* - to authorize users in General Token Sale
* - to add Tokens to the List of acceptable tokens
* recipient : multisig contract to collect unclaimed funds
* recipientContainer : multisig contract to collect other funds which remain on contract after deadline */
contract TokenSaleQueue {
using SafeMath for uint256;
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function getOwner() public view returns (address) {
return owner;
}
/* Struct with properties of each record for 'deposits' mapping */
struct Record {
uint256 balance;
bool authorized;
}
/* Contract has internal mapping `deposits`:
* Address -> (balance: uint, authorized: bool).
* It represents balance of everyone whoever used `deposit` method.
*
* This is where balances of all participants are stored. Additional flag of
* whether the participant is authorized investor is stored. This flag
* determines if the participant has passed AML/KYC check and reservation
* payment can be transferred to general Token Sale */
mapping(address => Record) public deposits;
address public manager; /* Contract administrator */
address public recipient; /* Unclaimed funds collector */
address public recipientContainer; /* Undefined funds collector */
uint public deadline; /* blocks */
uint public extendedTime; /* blocks */
uint public maxTime; /* blocks */
uint public finalTime; /* deadline + extendedTime - blocks */
/* Amount of wei raised */
uint256 public weiRaised;
function() public payable {
deposit();
}
/* A set of functions to get required variables */
function balanceOf(address who) public view returns (uint256 balance) {
return deposits[who].balance;
}
function isAuthorized(address who) public view returns (bool authorized) {
return deposits[who].authorized;
}
function getDeadline() public view returns (uint) {
return deadline;
}
function getManager() public view returns (address) {
return manager;
}
/* Contract has events for integration purposes */
event Whitelist(address who);
event Deposit(address who, uint256 amount);
event Withdrawal(address who);
event Authorized(address who);
event Process(address who);
event Refund(address who);
/* `TokenSaleQueue` is executed after the contract deployment, it sets up the Contract */
function TokenSaleQueue(address _owner, address _manager, address _recipient, address _recipientContainer, uint _deadline, uint _extendedTime, uint _maxTime) public {
require(_owner != address(0));
require(_manager != address(0));
require(_recipient != address(0));
require(_recipientContainer != address(0));
owner = _owner;
manager = _manager;
recipient = _recipient;
recipientContainer = _recipientContainer;
deadline = _deadline;
extendedTime = _extendedTime;
maxTime = _maxTime;
finalTime = deadline + extendedTime;
}
modifier onlyManager() {
require(msg.sender == manager);
_;
}
/* Contract has mapping `whitelist`.
* It contains participants addresses which have passed AML check and are allowed to deposit funds */
mapping(address => bool) whitelist;
/* Manager adds user to whitelist by executing function `addAddressInWhitelist` */
/* Contract checks if sender is equal to manager */
function addAddressInWhitelist(address who) public onlyManager {
require(who != address(0));
whitelist[who] = true;
Whitelist(who);
}
function isInWhiteList(address who) public view returns (bool result) {
return whitelist[who];
}
/* 3. Contract has payable method deposit
* Partisipant transfers reservation payment in Ether by executing this method.
* Participant can withdraw funds at anytime (4.) */
function deposit() public payable {
/* Contract checks that method invocation attaches non-zero value. */
require(msg.value > 0);
/* Contract checks whether the user is in whitelist */
require(whitelist[msg.sender]);
/* Contract checks if `finalTime` is not reached.
* If reached, it returns funds to `sender` and transfers uclaimed Ether to recipient. */
if (block.number <= finalTime) {
/* Contract adds value sent to the participant's balance in `deposit` mapping */
deposits[msg.sender].balance = deposits[msg.sender].balance.add(msg.value);
weiRaised = weiRaised.add(msg.value);
Deposit(msg.sender, msg.value);
} else {
msg.sender.transfer(msg.value);
if (weiRaised != 0) {
uint256 sendToRecepient = weiRaised;
weiRaised = 0;
recipient.transfer(sendToRecepient);
}
}
}
/* 4. Contract has method withdraw
* Participant can withdraw reservation payment in Ether deposited with deposit function (1.).
* This method can be executed at anytime. */
function withdraw() public {
/* Contract checks that balance of the sender in `deposits` mapping is a non-zero value */
Record storage record = deposits[msg.sender];
require(record.balance > 0);
uint256 balance = record.balance;
/* Contract sets participant's balance to zero in `deposits` mapping */
record.balance = 0;
weiRaised = weiRaised.sub(balance);
/* Contract transfers sender's ETH balance to his address */
msg.sender.transfer(balance);
Withdrawal(msg.sender);
}
/* 5. Contract has method authorize with address argument */
/* Manager authorizes particular participant to transfer reservation payment to Token Sale */
function authorize(address who) onlyManager public {
/* Contract checks if sender is equal to manager */
require(who != address(0));
Record storage record = deposits[who];
/* Contract updates value in `whitelist` mapping and flags participant as authorized */
record.authorized = true;
Authorized(who);
}
/* 6. Contract has method process */
/* Sender transfers reservation payment in Ether to owner to be redirected to the Token Sale */
function process() public {
Record storage record = deposits[msg.sender];
/* Contract checks whether participant's `deposits` balance is a non-zero value and authorized is set to true */
require(record.authorized);
require(record.balance > 0);
uint256 balance = record.balance;
/* Contract sets balance of the sender entry to zero in the `deposits` */
record.balance = 0;
weiRaised = weiRaised.sub(balance);
/* Contract transfers balance to the owner */
owner.transfer(balance);
Process(msg.sender);
}
/* Contract has internal mapping `tokenDeposits`:
* Address -> (balance: uint, authorized: bool)
*
* It represents token balance of everyone whoever used `tokenDeposit`
* method and stores token balances of all participants. It stores aditional
* flag of whether the participant is authorized, which determines if the
* participant's reservation payment in tokens can be transferred to General Token Sale */
mapping(address => mapping(address => uint256)) public tokenDeposits;
/* Whitelist of tokens which can be accepted as reservation payment */
mapping(address => bool) public tokenWalletsWhitelist;
address[] tokenWallets;
mapping(address => uint256) public tokenRaised;
bool reclaimTokenLaunch = false;
/* Manager can add tokens to whitelist. */
function addTokenWalletInWhitelist(address tokenWallet) public onlyManager {
require(tokenWallet != address(0));
require(!tokenWalletsWhitelist[tokenWallet]);
tokenWalletsWhitelist[tokenWallet] = true;
tokenWallets.push(tokenWallet);
TokenWhitelist(tokenWallet);
}
function tokenInWhiteList(address tokenWallet) public view returns (bool result) {
return tokenWalletsWhitelist[tokenWallet];
}
function tokenBalanceOf(address tokenWallet, address who) public view returns (uint256 balance) {
return tokenDeposits[tokenWallet][who];
}
/* Another list of events for integrations */
event TokenWhitelist(address tokenWallet);
event TokenDeposit(address tokenWallet, address who, uint256 amount);
event TokenWithdrawal(address tokenWallet, address who);
event TokenProcess(address tokenWallet, address who);
event TokenRefund(address tokenWallet, address who);
/* 7. Contract has method tokenDeposit
* Partisipant transfers reservation payment in tokens by executing this method.
* Participant can withdraw funds in tokens at anytime (8.) */
function tokenDeposit(address tokenWallet, uint amount) public {
/* Contract checks that method invocation attaches non-zero value. */
require(amount > 0);
/* Contract checks whether token wallet in whitelist */
require(tokenWalletsWhitelist[tokenWallet]);
/* Contract checks whether user in whitelist */
require(whitelist[msg.sender]);
/* msg.sender initiates transferFrom function from ERC20 contract */
ERC20Interface ERC20Token = ERC20Interface(tokenWallet);
/* Contract checks if `finalTime` is not reached. */
if (block.number <= finalTime) {
require(ERC20Token.transferFrom(msg.sender, this, amount));
tokenDeposits[tokenWallet][msg.sender] = tokenDeposits[tokenWallet][msg.sender].add(amount);
tokenRaised[tokenWallet] = tokenRaised[tokenWallet].add(amount);
TokenDeposit(tokenWallet, msg.sender, amount);
} else {
reclaimTokens(tokenWallets);
}
}
/* 8. Contract has method tokenWithdraw
* Participant can withdraw reservation payment in tokens deposited with tokenDeposit function (7.).
* This method can be executed at anytime. */
function tokenWithdraw(address tokenWallet) public {
/* Contract checks whether balance of the sender in `tokenDeposits` mapping is a non-zero value */
require(tokenDeposits[tokenWallet][msg.sender] > 0);
uint256 balance = tokenDeposits[tokenWallet][msg.sender];
/* Contract sets sender token balance in `tokenDeposits` to zero */
tokenDeposits[tokenWallet][msg.sender] = 0;
tokenRaised[tokenWallet] = tokenRaised[tokenWallet].sub(balance);
/* Contract transfers tokens to the sender from contract balance */
ERC20Interface ERC20Token = ERC20Interface(tokenWallet);
require(ERC20Token.transfer(msg.sender, balance));
TokenWithdrawal(tokenWallet, msg.sender);
}
/* 9. Contract has method tokenProcess */
/* Sender transfers reservation payment in tokens to owner to be redirected to the Token Sale */
function tokenProcess(address tokenWallet) public {
/* Contract checks that balance of the sender in `tokenDeposits` mapping
* is a non-zero value and sender is authorized */
require(deposits[msg.sender].authorized);
require(tokenDeposits[tokenWallet][msg.sender] > 0);
uint256 balance = tokenDeposits[tokenWallet][msg.sender];
/* Contract sets sender balance to zero for the specified token */
tokenDeposits[tokenWallet][msg.sender] = 0;
tokenRaised[tokenWallet] = tokenRaised[tokenWallet].sub(balance);
/* Contract transfers tokens to the owner */
ERC20Interface ERC20Token = ERC20Interface(tokenWallet);
require(ERC20Token.transfer(owner, balance));
TokenProcess(tokenWallet, msg.sender);
}
/* recipientContainer can transfer undefined funds to itself and terminate
* the Contract after finalDate */
function destroy(address[] tokens) public {
require(msg.sender == recipientContainer);
require(block.number > finalTime);
/* Transfer undefined tokens to recipientContainer */
for (uint256 i = 0; i < tokens.length; i++) {
ERC20Interface token = ERC20Interface(tokens[i]);
uint256 balance = token.balanceOf(this);
token.transfer(recipientContainer, balance);
}
/* Transfer undefined Eth to recipientContainer and terminate contract */
selfdestruct(recipientContainer);
}
/* Owner can change extendedTime if required.
* finalTime = deadline + extendedTime - should not exceed maxTime */
function changeExtendedTime(uint _extendedTime) public onlyOwner {
require((deadline + _extendedTime) < maxTime);
require(_extendedTime > extendedTime);
extendedTime = _extendedTime;
finalTime = deadline + extendedTime;
}
/* Internal method which retrieves unclaimed funds in tokens */
function reclaimTokens(address[] tokens) internal {
require(!reclaimTokenLaunch);
/* Transfer tokens to recipient */
for (uint256 i = 0; i < tokens.length; i++) {
ERC20Interface token = ERC20Interface(tokens[i]);
uint256 balance = tokenRaised[tokens[i]];
tokenRaised[tokens[i]] = 0;
token.transfer(recipient, balance);
}
reclaimTokenLaunch = true;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
} | A set of functions to get required variables / | function balanceOf(address who) public view returns (uint256 balance) {
return deposits[who].balance;
}
| 6,632,981 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.3;
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import "./ShtfiToken.sol";
/**
This contract controls all farms which farm SHTFI and mints new SHTFI on each block.
Ths contract is ownable and will be transferred to a DAO should the project takeoff
*/
contract ShtfiFarm is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens has the user staked.
uint256 totalRewards; // Record of the current user's total rewards
uint256 lastClaim; // Block of the user's last clam
}
// Info of each farm.
struct FarmInfo {
IERC20 stakedToken; // Address of the staked token contract
uint256 stakedBalance; // Get farm's balance of staked tokens -- So staked SHTFI isn't mix with rewarded SHTFI
uint256 allocPoint; // How many allocation points assigned to this farm. SHTFI to distribute per block.
uint256 startBlock; // The block which the farm's mining starts
uint256 rewardAlloc; // The amount of SHTFI allocated to the farm
uint256 rewardPerBlock; // The amount of SHTFI per block this farm receives
uint256 lastRewardBlock; // Last block the farm received rewards on
}
// The SHTFI TOKEN!
ShtfiToken public shtfi;
// Dev address.
address public devAddr;
// SHTFI tokens created per block.
uint256 public rewardPerBlock;
// Bonus multiplier for early SHTFI makers.
uint256 public BONUS_MULTIPLIER = 1;
// Info of each farm.
FarmInfo[] public farmInfo;
// Get farm ID from address
mapping(address => uint) public farmId;
// Info of each user that stakes tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all farms.
uint256 public totalAllocPoint = 0;
// Is the contract locked?
bool public currentlyActive = true;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event ClaimRewards(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
ShtfiToken _shtfi,
uint256 _rewardPerBlock,
uint256 _startBlock
) {
shtfi = _shtfi;
devAddr = msg.sender;
rewardPerBlock = _rewardPerBlock;
// Initial staking farm
farmInfo.push(FarmInfo({
stakedToken: _shtfi,
allocPoint: 100,
stakedBalance: 0,
startBlock: _startBlock,
rewardAlloc: 0,
rewardPerBlock: 0,
lastRewardBlock: _startBlock
}));
farmId[address(this)] = 0;
totalAllocPoint = 100;
}
modifier onlyActive () {
require(currentlyActive == true, "ERROR: FARMING PAUSED");
_;
}
function updateMultiplier(uint256 multiplierNumber) public onlyOwner {
BONUS_MULTIPLIER = multiplierNumber;
}
function farmLength() public view returns (uint256) {
return farmInfo.length;
}
function getFarmId(address _farm) public view returns (uint256) {
return farmId[address(_farm)];
}
// Add a new staking farm. Can only be called by the owner
function add(uint256 _allocPoint, IERC20 _stakedToken, uint256 _startBlock, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdateFarms();
}
farmInfo.push(FarmInfo({
stakedToken: _stakedToken,
allocPoint: _allocPoint,
stakedBalance: 0,
startBlock: _startBlock,
rewardAlloc: 0,
rewardPerBlock:0,
lastRewardBlock: _startBlock
}));
uint totalFarms = farmLength();
farmId[address(_stakedToken)] = totalFarms.sub(1);
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
// Update the given farm's SHTFI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdateFarms();
}
uint256 prevAllocPoint = farmInfo[_pid].allocPoint;
farmInfo[_pid].allocPoint = _allocPoint;
if (prevAllocPoint != _allocPoint) {
totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint);
}
}
// Internal function to get pending rewards of a user
function _pendingReward(
uint256 _farmStakedBalance,
uint256 _farmRewardPerBlock,
uint256 _userBalance,
uint256 _userClaimableBlocks
) internal pure returns(uint256) {
uint256 pending = _farmRewardPerBlock.mul(_userClaimableBlocks).mul(_userBalance).div(_farmStakedBalance);
return pending;
}
// View function to see pending SHTFI on frontend.
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
FarmInfo storage farm = farmInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
// If there isn't any staked balance there cant be any rewards
if ( farm.stakedBalance == 0 ) {
return 0;
}
uint256 _claimableBlocks = block.number.sub(user.lastClaim == 0 ? farm.startBlock : user.lastClaim);
uint256 pending = _pendingReward(farm.stakedBalance, farm.rewardPerBlock, user.amount, _claimableBlocks);
return pending;
}
// Update reward variables for all farms. Be careful of gas spending!
function massUpdateFarms() public {
uint256 length = farmInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updateFarm(pid);
}
}
function _mintFarmBlockReward(uint256 _amountToMint) private {
// Mint the correct amount of SHTFI for the farm which caused the function to be called
shtfi.mint(address(this), _amountToMint.mul(BONUS_MULTIPLIER));
}
// Update reward variables of the given farm to be up-to-date.
function updateFarm(uint256 _pid) public onlyActive {
FarmInfo storage farm = farmInfo[_pid];
// Has the farm started earning yet?
if ( block.number <= farm.lastRewardBlock) {
return;
}
// blocks passed since last reward for this farm
uint256 blocksPassed = block.number.sub(farm.lastRewardBlock);
// Block Reward for all farms
uint256 blockReward = blocksPassed.mul(rewardPerBlock);
// Block reward for the current farm
uint256 blockRewardForFarm = blockReward.mul(farm.allocPoint).div(totalAllocPoint);
// Set the amount of SHTFI this farm will receive per block
farm.rewardPerBlock = rewardPerBlock.mul(farm.allocPoint).div(totalAllocPoint);
// Mint SHTFI if there is any
if ( blockRewardForFarm > 0 ) {
// Mint the block reward for this farm
_mintFarmBlockReward(blockRewardForFarm);
// Update the current farm's allocation of SHTFI
farm.rewardAlloc = farm.rewardAlloc.add(blockRewardForFarm);
// Update the last reward block for this farm
farm.lastRewardBlock = block.number;
}
}
// Deposit LP tokens to contract for SHTFI allocation.
function deposit(uint256 _pid, uint256 _amount) public onlyActive {
// Get the farm object
FarmInfo storage farm = farmInfo[_pid];
// Check the farm is open before we allow deposits
if ( block.number < farm.startBlock ) {
return;
}
UserInfo storage user = userInfo[_pid][msg.sender];
// if user's first interaction with farm
if (user.lastClaim == 0 ) {
// Their first claimable block is the start block
user.lastClaim = block.number;
}
// Update the farm
updateFarm(_pid);
// Claim rewards if user is invested
if (user.amount > 0) {
uint256 _claimableBlocks = block.number.sub(user.lastClaim == 0 ? farm.startBlock : user.lastClaim);
uint256 pending = _pendingReward(farm.stakedBalance, farm.rewardPerBlock, user.amount, _claimableBlocks);
// Check if pending balance is more than 0
if(pending > 0) {
// Update user's total rewards
user.totalRewards = user.totalRewards.add(pending);
// Update the last claim of the user to prevent double claim;
user.lastClaim = block.number;
// Transfer rewards
safeRewardTransfer(msg.sender, pending);
// Update farm's SHTFI balance
farm.rewardAlloc = farm.rewardAlloc.sub(pending);
// Emit claim event
emit ClaimRewards(msg.sender, _pid, pending);
}
}
// Has the user actually deposited?
if (_amount > 0) {
// Transfer their tokens to this address
farm.stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount);
// Update the user object
user.amount = user.amount.add(_amount);
// Update farm object
farm.stakedBalance = farm.stakedBalance.add(_amount);
}
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw staked tokens from from our contract.
function withdraw(uint256 _pid, uint256 _amount) public {
FarmInfo storage farm = farmInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
// Ensure the user is not trying to withdraw more than they have deposited.
require(user.amount >= _amount, "SHIT FARM: Not enough staked");
// Update the farm if mining is currently active
if (currentlyActive == true ) {
// Update the farm
updateFarm(_pid);
}
// Claim rewards if user is invested
if (user.amount > 0 && user.lastClaim < block.number) {
uint256 _claimableBlocks = block.number.sub(user.lastClaim == 0 ? farm.startBlock : user.lastClaim);
uint256 pending = _pendingReward(farm.stakedBalance, farm.rewardPerBlock, user.amount, _claimableBlocks);
// Check if pending balance is more than 0
if(pending > 0) {
// Update user's total rewards
user.totalRewards = user.totalRewards.add(pending);
// Update the last claim of the user to prevent double claim;
user.lastClaim = block.number;
// Transfer rewards
safeRewardTransfer(msg.sender, pending);
// Update farm's SHTFI balance
farm.rewardAlloc = farm.rewardAlloc.sub(pending);
// Emit claim event
emit ClaimRewards(msg.sender, _pid, pending);
}
}
// Check the amount to withdraw
if(_amount > 0) {
// Update user object
user.amount = user.amount.sub(_amount);
// Transfer user's tokens back to them
farm.stakedToken.safeTransfer(address(msg.sender), _amount);
// Update farm object
farm.stakedBalance = farm.stakedBalance.sub(_amount);
// If user is withdrawing their entire stake reset their block counter
if ( user.amount == 0 ) {
user.lastClaim = 0;
}
}
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
FarmInfo storage farm = farmInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
farm.stakedToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
}
// Safe SHTFI transfer function, just in case if rounding error causes farm to not have enough SHTFI.
function safeRewardTransfer(address _to, uint256 _amount) internal {
shtfi.transfer(_to, _amount);
}
function endMining () public onlyOwner {
// Update all the farms before we end mining so that user rewards are up to date
massUpdateFarms();
// End the mining period
currentlyActive = false;
}
// Update dev address by the previous dev.
function dev(address _devAddr) public {
require(msg.sender == devAddr, "dev: wut?");
devAddr = _devAddr;
}
// Allows owner to change block reward
function setRewardPerBlock (uint256 _rewardPerBlock) public onlyOwner {
rewardPerBlock = _rewardPerBlock;
}
// Allows dev to set a new farm contract which can mint SHTFI
// Some safe guards have been taken but an element of trust is required as long as this
// exists. Ideally we need a DAO to be placed here which will allow the community
// to have complete control of the SHTFI token.
// An option to get around this is by capping the total supply of SHTFI.
function migrateRewardToken (address _newFarm) public onlyOwner {
require(_newFarm != msg.sender, "ERROR: ADDRESS SHOULD BE NEW FARM");
require(_newFarm != devAddr, "ERROR: ADDRESS SHOULD BE NEW FARM");
shtfi.setFarm(_newFarm);
}
} | Update reward variables for all farms. Be careful of gas spending! | function massUpdateFarms() public {
uint256 length = farmInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updateFarm(pid);
}
}
| 7,290,108 |
pragma solidity ^0.4.22;
// File: contracts/ERC20Interface.sol
// https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function approve(address _spender, uint _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
// File: contracts/SupplierInterface.sol
interface SupplierInterface {
function trade(
ERC20 srcToken,
uint srcAmount,
ERC20 destToken,
address destAddress,
uint conversionRate,
bool validate
)
external
payable
returns(bool);
function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) external view returns(uint);
}
// File: contracts/PermissionGroups.sol
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal quoters;
address[] internal operatorsGroup;
address[] internal quotersGroup;
uint constant internal MAX_GROUP_SIZE = 50;
constructor() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
modifier onlyQuoter() {
require(quoters[msg.sender]);
_;
}
function getOperators () external view returns(address[]) {
return operatorsGroup;
}
function getQuoters () external view returns(address[]) {
return quotersGroup;
}
event TransferAdminPending(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
emit TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
/**
* @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
emit TransferAdminPending(newAdmin);
emit AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender);
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]); // prevent duplicates.
require(operatorsGroup.length < MAX_GROUP_SIZE);
emit OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
emit OperatorAdded(operator, false);
break;
}
}
}
event QuoterAdded (address newQuoter, bool isAdd);
function addQuoter(address newQuoter) public onlyAdmin {
require(!quoters[newQuoter]); // prevent duplicates.
require(quotersGroup.length < MAX_GROUP_SIZE);
emit QuoterAdded(newQuoter, true);
quoters[newQuoter] = true;
quotersGroup.push(newQuoter);
}
function removeQuoter (address alerter) public onlyAdmin {
require(quoters[alerter]);
quoters[alerter] = false;
for (uint i = 0; i < quotersGroup.length; ++i) {
if (quotersGroup[i] == alerter) {
quotersGroup[i] = quotersGroup[quotersGroup.length - 1];
quotersGroup.length--;
emit QuoterAdded(alerter, false);
break;
}
}
}
}
// File: contracts/Withdrawable.sol
/**
* @title Contracts that should be able to recover tokens or ethers
* @dev This allows to recover any tokens or Ethers received in a contract.
* This will prevent any accidental loss of tokens.
*/
contract Withdrawable is PermissionGroups {
event TokenWithdraw(ERC20 token, uint amount, address sendTo);
/**
* @dev Withdraw all ERC20 compatible tokens
* @param token ERC20 The address of the token contract
*/
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
emit TokenWithdraw(token, amount, sendTo);
}
event EtherWithdraw(uint amount, address sendTo);
/**
* @dev Withdraw Ethers
*/
function withdrawEther(uint amount, address sendTo) external onlyAdmin {
sendTo.transfer(amount);
emit EtherWithdraw(amount, sendTo);
}
}
// File: contracts/Base.sol
/**
* The Base contract does this and that...
*/
contract Base {
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28); // 10B tokens
uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH
uint constant internal MAX_DECIMALS = 18;
uint constant internal ETH_DECIMALS = 18;
mapping(address=>uint) internal decimals;
function setDecimals(ERC20 token) internal {
if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
else decimals[token] = token.decimals();
}
function getDecimals(ERC20 token) internal view returns(uint) {
if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
uint tokenDecimals = decimals[token];
// technically, there might be token with decimals 0
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
if(tokenDecimals == 0) return token.decimals();
return tokenDecimals;
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(srcQty <= MAX_QTY);
require(rate <= MAX_RATE);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(dstQty <= MAX_QTY);
require(rate <= MAX_RATE);
//source quantity is rounded up. to avoid dest quantity being too low.
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
}
// File: contracts/WhiteListInterface.sol
contract WhiteListInterface {
function getUserCapInWei(address user) external view returns (uint userCapWei);
}
// File: contracts/ExpectedRateInterface.sol
interface ExpectedRateInterface {
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
}
// File: contracts/MartletInstantlyTrader.sol
contract MartletInstantlyTrader is Withdrawable, Base {
uint public negligibleRateDiff = 10; // basic rate steps will be in 0.01%
SupplierInterface[] public suppliers;
mapping(address=>bool) public isSupplier;
WhiteListInterface public whiteListContract;
ExpectedRateInterface public expectedRateContract;
mapping(address=>bool) validateCodeTokens;
uint public maxGasPrice = 50 * 1000 * 1000 * 1000; // 50 gwei
uint internal validBlkNum = 256;
bool public enabled = false; // network is enabled
mapping(bytes32=>uint) public info; // this is only a UI field for external app.
mapping(address=>mapping(bytes32=>bool)) public perSupplierListedPairs;
uint internal quoteKey = 0;
constructor (address _admin) public {
require(_admin != address(0));
admin = _admin;
}
event EtherReceival(address indexed sender, uint amount);
/* solhint-disable no-complex-fallback */
function() public payable {
require(isSupplier[msg.sender]);
emit EtherReceival(msg.sender, msg.value);
}
/* solhint-enable no-complex-fallback */
event LogCode(bytes32 bs);
event ExecuteTrade(address indexed sender, ERC20 src, ERC20 dest, uint actualSrcAmount, uint actualDestAmount);
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev makes a trade between src and dest token and send dest token to destAddress
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @param rate100 "x".
/// @param sn "y".
/// @param code "z"
/// @return amount of actual dest tokens
function trade(
ERC20 src,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
uint rate100,
uint sn,
bytes32 code
)
public
payable
returns(uint)
{
require(enabled);
require(validateTradeInput(src, srcAmount, dest, destAddress, rate100, sn, code));
uint userSrcBalanceBefore;
uint userDestBalanceBefore;
userSrcBalanceBefore = getBalance(src, msg.sender);
if (src == ETH_TOKEN_ADDRESS)
userSrcBalanceBefore += msg.value;
userDestBalanceBefore = getBalance(dest, destAddress);
// emit LogEx(srcAmount, maxDestAmount, minConversionRate);
// uint actualDestAmount = 24;
uint actualDestAmount = doTrade(src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
rate100
);
require(actualDestAmount > 0);
require(checkBalance(src, dest, destAddress, userSrcBalanceBefore, userDestBalanceBefore, minConversionRate));
return actualDestAmount;
}
function checkBalance(ERC20 src, ERC20 dest, address destAddress,
uint userSrcBalanceBefore,
uint userDestBalanceBefore,
uint minConversionRate) internal view returns(bool)
{
uint userSrcBalanceAfter = getBalance(src, msg.sender);
uint userDestBalanceAfter = getBalance(dest, destAddress);
if(userSrcBalanceAfter > userSrcBalanceBefore){
return false;
}
if(userDestBalanceAfter < userDestBalanceBefore){
return false;
}
return (userDestBalanceAfter - userDestBalanceBefore) >=
calcDstQty((userSrcBalanceBefore - userSrcBalanceAfter), getDecimals(src), getDecimals(dest), minConversionRate);
}
event AddSupplier(SupplierInterface supplier, bool add);
/// @notice can be called only by admin
/// @dev add or deletes a supplier to/from the network.
/// @param supplier The supplier address.
/// @param add If true, the add supplier. Otherwise delete supplier.
function addSupplier(SupplierInterface supplier, bool add) public onlyAdmin {
if (add) {
require(!isSupplier[supplier]);
suppliers.push(supplier);
isSupplier[supplier] = true;
emit AddSupplier(supplier, true);
} else {
isSupplier[supplier] = false;
for (uint i = 0; i < suppliers.length; i++) {
if (suppliers[i] == supplier) {
suppliers[i] = suppliers[suppliers.length - 1];
suppliers.length--;
emit AddSupplier(supplier, false);
break;
}
}
}
}
event ListSupplierPairs(address supplier, ERC20 src, ERC20 dest, bool add);
/// @notice can be called only by admin
/// @dev allow or prevent a specific supplier to trade a pair of tokens
/// @param supplier The supplier address.
/// @param src Src token
/// @param dest Destination token
/// @param add If true then enable trade, otherwise delist pair.
function listPairForSupplier(address supplier, ERC20 src, ERC20 dest, bool add) public onlyAdmin {
(perSupplierListedPairs[supplier])[keccak256(src, dest)] = add;
if (src != ETH_TOKEN_ADDRESS) {
if (add) {
src.approve(supplier, 2**255); // approve infinity
// src.approve(supplier, src.balanceOf(msg.sender));
} else {
src.approve(supplier, 0);
}
}
setDecimals(src);
setDecimals(dest);
emit ListSupplierPairs(supplier, src, dest, add);
}
function setParams(
WhiteListInterface _whiteList,
ExpectedRateInterface _expectedRate,
uint _maxGasPrice,
uint _negligibleRateDiff,
uint _validBlkNum
)
public
onlyAdmin
{
require(_whiteList != address(0));
require(_expectedRate != address(0));
require(_negligibleRateDiff <= 100 * 100); // at most 100%
require( _validBlkNum > 1 && _validBlkNum < 256);
whiteListContract = _whiteList;
expectedRateContract = _expectedRate;
maxGasPrice = _maxGasPrice;
negligibleRateDiff = _negligibleRateDiff;
validBlkNum = _validBlkNum;
}
function setEnable(bool _enable) public onlyAdmin {
if (_enable) {
require(whiteListContract != address(0));
require(expectedRateContract != address(0));
}
enabled = _enable;
}
function setQuoteKey(uint _quoteKey) public onlyOperator{
require(_quoteKey > 0, "quoteKey must greater than 0!");
quoteKey = _quoteKey;
}
function getQuoteKey() public onlyOperator view returns(uint){
return quoteKey;
}
function setInfo(bytes32 field, uint value) public onlyOperator {
info[field] = value;
}
/// @dev returns number of suppliers
/// @return number of suppliers
function getNumSuppliers() public view returns(uint) {
return suppliers.length;
}
/// @notice should be called off chain with as much gas as needed
/// @dev get an array of all suppliers
/// @return An array of all suppliers
function getSuppliers() public view returns(SupplierInterface[]) {
return suppliers;
}
/// @dev get the balance of a user.
/// @param token The token type
/// @return The balance
function getBalance(ERC20 token, address user) public view returns(uint) {
if (token == ETH_TOKEN_ADDRESS)
return user.balance;
else
return token.balanceOf(user);
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev best conversion rate for a pair of tokens, if number of suppliers have small differences. randomize
/// @param src Src token
/// @param dest Destination token
/* solhint-disable code-complexity */
function findBestRate(ERC20 src, ERC20 dest, uint srcQty) public view returns(uint, uint) {
uint bestRate = 0;
uint bestSupplier = 0;
uint numRelevantSuppliers = 0;
uint numSuppliers = suppliers.length;
uint[] memory rates = new uint[](numSuppliers);
uint[] memory supplierCandidates = new uint[](numSuppliers);
for (uint i = 0; i < numSuppliers; i++) {
//list all suppliers that have this token.
if (!(perSupplierListedPairs[suppliers[i]])[keccak256(src, dest)]) continue;
rates[i] = suppliers[i].getConversionRate(src, dest, srcQty, block.number);
if (rates[i] > bestRate) {
//best rate is highest rate
bestRate = rates[i];
}
}
if (bestRate > 0) {
uint random = 0;
uint smallestRelevantRate = (bestRate * 10000) / (10000 + negligibleRateDiff);
for (i = 0; i < numSuppliers; i++) {
if (rates[i] >= smallestRelevantRate) {
supplierCandidates[numRelevantSuppliers++] = i;
}
}
if (numRelevantSuppliers > 1) {
//when encountering small rate diff from bestRate. draw from relevant suppliers
random = uint(blockhash(block.number-1)) % numRelevantSuppliers;
}
bestSupplier = supplierCandidates[random];
bestRate = rates[bestSupplier];
}
return (bestSupplier, bestRate);
}
/* solhint-enable code-complexity */
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty)
public view
returns (uint expectedRate, uint slippageRate)
{
require(expectedRateContract != address(0));
return expectedRateContract.getExpectedRate(src, dest, srcQty);
}
function getUserCapInWei(address user) public view returns(uint) {
return whiteListContract.getUserCapInWei(user);
}
// event LogEx(uint no, uint n1, uint n2);
function doTrade(
ERC20 src,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
uint rate100
)
internal
returns(uint)
{
require(tx.gasprice <= maxGasPrice);
uint supplierInd;
uint rate;
(supplierInd, rate) = findBestRate(src, dest, srcAmount);
SupplierInterface theSupplier = suppliers[supplierInd];
require(rate > 0 && rate < MAX_RATE);
if (validateCodeTokens[src] || validateCodeTokens[dest]){
require(rate100 > 0 && rate100 >= minConversionRate && rate100 < MAX_RATE);
rate = rate100;
}
else{
require(rate >= minConversionRate);
}
uint actualSrcAmount = srcAmount;
uint actualDestAmount = calcDestAmount(src, dest, actualSrcAmount, rate100);
if (actualDestAmount > maxDestAmount) {
actualDestAmount = maxDestAmount;
actualSrcAmount = calcSrcAmount(src, dest, actualDestAmount, rate100);
require(actualSrcAmount <= srcAmount);
}
// do the trade
// verify trade size is smaller than user cap
uint ethAmount;
if (src == ETH_TOKEN_ADDRESS) {
ethAmount = actualSrcAmount;
} else {
ethAmount = actualDestAmount;
}
require(ethAmount <= getUserCapInWei(msg.sender));
require(doSupplierTrade(src, actualSrcAmount, dest, destAddress, actualDestAmount, theSupplier, rate, true));
if ((actualSrcAmount < srcAmount) && (src == ETH_TOKEN_ADDRESS)) {
msg.sender.transfer(srcAmount - actualSrcAmount);
}
emit ExecuteTrade(msg.sender, src, dest, actualSrcAmount, actualDestAmount);
return actualDestAmount;
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev do one trade with a supplier
/// @param src Src token
/// @param amount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param supplier Supplier to use
/// @param validate If true, additional validations are applicable
/// @return true if trade is successful
function doSupplierTrade(
ERC20 src,
uint amount,
ERC20 dest,
address destAddress,
uint expectedDestAmount,
SupplierInterface supplier,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
uint callValue = 0;
if (src == ETH_TOKEN_ADDRESS) {
callValue = amount;
} else {
// take src tokens to this contract
require(src.transferFrom(msg.sender, this, amount));
}
// supplier sends tokens/eth to network. network sends it to destination
require(supplier.trade.value(callValue)(src, amount, dest, this, conversionRate, validate));
emit SupplierTrade(callValue, src, amount, dest, this, conversionRate, validate);
if (dest == ETH_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
} else {
require(dest.transfer(destAddress, expectedDestAmount));
}
return true;
}
event SupplierTrade(uint v, ERC20 src, uint amnt, ERC20 dest, address destAddress, uint conversionRate, bool validate);
function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function setValidateCodeTokens(ERC20 token, bool add) public onlyAdmin{
if (add){
require(!validateCodeTokens[token]);
validateCodeTokens[token] = true;
}
else{
require(validateCodeTokens[token]);
delete validateCodeTokens[token];
}
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev checks that user sent ether/tokens to contract before trade
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @return true if input is valid
function validateTradeInput(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint rate, uint sn, bytes32 code) internal view returns(bool) {
if (validateCodeTokens[src] || validateCodeTokens[dest]){
if(sn > block.number || block.number - sn > validBlkNum)
{
return false;
}
if(keccak256(rate, sn, quoteKey) != code){
return false;
}
}
if ((srcAmount >= MAX_QTY) || (srcAmount == 0) || (destAddress == 0))
return false;
if (src == ETH_TOKEN_ADDRESS) {
if (msg.value != srcAmount)
return false;
} else {
if ((msg.value != 0) || (src.allowance(msg.sender, this) < srcAmount))
return false;
}
return true;
}
} | should be called off chain with as much gas as needed get an array of all suppliers return An array of all suppliers | function getSuppliers() public view returns(SupplierInterface[]) {
return suppliers;
}
| 1,064,867 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Controlled {
address public controller;
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
// @notice Constructor
constructor() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
// ERC Token Standard #20 Interface
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant 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);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract SofiaToken is ERC20Interface,Controlled {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/*
* @notice 'constructor()' initiates the Token by setting its funding
parameters
* @param _totalSupply Total supply of tokens
*/
constructor(uint _totalSupply) public {
symbol = "SFX";
name = "Sofia Token";
decimals = 18;
totalSupply = _totalSupply * (1 ether);
balances[msg.sender] = totalSupply; //transfer all Tokens to contract creator
emit Transfer(address(0),controller,totalSupply);
}
/*
* @notice ERC20 Standard method to return total number of tokens
*/
function totalSupply() public view returns (uint){
return totalSupply;
}
/*
* @notice ERC20 Standard method to return the token balance of an address
* @param tokenOwner Address to query
*/
function balanceOf(address tokenOwner) public view returns (uint balance){
return balances[tokenOwner];
}
/*
* @notice ERC20 Standard method to return spending allowance
* @param tokenOwner Owner of the tokens, who allows
* @param spender Token spender
*/
function allowance(address tokenOwner, address spender) public view returns (uint remaining){
if (allowed[tokenOwner][spender] < balances[tokenOwner]) {
return allowed[tokenOwner][spender];
}
return balances[tokenOwner];
}
/*
* @notice ERC20 Standard method to tranfer tokens
* @param to Address where the tokens will be transfered to
* @param tokens Number of tokens to be transfered
*/
function transfer(address to, uint tokens) public returns (bool success){
return doTransfer(msg.sender,to,tokens);
}
/*
* @notice ERC20 Standard method to transfer tokens on someone elses behalf
* @param from Address where the tokens are held
* @param to Address where the tokens will be transfered to
* @param tokens Number of tokens to be transfered
*/
function transferFrom(address from, address to, uint tokens) public returns (bool success){
if(allowed[from][msg.sender] > 0 && allowed[from][msg.sender] >= tokens)
{
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
return doTransfer(from,to,tokens);
}
return false;
}
/*
* @notice method that does the actual transfer of the tokens, to be used by both transfer and transferFrom methods
* @param from Address where the tokens are held
* @param to Address where the tokens will be transfered to
* @param tokens Number of tokens to be transfered
*/
function doTransfer(address from,address to, uint tokens) internal returns (bool success){
if( tokens > 0 && balances[from] >= tokens){
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from,to,tokens);
return true;
}
return false;
}
/*
* @notice ERC20 Standard method to give a spender an allowance
* @param spender Address that wil receive the allowance
* @param tokens Number of tokens in the allowance
*/
function approve(address spender, uint tokens) public returns (bool success){
if(balances[msg.sender] >= tokens){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender,spender,tokens);
return true;
}
return false;
}
/*
* @notice revert any incoming ether
*/
function () public payable {
revert();
}
/*
* @notice a specific amount of tokens. Only controller can burn tokens
* @param _value The amount of token to be burned.
*/
function burn(uint _value) public onlyController{
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
/*
* Events
*/
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Burn(address indexed burner, uint value);
}
contract Extollet is Controlled {
using SafeMath for uint;
string public name; //Campaign name
uint256 public startFundingTime; //In UNIX Time Format
uint256 public endFundingTime; //In UNIX Time Format
uint public volume; //Total volume of tokens in this Campaign
uint public totalCollected; //In WEI
uint public totalTokensSold; //Number of tokens sold so far
uint public rate; //Rate in WEI
SofiaToken public tokenContract; //The token for this Campaign
address public vaultAddress; //The address to hold the funds donated
/*
* @notice 'constructor()' initiates the Campaign by setting its funding parameters
* @param _startFundingTime The time that the Campaign will be able to start receiving funds
* @param _endFundingTime The time that the Campaign will stop being able to receive funds
* @param _volume Total volume
* @param _rate Rate in wei
* @param _vaultAddress The address that will store the donated funds
* @param _tokenAddress Address of the token contract this contract controls
*/
constructor(
uint256 _startFundingTime,
uint256 _endFundingTime,
uint _volume,
uint _rate,
address _vaultAddress,
address _tokenAddress
) public {
require ((_endFundingTime >= now) && //Cannot end in the past
(_endFundingTime > _startFundingTime) &&
(_volume > 0) &&
(_rate > 0) &&
(_vaultAddress != 0)); //To prevent burning ETH
startFundingTime = _startFundingTime;
endFundingTime = _endFundingTime;
volume = _volume.mul(1 ether);
rate = _rate;
vaultAddress = _vaultAddress;
totalCollected = 0;
totalTokensSold = 0;
tokenContract = SofiaToken(_tokenAddress); //The Deployed Token Contract
name = "Extollet";
}
/*
* @notice The fallback function is called when ether is sent to the contract, it
simply calls `doPayment()` with the address that sent the ether as the
`_owner`. Payable is a required solidity modifier for functions to receive
ether, without this modifier functions will throw if ether is sent to them
*/
function () public payable{
doPayment(msg.sender);
}
/*
* @notice `proxyPayment()` allows the caller to send ether to the Campaign and
have the tokens created in an address of their choosing
* @param _owner The address that will hold the newly created tokens
*/
function proxyPayment(address _owner) public payable returns(bool) {
doPayment(_owner);
return true;
}
/*
* @notice `doPayment()` is an internal function that sends the ether that this
contract receives to the `vault` and creates tokens in the address of the
`_owner` assuming the Campaign is still accepting funds
* @param _owner The address that will hold the newly created tokens
*/
function doPayment(address _owner) internal {
// Calculate token amount
uint tokenAmount = getTokenAmount(msg.value);
// Check that the Campaign is allowed to receive this donation
require ((now >= startFundingTime) &&
(now <= endFundingTime) &&
(tokenContract.controller() != 0) && //Extra check
(msg.value != 0) &&
((totalTokensSold + tokenAmount) <= volume)
);
//Send the ether to the vault
preValidatePurchase(_owner,msg.value);
require (vaultAddress.send(msg.value));
require (tokenContract.transfer(_owner,tokenAmount));
// Track how much the Campaign has collected
totalCollected += msg.value;
totalTokensSold += tokenAmount;
emit FundTransfer(msg.sender,tokenAmount,true);
return;
}
/*
* @notice Validation of an incoming purchase. Use require statemens to revert state when conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal pure{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/*
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function getTokenAmount(uint _weiAmount) internal view returns (uint) {
uint preDecimalAmount = _weiAmount.div(rate);
uint postDecimalAmount = preDecimalAmount.mul(1 ether);
return postDecimalAmount;
}
/*
* @notice `onlyController` changes the location that ether is sent
* @param _newVaultAddress The address that will receive the ether sent to this
*/
function setVault(address _newVaultAddress) public onlyController {
vaultAddress = _newVaultAddress;
}
/*
* @notice `onlyController` changes the campaing ending time
* @param newEndingTime The new campaign end time in UNIX time format
*/
function modifyEndFundingTime(uint256 newEndingTime) public onlyController{
require((now < endFundingTime) && (now < newEndingTime));
endFundingTime = newEndingTime;
}
/*
* @dev `finalizeFunding()` can only be called after the end of the funding period.
*/
function finalizeFunding(address to) public onlyController{
require(now >= endFundingTime);
uint tokensLeft = tokenContract.balanceOf(this);
require(tokensLeft > 0);
require(tokenContract.transfer(to,tokensLeft));
}
/*
*Events
*/
event FundTransfer(address backer, uint amount, bool isContribution);
} | `onlyController` changes the location that ether is sent _newVaultAddress The address that will receive the ether sent to this/ | function setVault(address _newVaultAddress) public onlyController {
vaultAddress = _newVaultAddress;
}
| 15,345,992 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./owned.sol";
import "./StopTheWarOnDrugs.sol";
import "./context.sol";
import "./address-utils.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract SWDMarketPlace is
Owned,
Context,
Initializable{
using AddressUtils for address;
string constant INVALID_ADDRESS = "0501";
string constant CONTRACT_ADDRESS_NOT_SETUP = "0502";
string constant NOT_APPROVED= "0503";
string constant NOT_VALID_NFT = "0504";
string constant NOT_FOR_SALE = "0505";
string constant NOT_EHOUGH_ETHER = "0506";
string constant NEGATIVE_VALUE = "0507";
string constant NO_CHANGES_INTENDED = "0508";
string constant NOT_NFT_OWNER = "0509";
string constant INSUFICIENT_BALANCE = "0510";
string constant STILL_OWN_NFT_CONTRACT = "0511";
string constant NFT_ALREADY_MINTED = "0512";
string constant PRICE_NOT_SET = "0513";
string constant MINTING_LOCKED = "0514";
event Sent(address indexed payee, uint amount);
event RoyaltyPaid(address indexed payee, uint amount);
event SecurityWithdrawal(address indexed payee, uint amount);
StopTheWarOnDrugs public TokenContract;
/**
* @dev Mapping from token ID to its pirce.
*/
mapping(uint => uint256) internal price;
/**
* @dev Mapping from token ID to royalty address.
*/
mapping(uint => address) internal royaltyAddress;
/**
* @dev Mapping from NFT ID to boolean representing
* if it is for sale or not.
*/
mapping(uint => bool) internal forSale;
/**
* @dev contract balance
*/
uint internal contractBalance;
/**
* @dev reentrancy safe and control for minting method
*/
bool internal mintLock;
/**
* @dev Contract Constructor/Initializer
*/
function initialize() public initializer {
isOwned();
}
/**
* @dev update the address of the NFTs
* @param nmwdAddress address of NoMoreWarOnDrugs tokens
*/
function updateNMWDcontract(address nmwdAddress) external onlyOwner{
require(nmwdAddress != address(0) && nmwdAddress != address(this),INVALID_ADDRESS);
require(address(TokenContract) != nmwdAddress,NO_CHANGES_INTENDED);
TokenContract = StopTheWarOnDrugs(nmwdAddress);
}
/**
* @dev transfers ownership of the NFT contract to the owner of
* the marketplace contract. Only if the marketplace owns the NFT
*/
function getBackOwnership() external onlyOwner{
require(address(TokenContract) != address(0),CONTRACT_ADDRESS_NOT_SETUP);
TokenContract.transferOwnership(address(owner));
}
/**
* @dev Purchase _tokenId
* @param _tokenId uint token ID (painting number)
*/
function purchaseToken(uint _tokenId) external payable {
require(forSale[_tokenId], NOT_FOR_SALE);
require(_msgSender() != address(0) && _msgSender() != address(this));
require(price[_tokenId] > 0,PRICE_NOT_SET);
require(msg.value >= price[_tokenId]);
require(TokenContract.ownerOf(_tokenId) != address(0), NOT_VALID_NFT);
address tokenSeller = TokenContract.ownerOf(_tokenId);
require(TokenContract.getApproved(_tokenId) == address(this) ||
TokenContract.isApprovedForAll(tokenSeller, address(this)),
NOT_APPROVED);
forSale[_tokenId] = false;
// this is the fee of the contract per transaction: 0.8%
uint256 saleFee = (msg.value / 1000) * 8;
contractBalance += saleFee;
//calculating the net amount of the sale
uint netAmount = msg.value - saleFee;
(address royaltyReceiver, uint256 royaltyAmount) = TokenContract.royaltyInfo( _tokenId, netAmount);
//calculating the amount to pay the seller
uint256 toPaySeller = netAmount - royaltyAmount;
//paying the seller and the royalty recepient
(bool successSeller, ) =tokenSeller.call{value: toPaySeller, gas: 120000}("");
require( successSeller, "Paying seller failed");
(bool successRoyalties, ) =royaltyReceiver.call{value: royaltyAmount, gas: 120000}("");
require( successRoyalties, "Paying Royalties failed");
//transfer the NFT to the buyer
TokenContract.safeTransferFrom(tokenSeller, _msgSender(), _tokenId);
//notifying the blockchain
emit Sent(tokenSeller, toPaySeller);
emit RoyaltyPaid(royaltyReceiver, royaltyAmount);
}
/**
* @dev mint an NFT through the market place
* @param _to the address that will receive the freshly minted NFT
* @param _tokenId uint token ID (painting number)
*/
function mintThroughPurchase(address _to, uint _tokenId) external payable {
require(price[_tokenId] > 0, PRICE_NOT_SET);
require(msg.value >= price[_tokenId],NOT_EHOUGH_ETHER);
require(_msgSender() != address(0) && _msgSender() != address(this));
//avoid reentrancy. Also mintLocked before launch time.
require(!mintLock,MINTING_LOCKED);
mintLock=true;
//we extract the royalty address from the mapping
address royaltyRecipient = royaltyAddress[_tokenId];
//this is hardcoded 6.0% for all NFTs
uint royaltyValue = 600;
contractBalance += msg.value;
TokenContract.mint(_to, _tokenId, royaltyRecipient, royaltyValue);
mintLock=false;
}
/**
* @dev send / withdraw _amount to _payee
* @param _payee the address where the funds are going to go
* @param _amount the amount of Ether that will be sent
*/
function withdrawFromContract(address _payee, uint _amount) external onlyOwner {
require(_payee != address(0) && _payee != address(this));
require(contractBalance >= _amount, INSUFICIENT_BALANCE);
require(_amount > 0 && _amount <= address(this).balance, NOT_EHOUGH_ETHER);
//we check if somebody has hacked the contract, in which case we send all the funds to
//the owner of the contract
if(contractBalance != address(this).balance){
contractBalance = 0;
payable(owner).transfer(address(this).balance);
emit SecurityWithdrawal(owner, _amount);
}else{
contractBalance -= _amount;
payable(_payee).transfer(_amount);
emit Sent(_payee, _amount);
}
}
/**
* @dev Updates price for the _tokenId NFT
* @dev Throws if updating price to the same current price, or to negative
* value, or is not the owner of the NFT.
* @param _price the price in wei for the NFT
* @param _tokenId uint token ID (painting number)
*/
function setPrice(uint _price, uint _tokenId) external {
require(_price > 0, NEGATIVE_VALUE);
require(_price != price[_tokenId], NO_CHANGES_INTENDED);
//Only owner of NFT can set a price
address _address = TokenContract.ownerOf(_tokenId);
require(_address == _msgSender());
//finally, we do what we came here for.
price[_tokenId] = _price;
}
/**
* @dev Updates price for the _tokenId NFT before minting
* @dev Throws if updating price to the same current price, or to negative
* value, or if sender is not the owner of the marketplace.
* @param _price the price in wei for the NFT
* @param _tokenId uint token ID (painting number)
* @param _royaltyAddress the address that will receive the royalties.
*/
function setPriceForMinting(uint _price, uint _tokenId, address _royaltyAddress) external onlyOwner{
require(_price > 0, NEGATIVE_VALUE);
require(_price != price[_tokenId], NO_CHANGES_INTENDED);
require(_royaltyAddress != address(0) && _royaltyAddress != address(this),INVALID_ADDRESS);
//this makes sure this is only set before minting. It is impossible to change the
//royalty address once it's been minted. The price can then be only reset by the NFT owner.
require( !TokenContract.exists(_tokenId),NFT_ALREADY_MINTED);
//finally, we do what we came here for.
price[_tokenId] = _price;
royaltyAddress[_tokenId] = _royaltyAddress;
}
/**
* @dev get _tokenId price in wei
* @param _tokenId uint token ID
*/
function getPrice(uint _tokenId) external view returns (uint256){
return price[_tokenId];
}
/**
* @dev get marketplace's balance (weis)
*/
function getMarketPlaceBalance() external view returns (uint256){
return contractBalance;
}
/**
* @dev sets the token with _tokenId a boolean representing if it's for sale or not.
* @param _tokenId uint token ID
* @param _forSale is it or not for sale? (true/false)
*/
function setForSale(uint _tokenId, bool _forSale) external returns (bool){
try TokenContract.ownerOf(_tokenId) returns (address _address) {
require(_address == _msgSender(),NOT_NFT_OWNER);
}catch {
return false;
}
require(_forSale != forSale[_tokenId],NO_CHANGES_INTENDED);
forSale[_tokenId] = _forSale;
return true;
}
/**
* @dev gets the token with _tokenId forSale variable.
* @param _tokenId uint token ID
*/
function getForSale(uint _tokenId) external view returns (bool){
return forSale[_tokenId];
}
/**
* @dev Burns an NFT.
* @param _tokenId of the NFT to burn.
*/
function burn(uint256 _tokenId ) external onlyOwner {
TokenContract.burn( _tokenId);
}
/**
* @dev the receive method to avoid balance incongruence
*/
receive() external payable{
contractBalance += msg.value;
}
/**
* @dev locks/unlocks the mint method.
* @param _locked bool value to set.
*/
function setMintLock(bool _locked) external onlyOwner {
mintLock=_locked;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract Owned {
/**
* @dev Error constants.
*/
string public constant NOT_CURRENT_OWNER = "0101";
string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = "0102";
/**
* @dev Current owner address.
*/
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
);
event _msg(address deliveredTo, string msg);
function isOwned() internal {
owner = msg.sender;
emit _msg(owner, "set owner" );
}
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
emit _msg(owner, "passed ownership requirement" );
_;
}
/**
* @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), CANNOT_TRANSFER_TO_ZERO_ADDRESS);
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
function getOwner() public view returns (address){
return owner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./nf-token-enumerable.sol";
import "./nf-token-metadata.sol";
import "./owned.sol";
import "./erc2981-per-token-royalties.sol";
contract StopTheWarOnDrugs is NFTokenEnumerable, NFTokenMetadata,
///Owned,
ERC2981PerTokenRoyalties {
/**
* @dev error when an NFT is attempted to be minted after the max
* supply of NFTs has been already reached.
*/
string constant MAX_TOKENS_MINTED = "0401";
/**
* @dev error when the message for an NFT is trying to be set afet
* it has been already set.
*/
string constant MESSAGE_ALREADY_SET = "0402";
/**
* @dev The message doesn't comply with the size restrictions
*/
string constant NOT_VALID_MSG = "0403";
/**
* @dev Can't pass 0 as value for the argument
*/
string constant ZERO_VALUE = "0404";
/**
* @dev The maximum amount of NFTs that can be minted in this collection
*/
uint16 constant MAX_TOKENS = 904;
/**
* @dev 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;
/**
* @dev Mapping from NFT ID to message.
*/
mapping (uint256 => string) private idToMsg;
constructor(string memory _name, string memory _symbol){
isOwned();
nftName = _name;
nftSymbol = _symbol;
}
/**
* @dev Mints a new NFT.
* @notice an approveForAll is given to the owner of the contract.
* This is due to the fact that the marketplae of this project will
* own this contract. Therefore, the NFTs will be transactable in
* the marketplace by default without any extra step from the user.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
* @param royaltyRecipient the address that will be entitled for the royalties.
* @param royaltyValue the percentage (from 0 - 10000) of the royalties
* @notice royaltyValue is amplified 100 times to be able to write a percentage
* with 2 decimals of precision. Therefore, 1 => 0.01%; 100 => 1%; 10000 => 100%
* @notice the URI is build from the tokenId since it is the SHA2-256 of the
* URI content in IPFS.
*/
function mint(address _to, uint256 _tokenId,
address royaltyRecipient, uint256 royaltyValue)
external onlyOwner
{
_mint(_to, _tokenId);
//uri setup
string memory _uri = getURI(_tokenId);
idToUri[_tokenId] = _uri;
//royalties setup
if (royaltyValue > 0) {
_setTokenRoyalty(_tokenId, royaltyRecipient, royaltyValue);
}
//approve marketplace
if(!ownerToOperators[_to][owner]){
ownerToOperators[_to][owner] = true;
}
}
/**
* @dev Mints a new NFT.
* @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 override (NFTokenEnumerable, NFToken){
require( tokens.length < MAX_TOKENS, MAX_TOKENS_MINTED );
super._mint(_to, _tokenId);
}
/**
* @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 override (NFTokenEnumerable, NFToken){
super._addNFToken(_to, _tokenId);
}
function addNFToken(address _to, uint256 _tokenId) internal {
_addNFToken(_to, _tokenId);
}
/**
* @dev Burns a NFT.
* @notice This is an 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. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn( uint256 _tokenId ) internal override (NFTokenEnumerable, NFTokenMetadata) {
super._burn(_tokenId);
}
function burn(uint256 _tokenId ) public onlyOwner {
//clearing the uri
idToUri[_tokenId] = "";
//clearing the royalties
_setTokenRoyalty(_tokenId, address(0), 0);
//burning the token for good
_burn( _tokenId);
}
/**
* @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable
* extension to remove double storage(gas optimization) of owner nft count.
* @param _owner Address for whom to query the count.
* @return Number of _owner NFTs.
*/
function _getOwnerNFTCount( address _owner ) internal override(NFTokenEnumerable, NFToken) view returns (uint256) {
return super._getOwnerNFTCount(_owner);
}
function getOwnerNFTCount( address _owner ) public view returns (uint256) {
return _getOwnerNFTCount(_owner);
}
/**
* @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
override (NFTokenEnumerable, NFToken)
{
super._removeNFToken(_from, _tokenId);
}
function removeNFToken(address _from, uint256 _tokenId) internal {
_removeNFToken(_from, _tokenId);
}
/**
* @dev A custom message given for the first NFT buyer.
* @param _tokenId Id for which we want the message.
* @return Message of _tokenId.
*/
function tokenMessage(
uint256 _tokenId
)
external
view
validNFToken(_tokenId)
returns (string memory)
{
return idToMsg[_tokenId];
}
/**
* @dev Sets a custom message for the NFT with _tokenId.
* @notice only the owner of the NFT can do this. Not even approved or
* operators can execute this function.
* @param _tokenId Id for which we want the message.
* @param _msg the custom message.
*/
function setTokenMessage(
uint256 _tokenId,
string memory _msg
)
external
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_msgSender() == tokenOwner, NOT_OWNER);
require(bytes(idToMsg[_tokenId]).length == 0, MESSAGE_ALREADY_SET);
bool valid_msg = validateMsg(_msg);
require(valid_msg, NOT_VALID_MSG);
idToMsg[_tokenId] = _msg;
}
/**
* @dev Check if the message string has a valid length
* @param _msg the custom message.
*/
function validateMsg(string memory _msg) public pure returns (bool){
bytes memory b = bytes(_msg);
if(b.length < 1) return false;
if(b.length > 300) return false; // Cannot be longer than 300 characters
return true;
}
/**
* @dev returns the list of NFTs owned by certain address.
* @param _address Id for which we want the message.
*/
function getNFTsByAddress(
address _address
)
view external returns (uint256[] memory)
{
return ownerToIds[_address];
}
/**
* @dev Builds and return the URL string from the tokenId.
* @notice the tokenId is the SHA2-256 of the URI content in IPFS.
* This ensures the complete authenticity of the token minted. The URL is
* therefore an IPFS URL which follows the pattern:
* ipfs://<CID>
* And the CID can be constructed as follows:
* CID = F01701220<ID>
* F signals that the CID is in hexadecimal format. 01 means CIDv1. 70 signals
* dag-pg link-data coding used. 12 references the hashing algorith SHA2-256.
* 20 is the length in bytes of the hash. In decimal, 32 bytes as specified
* in the SHA2-256 protocol. Finally, <ID> is the tokenId (the hash).
* @param _tokenId of the NFT (the SHA2-256 of the URI content).
*/
function getURI(uint _tokenId) internal pure returns(string memory){
string memory _hex = uintToHexStr(_tokenId);
string memory prefix = "ipfs://F01701220";
string memory result = string(abi.encodePacked(prefix,_hex ));
return result;
}
/**
* @dev Converts a uint into a hex string of 64 characters. Throws if 0 is passed.
* @notice that the returned string doesn't prepend the usual "0x".
* @param _uint number to convert to string.
*/
function uintToHexStr(uint _uint) internal pure returns (string memory) {
require(_uint != 0, ZERO_VALUE);
bytes memory byteStr = new bytes(64);
for (uint j = 0; j < 64 ;j++){
uint curr = (_uint & 15); //mask that allows us to filter only the last 4 bits (last character)
byteStr[63-j] = curr > 9 ? bytes1( uint8(55) + uint8(curr) ) :
bytes1( uint8(48) + uint8(curr) ); // 55 = 65 - 10
_uint = _uint >> 4;
}
return string(byteStr);
}
/**
* @dev Destroys the contract
* @notice that, due to the danger that the call of this contract poses, it is required
* to pass a specific integer value to effectively call this method.
* @param security_value number to pass security restriction (192837).
*/
function seflDestruct(uint security_value) external onlyOwner {
require(security_value == 192837); //this is just to make sure that this method was not called by accident
selfdestruct(payable(owner));
}
/**
* @dev returns boolean representing the existance of an NFT
* @param _tokenId of the NFT to look up.
*/
function exists(uint _tokenId) external view returns (bool) {
if( idToOwner[_tokenId] == address(0)){
return false;
}else{
return true;
}
}
}
// 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 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev Utility library of inline functions on addresses.
* @notice Based on:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
* Requires EIP-1052.
*/
library AddressUtils
{
/**
* @dev Returns whether the target address is a contract.
* @param _addr Address to check.
* @return addressCheck True if _addr is a contract, false if not.
*/
function isContract(
address _addr
)
internal
view
returns (bool addressCheck)
{
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(_addr) } // solhint-disable-line
addressCheck = (codehash != 0x0 && codehash != accountHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./nf-token.sol";
import "./erc721-enumerable.sol";
/**
* @dev Optional enumeration implementation for ERC-721 non-fungible token standard.
*/
contract NFTokenEnumerable is NFToken, ERC721Enumerable {
/**
* @dev List of revert message codes. Implementing dApp should handle showing the correct message.
* Based on 0xcert framework error codes.
*/
string constant INVALID_INDEX = "0201";
/**
* @dev Array of all NFT IDs.
*/
uint256[] internal tokens;
/**
* @dev Mapping from token ID to 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()
{
supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable
}
/**
* @dev Returns the count of all existing NFTokens.
* @return Total supply of NFTs.
*/
function totalSupply()
external
override
view
returns (uint256)
{
return tokens.length;
}
/**
* @dev Returns NFT ID by its index.
* @param _index A counter less than `totalSupply()`.
* @return Token id.
*/
function tokenByIndex(
uint256 _index
)
external
override
view
returns (uint256)
{
require(_index < tokens.length, INVALID_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.
* @return Token id.
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
override
view
returns (uint256)
{
require(_index < ownerToIds[_owner].length, INVALID_INDEX);
return ownerToIds[_owner][_index];
}
/**
* @dev Mints a new NFT.
* @notice This is an internal 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
override
virtual
{
super._mint(_to, _tokenId);
tokens.push(_tokenId);
idToIndex[_tokenId] = tokens.length - 1;
}
/**
* @dev Burns a NFT.
* @notice This is an 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. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
uint256 _tokenId
)
internal
override
virtual
{
super._burn(_tokenId);
uint256 tokenIndex = idToIndex[_tokenId];
uint256 lastTokenIndex = tokens.length - 1;
uint256 lastToken = tokens[lastTokenIndex];
tokens[tokenIndex] = lastToken;
tokens.pop();
// This wastes gas if you are burning the last token but saves a little gas if you are not.
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
override
virtual
{
require(idToOwner[_tokenId] == _from, NOT_OWNER);
delete idToOwner[_tokenId];
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length - 1;
if (lastTokenIndex != tokenToRemoveIndex)
{
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].pop();
}
/**
* @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
override
virtual
{
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
idToOwner[_tokenId] = _to;
ownerToIds[_to].push(_tokenId);
idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1;
}
/**
* @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable
* extension to remove double storage(gas optimization) of owner nft count.
* @param _owner Address for whom to query the count.
* @return Number of _owner NFTs.
*/
function _getOwnerNFTCount(
address _owner
)
internal
override
virtual
view
returns (uint256)
{
return ownerToIds[_owner].length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./nf-token.sol";
import "./erc721-metadata.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()
{
supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata
}
/**
* @dev Returns a descriptive name for a collection of NFTokens.
* @return _name Representing name.
*/
function name()
external
override
view
returns (string memory _name)
{
_name = nftName;
}
/**
* @dev Returns an abbreviated name for NFTokens.
* @return _symbol Representing symbol.
*/
function symbol()
external
override
view
returns (string memory _symbol)
{
_symbol = nftSymbol;
}
/**
* @dev A distinct URI (RFC 3986) for a given NFT.
* @param _tokenId Id for which we want uri.
* @return URI of _tokenId.
*/
function tokenURI(
uint256 _tokenId
)
external
override
view
validNFToken(_tokenId)
returns (string memory)
{
return idToUri[_tokenId];
}
/**
* @dev Burns a NFT.
* @notice This is an 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. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
uint256 _tokenId
)
internal
override
virtual
{
super._burn(_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 an 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 memory _uri
)
internal
validNFToken(_tokenId)
{
idToUri[_tokenId] = _uri;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './ierc2981-royalties.sol';
import "./supports-interface.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
contract ERC2981PerTokenRoyalties is IERC2981Royalties, SupportsInterface {
/**
* @dev This is where the info about the royalty resides
* @dev recipient is the address where the royalties should be sent to.
* @dev value is the percentage of the sale value that will be sent as royalty.
* @notice "value" will be expressed as an unsigned integer between 0 and 1000.
* This means that 10000 = 100%, and 1 = 0.01%
*/
struct Royalty {
address recipient;
uint256 value;
}
/**
* @dev the data structure where the NFT id points to the Royalty struct with the
* corresponding royalty info.
*/
mapping(uint256 => Royalty) internal idToRoyalties;
constructor(){
supportedInterfaces[0x2a55205a] = true; // ERC2981
}
/**
* @dev Sets token royalties
* @param id the token id fir which we register the royalties
* @param recipient recipient of the royalties
* @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)
*/
function _setTokenRoyalty(
uint256 id,
address recipient,
uint256 value
) internal {
require(value <= 10000, 'ERC2981Royalties: Too high');
idToRoyalties[id] = Royalty(recipient, value);
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
Royalty memory royalty = idToRoyalties[_tokenId];
return (royalty.recipient, (_salePrice * royalty.value) / 10000);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./erc721.sol";
import "./erc721-token-receiver.sol";
import "./supports-interface.sol";
import "./address-utils.sol";
import "./context.sol";
import "./owned.sol";
/**
* @dev Implementation of ERC-721 non-fungible token standard.
*/
contract NFToken is
ERC721,
Context,
SupportsInterface,
Owned
{
using AddressUtils for address;
/**
* @dev List of revert message codes. Implementing dApp should handle showing the correct message.
* Based on 0xcert framework error codes.
*/
string constant ZERO_ADDRESS = "0301";
string constant NOT_VALID_NFT = "0302";
string constant NOT_OWNER_OR_OPERATOR = "0303";
string constant NOT_OWNER_APPROVED_OR_OPERATOR = "0304";
string constant NOT_ABLE_TO_RECEIVE_NFT = "0305";
string constant NFT_ALREADY_EXISTS = "0306";
string constant NOT_OWNER = "0307";
string constant IS_OWNER = "0308";
/**
* @dev Magic value of a smart contract that can recieve NFT.
* Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")).
*/
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
/**
* @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 idToApproval;
/**
* @dev Mapping from owner address to count of his tokens.
*/
mapping (address => uint256) private ownerToNFTokenCount;
/**
* @dev Mapping from owner address to mapping of operator addresses.
*/
mapping (address => mapping (address => bool)) internal ownerToOperators;
/**
* @dev Guarantees that the_msgSender() 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 ==_msgSender() || ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_OR_OPERATOR
);
_;
}
/**
* @dev Guarantees that the_msgSender() is allowed to transfer NFT.
* @param _tokenId ID of the NFT to transfer.
*/
modifier canTransfer(
uint256 _tokenId
)
{
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner ==_msgSender()
|| idToApproval[_tokenId] ==_msgSender()
|| ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_APPROVED_OR_OPERATOR
);
_;
}
/**
* @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), NOT_VALID_NFT);
_;
}
/**
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x80ac58cd] = true; // ERC721
}
/**
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @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 calldata _data
)
external
override
{
_safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @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
override
{
_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. This function can be changed to payable.
* @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
override
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
}
/**
* @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable.
* @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
override
canOperate(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner, IS_OWNER);
idToApproval[_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
override
{
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _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.
* @return Balance of _owner.
*/
function balanceOf(
address _owner
)
external
override
view
returns (uint256)
{
require(_owner != address(0), ZERO_ADDRESS);
return _getOwnerNFTCount(_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.
* @return _owner Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
override
view
returns (address _owner)
{
_owner = idToOwner[_tokenId];
require(_owner != address(0), NOT_VALID_NFT);
}
/**
* @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.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
override
view
validNFToken(_tokenId)
returns (address)
{
return idToApproval[_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.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
override
view
returns (bool)
{
return ownerToOperators[_owner][_operator];
}
/**
* @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
)
internal
{
address from = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(from, _tokenId);
_addNFToken(_to, _tokenId);
//Native marketplace (owner) will always be an authorized operator.
if(!ownerToOperators[_to][owner]){
ownerToOperators[_to][owner] = true;
}
emit Transfer(from, _to, _tokenId);
}
/**
* @dev Mints a new NFT.
* @notice This is an internal 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_msgSender().
*/
function _mint(
address _to,
uint256 _tokenId
)
internal
virtual
{
require(_to != address(0), ZERO_ADDRESS);
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
_addNFToken(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, address(0), _tokenId, "");
require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);
}
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Burns a NFT.
* @notice This is an 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. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
uint256 _tokenId
)
internal
virtual
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(tokenOwner, _tokenId);
emit Transfer(tokenOwner, address(0), _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
virtual
{
require(idToOwner[_tokenId] == _from, NOT_OWNER);
ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 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
virtual
{
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
idToOwner[_tokenId] = _to;
ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to] + 1;
}
/**
* @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable
* extension to remove double storage (gas optimization) of owner nft count.
* @param _owner Address for whom to query the count.
* @return Number of _owner NFTs.
*/
function _getOwnerNFTCount(
address _owner
)
internal
virtual
view
returns (uint256)
{
return ownerToNFTokenCount[_owner];
}
/**
* @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 memory _data
)
private
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);
}
}
/**
* @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 (idToApproval[_tokenId] != address(0))
{
delete idToApproval[_tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev Optional enumeration extension for ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
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.
* @return Total supply of NFTs.
*/
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()`.
* @return Token id.
*/
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)`.
* @return Token id.
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
view
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
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 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 calldata _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 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.
* @return Balance of _owner.
*/
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.
* @return Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
view
returns (address);
/**
* @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.
* @return Address that _tokenId is approved 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.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev ERC-721 interface for accepting safe transfers.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
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.
* @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./erc165.sol";
/**
* @dev Implementation of standard for detect smart contract interfaces.
*/
contract SupportsInterface is
ERC165
{
/**
* @dev Mapping of supported intefraces. You must not set element 0xffffffff to true.
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/**
* @dev Function to check which interfaces are suported by this contract.
* @param _interfaceID Id of the interface.
* @return True if _interfaceID is supported, false otherwise.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
override
view
returns (bool)
{
return supportedInterfaces[_interfaceID];
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev A standard for detecting smart contract interfaces.
* See: https://eips.ethereum.org/EIPS/eip-165.
*/
interface ERC165
{
/**
* @dev Checks if the smart contract includes a specific interface.
* This function uses less than 30,000 gas.
* @param _interfaceID The interface identifier, as specified in ERC-165.
* @return True if _interfaceID is supported, false otherwise.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev Optional metadata extension for ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721Metadata
{
/**
* @dev Returns a descriptive name for a collection of NFTs in this contract.
* @return _name Representing name.
*/
function name()
external
view
returns (string memory _name);
/**
* @dev Returns a abbreviated name for a collection of NFTs in this contract.
* @return _symbol Representing symbol.
*/
function symbol()
external
view
returns (string memory _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".
* @return URI of _tokenId.
*/
function tokenURI(uint256 _tokenId)
external
view
returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
} | Mints a new NFT. This is an internal 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. _to The address that will own the minted NFT. _tokenId of the NFT to be minted by the_msgSender()./ | function _mint(
address _to,
uint256 _tokenId
)
internal
virtual
{
require(_to != address(0), ZERO_ADDRESS);
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
_addNFToken(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, address(0), _tokenId, "");
require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);
}
emit Transfer(address(0), _to, _tokenId);
}
| 5,804,301 |
/**
The software and documentation available in this repository (the "Software") is
protected by copyright law and accessible pursuant to the license set forth below.
Copyright © 2019 Staked Securely, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person or organization
obtaining the Software (the “Licensee”) to privately study, review, and analyze
the Software. Licensee shall not use the Software for any other purpose. Licensee
shall not modify, transfer, assign, share, or sub-license the Software or any
derivative works 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, TITLE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT
HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT,
OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE.
*/
pragma solidity 0.4.25;
// external dependencies
import "./impl/openzeppelin/ERC721/IERC721Receiver.sol";
import "./impl/openzeppelin/ERC721/IERC721.sol";
import "./impl/openzeppelin/ERC20/IERC20.sol";
import "./impl/openzeppelin/math/SafeMath.sol";
// internal dependencies
import "./interfaces/Approves.sol";
import "./interfaces/Upgradeable.sol";
import "./interfaces/IOpportunityManager.sol";
import "./interfaces/IPositionManager.sol";
import "./interfaces/IFeeModel.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/INAVCalculator.sol";
import "./interfaces/IRAYToken.sol";
import "./interfaces/IStorageWrapper.sol";
import "./interfaces/IStorage.sol";
/// @notice PortfolioManager accepts users assets and mints RAY Tokens [RAYT].
/// The owner of the loans is the RAYT, not the user. This contract is
/// the user entry-point to the core RAY system.
///
/// TODO: Gas optimization in all contracts [once design is settled]
///
/// Author: Devan Purhar
/// Version: 1.0.0
contract PortfolioManager is IERC721Receiver, Upgradeable, Approves {
using SafeMath
for uint256;
/*************** STORAGE VARIABLE DECLARATIONS **************/
/* TODO: Re-order declarations for gas optimization (not important for now) */
// contracts used
bytes32 internal constant RAY_TOKEN_CONTRACT = keccak256("RAYTokenContract");
bytes32 internal constant FEE_MODEL_CONTRACT = keccak256("FeeModelContract");
bytes32 internal constant ADMIN_CONTRACT = keccak256("AdminContract");
bytes32 internal constant POSITION_MANAGER_CONTRACT = keccak256("PositionManagerContract");
bytes32 internal constant STORAGE_WRAPPER_TWO_CONTRACT = keccak256("StorageWrapperTwoContract");
bytes32 internal constant NAV_CALCULATOR_CONTRACT = keccak256("NAVCalculatorContract");
bytes32 internal constant OPPORTUNITY_MANAGER_CONTRACT = keccak256("OpportunityManagerContract");
bytes32 internal constant ORACLE_CONTRACT = keccak256("OracleContract");
bytes32 internal constant name = keccak256("RAY");
IStorage public _storage;
bool public deprecated;
/*************** EVENT DECLARATIONS **************/
/// @notice Logs the minting of a RAY token
event LogMintRAYT(
bytes32 indexed tokenId,
bytes32 indexed portfolioId,
address indexed beneficiary,
uint value
);
/// @notice Logs the minting of an Opportunity token
event LogMintOpportunityToken(
bytes32 tokenId,
bytes32 indexed portfolioId
);
/// @notice Logs the withdrawing from a RAY token
event LogWithdrawFromRAYT(
bytes32 indexed tokenId,
uint value,
uint tokenValue // used to calculate gross return off-chain
);
/// @notice Logs the burning of a RAY token
event LogBurnRAYT(
bytes32 indexed tokenId,
address indexed beneficiary,
uint value,
uint tokenValue // used to calculate gross return off-chain
);
/// @notice Logs a deposit to a RAY token
event LogDepositToRAYT(
bytes32 indexed tokenId,
uint value,
uint tokenValue // used to calculate gross return off-chain
);
/*************** MODIFIER DECLARATIONS **************/
/// @notice Checks if the token id exists within the RAY token contract
modifier existingRAYT(bytes32 tokenId)
{
require(
IRAYToken(_storage.getContractAddress(RAY_TOKEN_CONTRACT)).tokenExists(tokenId),
"#PortfolioMananger existingRAYT Modifier: This is not a valid RAYT"
);
_;
}
/// @notice Checks the caller is our Oracle contract
modifier onlyOracle()
{
require(
_storage.getContractAddress(ORACLE_CONTRACT) == msg.sender,
"#NCController onlyOracle Modifier: Only Oracle can call this"
);
_;
}
/// @notice Checks the caller is our Admin contract
modifier onlyAdmin()
{
require(
_storage.getContractAddress(ADMIN_CONTRACT) == msg.sender,
"#NCController onlyAdmin Modifier: Only Admin can call this"
);
_;
}
/// @notice Checks the caller is our Governance Wallet
///
/// @dev To be removed once fallbacks are
modifier onlyGovernance()
{
require(
msg.sender == _storage.getGovernanceWallet(),
"#PortfolioMananger onlyGovernance Modifier: Only Governance can call this"
);
_;
}
/// @notice Checks the opportunity entered is valid for the portfolio entered
///
/// @param portfolioId - The portfolio id
/// @param opportunityId - The opportunity id
modifier isValidOpportunity(bytes32 portfolioId, bytes32 opportunityId)
{
require(_storage.isValidOpportunity(portfolioId, opportunityId),
"#PortfolioMananger isValidOpportunity modifier: This is not a valid opportunity for this portfolio");
_;
}
/// @notice Checks the opportunity address entered is the correct one
///
/// @param opportunityId - The opportunity id
/// @param opportunity - The contract address of the opportunity
///
/// TODO: Stop passing in, just access storage and grab from there
modifier isCorrectAddress(bytes32 opportunityId, address opportunity)
{
require(_storage.getVerifier(opportunityId) == opportunity,
"#PortfolioMananger isCorrectAddress modifier: This is not the correct address for this opportunity");
_;
}
/// @notice Use this on public functions only
///
/// @param portfolioId - The portfolio id
modifier isValidPortfolio(bytes32 portfolioId)
{
require(_storage.getVerifier(portfolioId) != address(0),
"#PortfolioMananger isValidPortfolio modifier: This is not a valid portfolio");
_;
}
/// @notice Checks if the contract has been set to deprecated
modifier notDeprecated()
{
require(
deprecated == false,
"#PortfolioMananger notDeprecated Modifier: In deprecated mode - this contract has been deprecated"
);
_;
}
/////////////////////// FUNCTION DECLARATIONS BEGIN ///////////////////////
/******************* PUBLIC FUNCTIONS *******************/
/// @notice Sets the Storage contract instance
///
/// @param __storage - The Storage contracts address
constructor(
address __storage
)
public
{
_storage = IStorage(__storage);
}
/// @notice Fallback function to receive Ether
///
/// @dev Required to receive Ether from the OpportunityManager upon withdraws
function() external payable {
}
/** --------------- USER ENTRYPOINTS ----------------- **/
/// @notice Allows users to send ETH or accepted ERC20's to this contract and
/// used as capital. In return the PM mints and gives them a RAYT which
/// represents their 'stake' in the investing pool. A RAYT maps to many shares.
/// The price of shares is determined by the NAV.
///
/// @param portfolioId - The portfolio id
/// @param beneficiary - The owner of the position, supports third-party buys
/// @param value - The amount to be invested, need so we can accept ERC20's
///
/// @return The unique token id of their RAY Token position
function mint(
bytes32 portfolioId,
address beneficiary,
uint value
)
external
notDeprecated
isValidPortfolio(portfolioId)
payable
returns(bytes32)
{
notPaused(portfolioId);
verifyValue(portfolioId, msg.sender, value); // verify the amount they claim to have sent in
uint pricePerShare = INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getPortfolioPricePerShare(portfolioId);
// create their RAY Token
bytes32 tokenId = IPositionManager(_storage.getContractAddress(POSITION_MANAGER_CONTRACT)).createToken(
portfolioId,
_storage.getContractAddress(RAY_TOKEN_CONTRACT),
beneficiary,
value,
pricePerShare
);
// record what portfolio this token belongs too, not in PositionManager since Opp tokens don't need that logic
IStorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_TWO_CONTRACT)).setTokenKey(tokenId, portfolioId);
// record what the rate was when they entered for tracking yield allowances
// not in createToken() b/c Opp Tokens don't need this (unless we implement fees on them)
uint cumulativeRate = IFeeModel(_storage.getContractAddress(FEE_MODEL_CONTRACT)).updateCumulativeRate(_storage.getPrincipalAddress(portfolioId));
IStorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_TWO_CONTRACT)).setEntryRate(portfolioId, tokenId, cumulativeRate);
// increase the available capital in this portfolio upon this investment
IStorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_TWO_CONTRACT)).setAvailableCapital(portfolioId, _storage.getAvailableCapital(portfolioId) + value);
emit LogMintRAYT(tokenId, portfolioId, beneficiary, value);
return tokenId;
}
/// @notice Adds capital to an existing RAYT, this doesn't restrict who adds,
/// addresses besides the owner can add value to the position.
///
/// @dev The value added must be in the same coin type as the position
///
/// @param tokenId - The unique id of the position
/// @param value - The amount of value they wish to add
function deposit(
bytes32 tokenId,
uint value
)
external
payable
notDeprecated
existingRAYT(tokenId)
{
bytes32 portfolioId = _storage.getTokenKey(tokenId);
notPaused(portfolioId);
verifyValue(portfolioId, msg.sender, value);
// don't need the return value of this function (the tokens updated allowance), just need to carry the action out
// since they're adding capital, they're going to a new "capital stage". Their
// allowance will be calculated based on their new amount of capital from this point on.
IFeeModel(_storage.getContractAddress(FEE_MODEL_CONTRACT)).updateAllowance(portfolioId, tokenId);
uint tokenValueBeforeDeposit;
uint pricePerShare;
(tokenValueBeforeDeposit, pricePerShare) = INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getTokenValue(portfolioId, tokenId);
IPositionManager(_storage.getContractAddress(POSITION_MANAGER_CONTRACT)).increaseTokenCapital(
portfolioId,
tokenId,
pricePerShare,
value
);
IStorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_TWO_CONTRACT)).setAvailableCapital(portfolioId, _storage.getAvailableCapital(portfolioId) + value);
emit LogDepositToRAYT(tokenId, value, tokenValueBeforeDeposit);
}
/// @notice Part 1 of 3 to withdraw value from a RAY Position
///
/// @dev Caller must be the owner of the token or our GasFunder (Payer) contract
///
/// @param tokenId - The id of the position
/// @param valueToWithdraw - The value to withdraw
/// @param originalCaller - Unimportant unless Payer is the msg.sender, tells
/// us who signed the original message.
///
/// NOTE: We no longer force a RAY token burn to unlock all value of the position
function redeem(
bytes32 tokenId,
uint valueToWithdraw,
address originalCaller
)
external
notDeprecated
existingRAYT(tokenId)
returns(uint)
{
address addressToUse = INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).onlyTokenOwner(tokenId, originalCaller, msg.sender);
uint totalValue;
uint pricePerShare;
bytes32 portfolioId = _storage.getTokenKey(tokenId);
(totalValue, pricePerShare) = INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getTokenValue(portfolioId, tokenId);
uint valueAfterFee = redeem2(
portfolioId,
tokenId,
pricePerShare,
valueToWithdraw,
totalValue,
addressToUse
);
return valueAfterFee;
}
/// @notice Implemented to receive ERC721 tokens. Main use case is for users to burn
/// and withdraw their RAYT and withdraw the underlying value. It clears
/// it's associated token data, burns the RAYT, and transfers the capital + yield
///
/// @dev Must return hash of the function signature for tx to be valid.
///
/// @param from - The last owner of the RAY before becoming us
/// @param tokenId - the unique id of the position
///
/// TODO: find value of hash: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
//// and make it a constant.
function onERC721Received
(
address /*operator*/,
address from,
uint256 tokenId,
bytes /*data*/
)
public
notDeprecated
returns(bytes4)
{
bytes32 convertedTokenId = bytes32(tokenId);
// optimization: should create local var to store the RAYT Contract Address rather then calling for it twice or more times
if (
(IRAYToken(_storage.getContractAddress(RAY_TOKEN_CONTRACT)).tokenExists(convertedTokenId)) &&
(msg.sender == _storage.getContractAddress(RAY_TOKEN_CONTRACT))
) {
bytes32 portfolioId = _storage.getTokenKey(convertedTokenId);
uint totalValue;
uint pricePerShare;
uint valueAfterFee;
(totalValue, pricePerShare) = INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getTokenValue(portfolioId, convertedTokenId);
// we allow ray tokens with zero value to be sent in still simply to burn
if (totalValue > 0) {
IOracle(_storage.getContractAddress(ORACLE_CONTRACT)).withdrawFromProtocols(portfolioId, totalValue, totalValue);
valueAfterFee = IFeeModel(_storage.getContractAddress(FEE_MODEL_CONTRACT)).takeFee(portfolioId, convertedTokenId, totalValue, totalValue);
IPositionManager(_storage.getContractAddress(POSITION_MANAGER_CONTRACT)).updateTokenUponWithdrawal(
portfolioId,
convertedTokenId,
totalValue,
pricePerShare,
_storage.getTokenShares(portfolioId, convertedTokenId),
INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getPortfolioUnrealizedYield(portfolioId)
);
}
// deletes entire values on the token (shares, capital, owner, existence, etc.)
IStorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_TWO_CONTRACT)).deleteTokenValues(portfolioId, convertedTokenId);
IRAYToken(_storage.getContractAddress(RAY_TOKEN_CONTRACT)).burn(tokenId);
emit LogBurnRAYT(convertedTokenId, from, valueAfterFee, totalValue);
// send them the assets, this could be 0 if the totalvalue was zero to begin with
// could put this transfer in the bottom of if block for the totalvalue check since it would still be safe
// against re-entrancy since we're using transfer()
_transferFunds(portfolioId, from, valueAfterFee);
}
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
/** ----------------- ONLY ORACLE MUTATORS ----------------- **/
/// @notice Entrypoint of the Oracle to tell us where/how to lend
///
/// @dev Could pass in sha3 id and use _storage to find the appropriate contract address
/// but that is an extra external call when we can just do it free beforehand
///
/// @param portfolioId - The portfolio id we're lending for
/// @param opportunityId - The opportunity id we're lending too
/// @param opportunity - The contract address of our Opportunity contract
/// @param value - The amount to lend in-kind
/// @param subtract - Flag to let us know if we wish to subtract value lent
/// from the available capital.
function lend(
bytes32 portfolioId,
bytes32 opportunityId,
address opportunity,
uint value,
bool subtract
)
external
onlyOracle
isValidPortfolio(portfolioId)
// notDeprecated --> called in _lend
{
if (subtract) {
// we don't want to call this on rebalances else we'd have to add capital as we withdrew it and
// then when withdrawing to send to a user we'd have to subtract it right back off == waste of gas
// this can't underflow, Oracle function that calls this has a check
IStorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_TWO_CONTRACT)).setAvailableCapital(portfolioId, _storage.getAvailableCapital(portfolioId) - value);
}
_lend(portfolioId, opportunityId, opportunity, value);
}
/// @notice Entrypoint of the Oracle to tell us where/how to withdraw
///
/// @dev Could pass in sha3 id and use _storage to find the appropriate contract address
/// but that is an extra external call when we can just do it free beforehand
///
/// @param portfolioId - The portfolio id we're withdrawing for
/// @param opportunityId - The opportunity id we're withdrawing from
/// @param opportunity - The contract address of our Opportunity contract
/// @param value - The amount to withdraw in-kind
/// @param add - Flag to let us know if we wish to add value withdrawn
/// into the available capital.
function withdraw(
bytes32 portfolioId,
bytes32 opportunityId,
address opportunity,
uint value,
bool add
)
external
onlyOracle
isValidPortfolio(portfolioId)
// notDeprecated --> called in _withdraw
{ // called by oracle to rebalance, withdraw during upgrade, or withdraw-From-Protocols
// if we're paused, and the oracle is the one who called withdraw(), we want to re-add the withdrawn funds to availbale capital
// we're probably upgrading the opportunity. We don't want to re-add to available capital if fee model is the sender b/c that
// means a user is trying to withdraw from the RAY token (meaning the value flows out instead of staying around and being 'available capital')
if (add) {
IStorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_TWO_CONTRACT)).setAvailableCapital(portfolioId, _storage.getAvailableCapital(portfolioId) + value); // if we're paused we're not
}
_withdraw(portfolioId, opportunityId, opportunity, value);
}
/** ----------------- ONLY ADMIN MUTATORS ----------------- **/
/// @notice Public wrapper so we can call via our Admin contract
///
/// @dev If this is deprecated, should be no value, therefore this function will revert anyway, so we don't ned the deprecation flag
/// since it won't help us debug the error in prod. since error msgs don't show up
function transferFunds(
bytes32 portfolioId,
address beneficiary,
uint value
)
external
onlyAdmin
{
_transferFunds(portfolioId, beneficiary, value);
}
/// @notice Approve function for ERC20's
///
/// @dev Need to approve the OpportunityManager contract
///
/// @param token - Contract address of the token
/// @param beneficiary - The OpportunityManager contract for now
function approve(
address token,
address beneficiary,
uint amount
)
external
onlyAdmin
{
require(
IERC20(token).approve(beneficiary, amount),
"#PortfolioMananger approve: Approval of ERC20 Token failed"
);
}
/// @notice Approval for ERC721's
///
/// @dev Used by Admin so it can deprecate this contract, it transfers
/// all the opporunity tokens to a new contract.
///
/// @param token - The contract address of the token
function setApprovalForAll(
address token,
address to,
bool approved
)
external
onlyAdmin
{
IERC721(token).setApprovalForAll(to, approved);
}
/// @notice Sets the deprecated flag of the contract
///
/// @dev Used when upgrading a contract
///
/// @param value - true to deprecate, false to un-deprecate
function setDeprecated(bool value) external onlyAdmin {
deprecated = value;
}
/********************* INTERNAL FUNCTIONS **********************/
/// @notice Direct OpportunityManager to lend capital
///
/// @param portfolioId - The portfolio id we're lending for
/// @param opportunityId - The opportunity id we're lending too
/// @param opportunity - The contract address of our Opportunity contract
/// @param value - The amount to lend in-kind
function _lend(
bytes32 portfolioId,
bytes32 opportunityId,
address opportunity,
uint value
)
internal
notDeprecated
isValidOpportunity(portfolioId, opportunityId)
isCorrectAddress(opportunityId, opportunity)
{
notPaused(portfolioId);
bytes32 tokenId = _storage.getOpportunityToken(portfolioId, opportunityId);
address principalAddress = _storage.getPrincipalAddress(portfolioId);
bool isERC20;
uint payableValue;
(isERC20, payableValue) = INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).calculatePayableAmount(principalAddress, value);
if (tokenId == bytes32(0)) { // if this contract/portfolio don't have a position yet, buy one and lend
tokenId = IOpportunityManager(_storage.getContractAddress(OPPORTUNITY_MANAGER_CONTRACT)).buyPosition.value(payableValue)(
opportunityId,
address(this),
opportunity,
principalAddress,
value,
isERC20
);
// we'll only have one opportunity token per opporutnity per portfolio
IStorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_TWO_CONTRACT)).setOpportunityToken(portfolioId, opportunityId, tokenId);
emit LogMintOpportunityToken(tokenId, portfolioId);
} else { // else add capital to our existing portfolio's position
IOpportunityManager(_storage.getContractAddress(OPPORTUNITY_MANAGER_CONTRACT)).increasePosition.value(payableValue)(
opportunityId,
tokenId,
opportunity,
principalAddress,
value,
isERC20
);
}
}
/// @notice Direct OpportunityManager to withdraw funds
///
/// @param portfolioId - The portfolio id we're withdrawing for
/// @param opportunityId - The opportunity id we're withdrawing from
/// @param opportunity - The contract address of our Opportunity contract
/// @param value - The amount to withdraw in-kind
function _withdraw(
bytes32 portfolioId,
bytes32 opportunityId,
address opportunity,
uint value
)
internal
notDeprecated // need to block this even though nobody should have value left in the contract if it's deprecated, since the logic could be wrong
isValidOpportunity(portfolioId, opportunityId)
isCorrectAddress(opportunityId, opportunity)
{
uint yield = INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getOpportunityYield(portfolioId, opportunityId, value);
bytes32 tokenId = _storage.getOpportunityToken(portfolioId, opportunityId);
address principalAddress = _storage.getPrincipalAddress(portfolioId);
IOpportunityManager(_storage.getContractAddress(OPPORTUNITY_MANAGER_CONTRACT)).withdrawPosition(
opportunityId,
tokenId,
opportunity,
principalAddress,
value,
_storage.getIsERC20(principalAddress)
);
if (yield > 0) {
INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).updateYield(portfolioId, yield);
}
}
/// @notice Part 2 of 3 to withdraw a tokens value
///
/// @param portfolioId - The portfolio id of the token
/// @param tokenId - The unique token we're withdrawing from
/// @param pricePerShare - The current price per share we're using
/// @param valueToWithdraw - THe value being withdrawn in-kind
/// @param totalValue - The total value of the token
/// @param addressToUse - Added to support us paying for user transactions
function redeem2(
bytes32 portfolioId,
bytes32 tokenId,
uint pricePerShare,
uint valueToWithdraw,
uint totalValue,
address addressToUse
)
internal
returns(uint)
{
address beneficiary = IPositionManager(_storage.getContractAddress(POSITION_MANAGER_CONTRACT)).verifyWithdrawer(
portfolioId,
tokenId,
_storage.getContractAddress(RAY_TOKEN_CONTRACT),
addressToUse, // person who called/signed to call this function
pricePerShare,
valueToWithdraw,
totalValue
);
valueToWithdraw += IOracle(_storage.getContractAddress(ORACLE_CONTRACT)).withdrawFromProtocols(portfolioId, valueToWithdraw, totalValue);
uint valueAfterFee = IFeeModel(_storage.getContractAddress(FEE_MODEL_CONTRACT)).takeFee(portfolioId, tokenId, valueToWithdraw, totalValue);
redeem3(portfolioId, tokenId, valueToWithdraw, pricePerShare);
emit LogWithdrawFromRAYT(tokenId, valueAfterFee, totalValue);
_transferFunds(portfolioId, beneficiary, valueAfterFee);
return valueAfterFee;
}
/// @notice Part 3 of 3 for withdrawing from a position, updates the tokens storage
/// such as the shares, capital, etc.
///
/// @param portfolioId - The portfolio id we're withdrawing from
/// @param tokenId - The token we're withdrawing from
/// @param valueToWithdraw - The value being withdrawn
/// @param pricePerShare - The price per share we're using to calculate value
function redeem3(
bytes32 portfolioId,
bytes32 tokenId,
uint valueToWithdraw,
uint pricePerShare
)
internal
{
IPositionManager(_storage.getContractAddress(POSITION_MANAGER_CONTRACT)).updateTokenUponWithdrawal(
portfolioId,
tokenId,
valueToWithdraw,
pricePerShare,
_storage.getTokenShares(portfolioId, tokenId),
INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getPortfolioUnrealizedYield(portfolioId)
);
}
/// @notice Used to transfer ETH or ERC20's
///
/// @param portfolioId - The portfolio id, used to get the coin associated
/// @param beneficiary - The address to send funds to - is untrusted
/// @param value - The value to send in-kind
function _transferFunds(
bytes32 portfolioId,
address beneficiary,
uint value
)
internal
{
address principalAddress = _storage.getPrincipalAddress(portfolioId);
if (_storage.getIsERC20(principalAddress)) {
require(
IERC20(principalAddress).transfer(beneficiary, value),
"#PortfolioMananger _transferFunds(): Transfer of ERC20 Token failed"
);
} else {
beneficiary.transfer(value);
}
}
/// @notice Verify the amount the sender claims to give to the system is true
///
/// @dev Used for ETH and ERC20's
///
/// @param portfolioId - The portfolio id, used to get the coin associated
/// @param funder - The payer of the transaction
/// @param inputValue - The value the user said they're contributing by parameter
function verifyValue(
bytes32 portfolioId,
address funder,
uint inputValue
)
internal
{
address principalAddress = _storage.getPrincipalAddress(portfolioId);
if (_storage.getIsERC20(principalAddress)) {
require(
IERC20(principalAddress).transferFrom(funder, address(this), inputValue),
"#PortfolioMananger verifyValue: TransferFrom of ERC20 Token failed"
);
} else {
require(
inputValue == msg.value,
"#PortfolioMananger verifyValue(): ETH value sent does not match input value");
}
}
/// @notice Checks if the portfolio or this Opportunity has been paused.
///
/// @dev Withdrawals are allowed on pauses, lending or accepting value isn't
function notPaused(bytes32 portfolioId) internal view {
require(
_storage.getPausedMode(name) == false &&
_storage.getPausedMode(portfolioId) == false,
"#PortfolioMananger notPaused: In withdraw mode - this function has been paused"
);
}
/** ----------------- FALLBACK FUNCTIONS (to be removed Sept. 26th ----------------- **/
function fallbackClaim(
uint value,
address principalToken,
bool isERC20
)
external
onlyGovernance
{
if (isERC20) {
require(
IERC20(principalToken).transfer(_storage.getGovernanceWallet(), value),
"PortfolioManager fallbackClaim(): ERC20 Transfer failed"
);
} else {
_storage.getGovernanceWallet().transfer(value);
}
}
}
| Implemented to receive ERC721 tokens. Main use case is for users to burn and withdraw their RAYT and withdraw the underlying value. It clears it's associated token data, burns the RAYT, and transfers the capital + yield Must return hash of the function signature for tx to be valid. from - The last owner of the RAY before becoming us tokenId - the unique id of the position TODO: find value of hash: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))/ and make it a constant. optimization: should create local var to store the RAYT Contract Address rather then calling for it twice or more times we allow ray tokens with zero value to be sent in still simply to burn | function onERC721Received
(
address /*operator*/,
address from,
uint256 tokenId,
bytes /*data*/
)
public
notDeprecated
returns(bytes4)
{
bytes32 convertedTokenId = bytes32(tokenId);
if (
(IRAYToken(_storage.getContractAddress(RAY_TOKEN_CONTRACT)).tokenExists(convertedTokenId)) &&
(msg.sender == _storage.getContractAddress(RAY_TOKEN_CONTRACT))
) {
bytes32 portfolioId = _storage.getTokenKey(convertedTokenId);
uint totalValue;
uint pricePerShare;
uint valueAfterFee;
(totalValue, pricePerShare) = INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getTokenValue(portfolioId, convertedTokenId);
if (totalValue > 0) {
IOracle(_storage.getContractAddress(ORACLE_CONTRACT)).withdrawFromProtocols(portfolioId, totalValue, totalValue);
valueAfterFee = IFeeModel(_storage.getContractAddress(FEE_MODEL_CONTRACT)).takeFee(portfolioId, convertedTokenId, totalValue, totalValue);
IPositionManager(_storage.getContractAddress(POSITION_MANAGER_CONTRACT)).updateTokenUponWithdrawal(
portfolioId,
convertedTokenId,
totalValue,
pricePerShare,
_storage.getTokenShares(portfolioId, convertedTokenId),
INAVCalculator(_storage.getContractAddress(NAV_CALCULATOR_CONTRACT)).getPortfolioUnrealizedYield(portfolioId)
);
}
IRAYToken(_storage.getContractAddress(RAY_TOKEN_CONTRACT)).burn(tokenId);
emit LogBurnRAYT(convertedTokenId, from, valueAfterFee, totalValue);
}
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
| 15,852,841 |
./partial_match/3/0xB205ed9d4822C48748194e2Aa8EdCf53d2eB6e84/sources/PPToken.sol | ------------------------------------------------------------------------ Transfer the balance from token owner's account to to account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------require(_value > 0, 'Value should be greater-than zero.'); | function transfer(address to, uint tokens) public override returns (bool success) {
require(balances[msg.sender] >= tokens, 'Insufficient balance');
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
| 5,194,494 |
./partial_match/1/0x81677c261019760859c44bC7D8a70F8C4DbB388e/sources/CrossDelegate.sol | revoke storeman debt storageData Cross storage data xHash hash of HTLC random number | function srcDebtRevoke(CrossTypes.Data storage storageData, bytes32 xHash)
external
{
storageData.htlcTxData.revokeDebtTx(xHash, HTLCTxLib.TxStatus.AssetLocked);
bytes32 srcSmgID;
bytes32 destSmgID;
(srcSmgID, destSmgID) = storageData.htlcTxData.getDebtTx(xHash);
storageData.quota.assetRevoke(srcSmgID, destSmgID);
emit SrcDebtRevokeLogger(xHash, srcSmgID, destSmgID);
}
| 3,920,920 |
./full_match/1/0xffdAe6724380828178EA290444116BcF5d56cF3D/sources/contracts/EricOrb.sol | Returns if a response to a trigger exists, based on the timestamp of the response being non-zero. triggerId_ ID of a trigger to which to check the existance of a response of. return bool If a response to a trigger exists or not./ | function _responseExists(uint256 triggerId_) internal view returns (bool) {
if (responses[triggerId_].timestamp != 0) {
return true;
}
return false;
}
| 4,995,420 |
pragma solidity ^0.4.23;
import "openzeppelin-solidity/contracts/access/rbac/RBAC.sol";
contract NAutoblock is RBAC{
string constant AUTOBLK_ROLE = "autoblocker";
constructor() public {}
modifier onlyAutoblockers() {
require(isAutoblocker(msg.sender), "Autoblocker rights required.");
_;
}
/**
* @dev Allows autoblockers to add people to the autoblocker list.
* @param _toAdd The address to be added to autoblocker list.
*/
function addToAutoblockers(address _toAdd) public {
require(!isAutoblocker(_toAdd), "Address is autoblocker already");
addRole(_toAdd,AUTOBLK_ROLE);
}
function addListToAutoblockers(address[] _toAdd) public {
for(uint256 i = 0; i<_toAdd.length; i++){
addToAutoblockers(_toAdd[i]);
}
}
function removeFromAutoblockers(address _toRemove) public {
require(isAutoblocker(_toRemove), "Address is not autoblocker");
removeRole(_toRemove,AUTOBLK_ROLE);
}
function removeListFromAutoblockers(address[] _toRemove) public {
for(uint256 i = 0; i<_toRemove.length; i++){
removeFromAutoblockers(_toRemove[i]);
}
}
function isAutoblocker(address _address) public view returns(bool) {
return hasRole(_address,AUTOBLK_ROLE);
}
}
| Allows autoblockers to add people to the autoblocker list. _toAdd The address to be added to autoblocker list./ | function addToAutoblockers(address _toAdd) public {
require(!isAutoblocker(_toAdd), "Address is autoblocker already");
addRole(_toAdd,AUTOBLK_ROLE);
}
| 913,360 |
pragma solidity ^0.5.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title 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];
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
/*
* @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;
}
}
contract SupporterRole is Context {
using Roles for Roles.Role;
event SupporterAdded(address indexed account);
event SupporterRemoved(address indexed account);
Roles.Role private _supporters;
constructor () internal {
_addSupporter(_msgSender());
}
modifier onlySupporter() {
require(isSupporter(_msgSender()), "SupporterRole: caller does not have the Supporter role");
_;
}
function isSupporter(address account) public view returns (bool) {
return _supporters.has(account);
}
function addSupporter(address account) public onlySupporter {
_addSupporter(account);
}
function renounceSupporter() public {
_removeSupporter(_msgSender());
}
function _addSupporter(address account) internal {
_supporters.add(account);
emit SupporterAdded(account);
}
function _removeSupporter(address account) internal {
_supporters.remove(account);
emit SupporterRemoved(account);
}
}
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @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() internal 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() internal 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;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev A Secondary contract can only be used by its primary account (the one that created it).
*/
contract Secondary is Context {
address private _primary;
/**
* @dev Emitted when the primary contract changes.
*/
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () internal {
address msgSender = _msgSender();
_primary = msgSender;
emit PrimaryTransferred(msgSender);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(_msgSender() == _primary, "Secondary: caller is not the primary account");
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0), "Secondary: new primary is the zero address");
_primary = recipient;
emit PrimaryTransferred(recipient);
}
}
/**
* @title __unstable__TokenVault
* @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit.
* This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context.
*/
// solhint-disable-next-line contract-name-camelcase
contract __unstable__TokenVault is Secondary {
function transferToken(IERC20 token, address to, uint256 amount) public onlyPrimary {
token.transfer(to, amount);
}
function transferFunds(address payable to, uint256 amount) public onlyPrimary {
require (address(this).balance >= amount);
to.transfer(amount);
}
function () external payable {}
}
/**
* @title MoonStaking
*/
contract MoonStaking is Ownable, Pausable, SupporterRole, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Pool {
uint256 rate;
uint256 adapter;
uint256 totalStaked;
}
struct User {
mapping(address => UserSp) tokenPools;
UserSp ePool;
}
struct UserSp {
uint256 staked;
uint256 lastRewardTime;
uint256 earned;
}
mapping(address => User) users;
mapping(address => Pool) pools;
// The MOON TOKEN!
IERC20 public moon;
uint256 eRate;
uint256 eAdapter;
uint256 eTotalStaked;
__unstable__TokenVault private _vault;
/**
* @param _moon The MOON token.
*/
constructor(IERC20 _moon) public {
_vault = new __unstable__TokenVault();
moon = _moon;
}
/**
* @dev Update token pool rate
* @return True when successful
*/
function updatePoolRate(address pool, uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
pools[pool].rate = _rate;
pools[pool].adapter = _adapter;
return true;
}
/**
* @dev Update epool pool rate
* @return True when successful
*/
function updateEpoolRate(uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
eRate = _rate;
eAdapter = _adapter;
return true;
}
/**
* @dev Checks whether the pool is available.
* @return Whether the pool is available.
*/
function isPoolAvailable(address pool) public view returns (bool) {
return pools[pool].rate != 0;
}
/**
* @dev View pool token info
* @param _pool Token address.
* @return Pool info
*/
function poolTokenInfo(address _pool) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage pool = pools[_pool];
return (pool.rate, pool.adapter, pool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolInfo(address poolAddress) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage sPool = pools[poolAddress];
return (sPool.rate, sPool.adapter, sPool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolEInfo() public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
return (eRate, eAdapter, eTotalStaked);
}
/**
* @dev Get earned reward in e pool.
*/
function getEarnedEpool() public view returns (uint256) {
UserSp storage pool = users[_msgSender()].ePool;
return _getEarned(eRate, eAdapter, pool);
}
/**
* @dev Get earned reward in t pool.
*/
function getEarnedTpool(address stakingPoolAddress) public view returns (uint256) {
UserSp storage stakingPool = users[_msgSender()].tokenPools[stakingPoolAddress];
Pool storage pool = pools[stakingPoolAddress];
return _getEarned(pool.rate, pool.adapter, stakingPool);
}
/**
* @dev Stake with E
* @return true if successful
*/
function stakeE() public payable returns (bool) {
uint256 _value = msg.value;
require(_value != 0, "Zero amount");
address(uint160((address(_vault)))).transfer(_value);
UserSp storage ePool = users[_msgSender()].ePool;
ePool.earned = ePool.earned.add(_getEarned(eRate, eAdapter, ePool));
ePool.lastRewardTime = block.timestamp;
ePool.staked = ePool.staked.add(_value);
eTotalStaked = eTotalStaked.add(_value);
return true;
}
/**
* @dev Stake with tokens
* @param _value Token amount.
* @param token Token address.
* @return true if successful
*/
function stake(uint256 _value, IERC20 token) public returns (bool) {
require(token.balanceOf(_msgSender()) >= _value, "Insufficient Funds");
require(token.allowance(_msgSender(), address(this)) >= _value, "Insufficient Funds Approved");
address tokenAddress = address(token);
require(isPoolAvailable(tokenAddress), "Pool is not available");
_forwardFundsToken(token, _value);
Pool storage pool = pools[tokenAddress];
UserSp storage tokenPool = users[_msgSender()].tokenPools[tokenAddress];
tokenPool.earned = tokenPool.earned.add(_getEarned(pool.rate, pool.adapter, tokenPool));
tokenPool.lastRewardTime = block.timestamp;
tokenPool.staked = tokenPool.staked.add(_value);
pool.totalStaked = pool.totalStaked.add(_value);
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawTokenPool(address token) public whenNotPaused nonReentrant returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
if (tokenStakingPool.earned > 0) {
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
}
if (tokenStakingPool.staked > 0) {
_vault.transferToken(IERC20(token), _msgSender(), tokenStakingPool.staked);
tokenStakingPool.staked = 0;
}
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawEPool() public whenNotPaused nonReentrant returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
if (eStakingPool.earned > 0) {
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
}
if (eStakingPool.staked > 0) {
_vault.transferFunds(_msgSender(), eStakingPool.staked);
eStakingPool.staked = 0;
}
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInTpool(address token) public whenNotPaused returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInEpool() public whenNotPaused returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
return true;
}
/**
* @dev Get reserved token.
*/
function getReserved() public view onlyOwner
returns (uint256 vaultTokens, uint256 vaultFunds) {
address vaultAddress = address(_vault);
vaultTokens = moon.balanceOf(vaultAddress);
vaultFunds = address(uint160(vaultAddress)).balance;
}
/**
* @dev Get reserved token by address.
*/
function getReservedByAddress(IERC20 token) public view onlyOwner returns (uint256) {
return token.balanceOf(address(_vault));
}
/**
* @dev Supply token for the vaults.
* @param amount Supply amount
*/
function supplyVault(uint256 amount)
public onlyOwner
returns (bool) {
moon.transferFrom(_msgSender(), address(_vault), amount);
return true;
}
/**
* @dev deprive tokens from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveToken(address vault, IERC20 token, uint256 amount)
public onlyOwner returns (bool) {
_vault.transferToken(token, vault, amount);
return true;
}
/**
* @dev deprive funds from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveFunds(address payable vault, uint256 amount)
public onlyOwner
returns (bool) {
_vault.transferFunds(vault, amount);
return true;
}
/**
* @dev Fallback function
*/
function () external payable {
address(uint160((address(_vault)))).transfer(msg.value);
}
/**
* @dev Extend parent behavior
* @param erc20Token ERC20 Token
* @param _value Amount contributed
*/
function _forwardFundsToken(IERC20 erc20Token, uint256 _value) internal {
erc20Token.transferFrom(_msgSender(), address(_vault), _value);
}
/**
* @dev Get earned reward.
*/
function _getEarned(uint256 rate, uint256 adapter, UserSp memory stakingPool) internal view returns (uint256) {
uint256 moonPerSec = stakingPool.staked.mul(rate).div(adapter);
return block.timestamp.sub(stakingPool.lastRewardTime).mul(moonPerSec).add(stakingPool.earned);
}
} | Withdraw all available tokens./ | function withdrawEPool() public whenNotPaused nonReentrant returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
if (eStakingPool.earned > 0) {
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
}
if (eStakingPool.staked > 0) {
_vault.transferFunds(_msgSender(), eStakingPool.staked);
eStakingPool.staked = 0;
}
return true;
}
| 6,159,423 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
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;
}
}
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);
}
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;
}
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);
}
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);
}
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);
}
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;
}
}
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;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = 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));
}
}
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)))
);
}
}
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);
}
}
/**
* @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 {}
}
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
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;
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
contract MetaTunes is ERC721, Pausable, Ownable {
using Counters for Counters.Counter;
using SafeMath for uint256;
Counters.Counter private _tokenIdCounter;
event Mint(address indexed to, uint256 indexed tokenId);
uint256 public CAP;
uint256 public PRICE_ONE;
uint256 public PRICE_DISCOUNT_TRIPLE;
uint256 public PRICE_DISCOUNT_TEN;
mapping(address => bool) whitelist;
uint256 presales = 0;
bool mintingStop4Ever = false;
constructor(
string memory _token_name,
string memory _token_symbol,
uint256 _CAP,
uint256 _PRICE_ONE
) ERC721(_token_name, _token_symbol) {
CAP = _CAP;
PRICE_ONE = _PRICE_ONE;
PRICE_DISCOUNT_TRIPLE = _PRICE_ONE.mul(90).div(100); //10% discount
PRICE_DISCOUNT_TEN = _PRICE_ONE.mul(80).div(100); //20% discount
pause();
}
function addToWhitelist(address[] memory wallets, bool enabled)
public
onlyOwner
{
for (uint256 i = 0; i < wallets.length; i++) {
whitelist[wallets[i]] = enabled;
}
}
function mintWhitelist(address _to, uint256 _amount) public payable {
require(whitelist[msg.sender], "Not whitlisted");
require(msg.value >= 5 * 10**16 * _amount);
uint256 newCap = presales.add(_amount);
require(newCap <= 100, "Mint would exceed allowed presale amount");
_mintX(_to, _amount);
presales = newCap;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function setPrice(uint256 newPrice) public onlyOwner {
PRICE_ONE = newPrice;
PRICE_DISCOUNT_TRIPLE = newPrice.mul(90).div(100);
PRICE_DISCOUNT_TEN = newPrice.mul(80).div(100);
}
function mintOne(address _to) public payable whenNotPaused {
require(msg.value >= PRICE_ONE, "Wrong amount sent");
_mintX(_to, 1);
}
function mintThree(address _to) public payable whenNotPaused {
require(msg.value >= PRICE_DISCOUNT_TRIPLE, "wrong amount sent");
_mintX(_to, 3);
}
function mintTen(address _to) public payable whenNotPaused {
require(msg.value >= PRICE_DISCOUNT_TEN, "wrong amount sent");
_mintX(_to, 10);
}
function _mintX(address _to, uint256 _amount) internal {
uint256 totalSupply = totalSupply();
require(
(totalSupply + _amount) <= CAP,
"mint would exceed the totalSupply"
);
require(!mintingStop4Ever, "Minting was stopped foreva eva");
for (uint256 i = 0; i < _amount; i++) {
_safeMint(_to, totalSupply + i);
}
}
function reservedMint(address _to, uint256 _amount) public onlyOwner {
_mintX(_to, _amount);
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
function burnUnsold() public onlyOwner {
mintingStop4Ever = true;
}
} | Returns to normal state. Requirements: - The contract must be paused./ | function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
| 11,733,670 |
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB877(a, b, "SafeMath: subtraction overflow");
}
function SUB877(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 MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV156(a, b, "SafeMath: division by zero");
}
function DIV156(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;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD860(a, b, "SafeMath: modulo by zero");
}
function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT107(address account) 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 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value));
}
function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value));
}
function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value));
}
function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS837(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(uint256(value)));
}
function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(uint256(value)));
}
function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(uint256(value)));
}
function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT524(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(value));
}
function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(value));
}
function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(value));
}
function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT524(set._inner, index));
}
}
contract Initializable {
bool private initialized;
bool private initializing;
modifier INITIALIZER933() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
}
function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING
}
function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA356() 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;
}
uint256[50] private __gap;
}
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
__OWNABLE_INIT_UNCHAINED19();
}
function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER195();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED637(address(0), msgSender);
}
function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER691() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED637(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED637(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
interface INBUNIERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
event LOG470(string log); //inject NONSTANDARD NAMING
}
library console {
address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address243;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG714() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log()"));
}
function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOG714(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// HDCore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract HdcoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many 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 HdCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accHdcorePerShare` (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 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block.
uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The HDCORE TOKEN!
INBUNIERC20 public hdcore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes 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;
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock));
}
// Returns averge fees in this epoch
function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING
address indexed user,
uint256 indexed pid,
uint256 amount
);
event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING
function INITIALIZE896( //inject NONSTANDARD NAMING
INBUNIERC20 _hdcore
) public INITIALIZER933 {
OwnableUpgradeSafe.__OWNABLE_INIT503();
DEV_FEE = 724;
hdcore = _hdcore;
devaddr = msg.sender;
contractStartBlock = block.number;
_superAdmin = msg.sender;
}
function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function ADD659( //inject NONSTANDARD NAMING
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.ADD659(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accHdcorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's HDCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SET408( //inject NONSTANDARD NAMING
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING
uint256 _pid,
bool _withdrawable
) public ONLYOWNER691 {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 7.24%
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
uint16 DEV_FEE;
function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING
require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending HDCOREs on frontend.
function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHdcorePerShare = pool.accHdcorePerShare;
return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING
console.LOG714("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.ADD659(UPDATEPOOL374(pid));
}
pendingRewards = pendingRewards.SUB877(allRewards);
}
// ----
// Function that adds pending rewards, called by the HDCORE token.
// ----
uint256 private hdcoreBalance;
function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING
uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance);
if(newRewards > 0) {
hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.ADD659(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.BALANCEOF536(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.DIV156(totalAllocPoint); // we can do this because pools are only mass updated
uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000);
uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee);
pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659(
hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply)
);
}
// Deposit tokens to HdcoreVault for HDCORE allocation.
function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit APPROVAL172(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount);
_WITHDRAW26(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from HdcoreVault.
function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
_WITHDRAW26(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed
if(_amount > 0) {
user.amount = user.amount.SUB877(_amount);
pool.token.SAFETRANSFER239(address(to), _amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit WITHDRAW483(to, _pid, _amount);
}
function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
}
function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING
if(user.amount == 0) return;
uint256 pending = user
.amount
.MUL487(pool.accHdcorePerShare)
.DIV156(1e12)
.SUB877(user.rewardDebt);
if(pending > 0) {
SAFEHDCORETRANSFER939(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked
function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).APPROVE926(contractAddress, _amount);
}
function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.SAFETRANSFER239(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs.
function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
if(_amount == 0) return;
uint256 hdcoreBal = hdcore.BALANCEOF536(address(this));
if (_amount > hdcoreBal) {
console.LOG714("transfering out for to person:", _amount);
console.LOG714("Balance of this address is :", hdcoreBal);
hdcore.TRANSFER353(_to, hdcoreBal);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
} else {
hdcore.TRANSFER353(_to, _amount);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
}
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
SAFEHDCORETRANSFER939(devaddr, devSend);
}
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing HDCORE governance token holders to do this functions.
function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING
devaddr = _devaddr;
}
address private _superAdmin;
event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING
return _superAdmin;
}
modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING
require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
emit SUPERADMINTRANSFERED362(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SUPERADMINTRANSFERED362(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | inject NONSTANDARD NAMING | function LOG714(address p0, address p1, string memory p2) internal view { | 14,087,724 |
pragma solidity ^0.4.24;
contract ExchangeCash {
address owner;
constructor() public {
owner = msg.sender;
}
uint fee = 10;// 1%
enum S { Inited, Rejected, Cancelled,Done }
enum T { Station, Customer }
struct Exchange {
address stationOwner;
address customer;
uint escrow;
S state;
T exType;
}
Exchange[] public ex;
event __setFee(uint fee);
event __initByStationOwner(uint hid, address stationOwner, uint value,bytes32 offchain);
event __closeByStationOwner(uint hid, bytes32 offchain);
event __releasePartialFund(uint hid,address customer,uint amount,bytes32 offchainP,bytes32 offchainC);
event __addInventory(uint hid, bytes32 offchain);
event __initByCustomer(uint hid, address customer, address stationOwner, uint value,bytes32 offchain);
event __cancel(uint hid, bytes32 offchain);
event __reject(uint hid, bytes32 offchain);
event __finish(uint hid, bytes32 offchain);
event __resetStation(bytes32 offchain, uint hid);
//success if sender is stationOwner
modifier onlyStationOwner(uint hid) {
require(msg.sender == ex[hid].stationOwner);
_;
}
//success if sender is customer
modifier onlyCustomer(uint hid) {
require(msg.sender == ex[hid].customer);
_;
}
//success if sender is stationOwner or customer
modifier onlyStationOwnerOrCustomer(uint hid) {
require(msg.sender == ex[hid].stationOwner || msg.sender == ex[hid].customer);
_;
}
//success if sender is owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier atState(S _s, uint hid) {
require(_s == ex[hid].state);
_;
}
modifier atType(T _t, uint hid) {
require(_t == ex[hid].exType);
_;
}
/**
* @dev Initiate exchange fee by owner
* @param f exchange fee
*/
function setFee(
uint f
)
public
onlyOwner()
{
fee = f;
emit __setFee(fee);
}
/**
* @dev Initiate handshake by stationOwner
* @param offchain record ID in offchain backend database
*/
function initByStationOwner(
bytes32 offchain
)
public
payable
{
require(msg.value > 0);
Exchange memory p;
p.stationOwner = msg.sender;
p.escrow = msg.value;
p.state = S.Inited;
p.exType = T.Station;
ex.push(p);
emit __initByStationOwner(ex.length - 1, msg.sender, msg.value, offchain);
}
//CashOwner close the transaction after init
function closeByStationOwner(uint hid, bytes32 offchain) public onlyStationOwner(hid)
atState(S.Inited, hid)
atType(T.Station, hid)
{
Exchange storage p = ex[hid];
p.state = S.Cancelled;
msg.sender.transfer(p.escrow);
p.escrow = 0;
emit __closeByStationOwner(hid, offchain);
}
//CashOwner close the transaction after init
function addInventory(uint hid, bytes32 offchain)
public
payable
onlyStationOwner(hid)
atState(S.Inited, hid)
atType(T.Station, hid)
{
require(msg.value > 0);
Exchange storage p = ex[hid];
p.escrow += msg.value;
emit __addInventory(hid, offchain);
}
//CoinOwner releaseFundByStationOwner transaction
function releasePartialFund(uint hid,address customer,uint amount, bytes32 offchainP, bytes32 offchainC) public onlyStationOwner(hid)
atState(S.Inited, hid)
atType(T.Station, hid)
{
require(customer != 0x0 && amount > 0);
Exchange storage p = ex[hid];
uint f = (amount * fee) / 1000;
uint t = amount + f;
require(p.escrow >= t);
p.escrow -= t;
owner.transfer(f);
customer.transfer(amount);
emit __releasePartialFund(hid,customer, amount, offchainP, offchainC);
}
/**
* @dev Initiate handshake by Customer
*/
function initByCustomer(
address stationOwner,
bytes32 offchain
)
public
payable
{
require(msg.value > 0);
Exchange memory p;
p.customer = msg.sender;
p.stationOwner = stationOwner;
p.escrow = msg.value;
p.state = S.Inited;
p.exType = T.Customer;
ex.push(p);
emit __initByCustomer(ex.length - 1, msg.sender,stationOwner,msg.value, offchain);
}
//coinOwner cancel the handshake
function cancel(uint hid, bytes32 offchain) public
onlyStationOwnerOrCustomer(hid)
atState(S.Inited, hid)
{
Exchange storage p = ex[hid];
if(p.exType == T.Station && p.stationOwner != 0x0){
p.stationOwner.transfer(p.escrow);
}
if(p.exType == T.Customer && p.customer != 0x0){
p.customer.transfer(p.escrow);
}
p.escrow = 0;
p.state = S.Cancelled;
emit __cancel(hid, offchain);
}
//customer finish transaction for sending the coin to stationOwner
function finish(uint hid, bytes32 offchain) public onlyCustomer(hid)
atState(S.Inited, hid)
atType(T.Customer, hid)
{
Exchange storage p = ex[hid];
uint f = (p.escrow * fee) / 1000;
require(p.escrow > f);
p.stationOwner.transfer(p.escrow-f);
owner.transfer(f);
p.escrow = 0;
p.state = S.Done;
emit __finish(hid, offchain);
}
//CashOwner reject the transaction
function reject(uint hid, bytes32 offchain) public
onlyStationOwner(hid)
atType(T.Customer, hid)
{
Exchange storage p = ex[hid];
p.customer.transfer(p.escrow);
p.escrow = 0;
p.state = S.Rejected;
emit __reject(hid, offchain);
}
//get handshake stage by hid
function getState(uint hid) public constant returns(uint8){
Exchange storage p = ex[hid];
return uint8(p.state);
}
//get handshake balance by hid
function getBalance(uint hid) public constant returns(uint){
Exchange storage p = ex[hid];
return p.escrow;
}
// TODO: remove this function after 3 months once the system is stable
function resetAllStation(bytes32 offchain) public onlyOwner {
for (uint i = 0; i < ex.length; i++) {
Exchange storage p = ex[i];
if(p.escrow > 0 && p.state == S.Inited){
if(p.exType == T.Station && p.stationOwner != 0x0){
p.stationOwner.transfer(p.escrow);
}
if(p.exType == T.Customer && p.customer != 0x0){
p.customer.transfer(p.escrow);
}
p.escrow = 0;
p.state = S.Cancelled;
emit __resetStation(offchain,i);
}
}
}
}
| get handshake balance by hid | function getBalance(uint hid) public constant returns(uint){
Exchange storage p = ex[hid];
return p.escrow;
}
| 13,000,879 |
./full_match/3/0xc96c8c47CFcA7D013e551aB16a89E11bDB8701c0/sources/browser/5ive/FiveBuckToken.sol | Mints the amount of Token to the Owner-address (Only callable from the owner) | function mint(uint256 amount) public
{
require(msg.sender == owner());
_mint(owner(), amount);
}
| 8,149,637 |
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.6;
import "./interfaces/SafeMathUpgradeable.sol";
import "./interfaces/IERC20MetadataUpgradeable.sol";
import "./interfaces/SafeERC20Upgradeable.sol";
import "./interfaces/AddressUpgradeable.sol";
import "./interfaces/ReentrancyGuardUpgradeable.sol";
import "./interfaces/OwnableUpgradeable.sol";
import "./interfaces/PausableUpgradeable.sol";
contract FxBridgeLogic is ReentrancyGuardUpgradeable, OwnableUpgradeable, PausableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20MetadataUpgradeable;
bytes32 public state_fxBridgeId;
uint256 public state_powerThreshold;
address public state_fxOriginatedToken;
uint256 public state_lastEventNonce;
bytes32 public state_lastValsetCheckpoint;
uint256 public state_lastValsetNonce;
mapping(address => uint256) public state_lastBatchNonces;
address[] public bridgeTokens;
struct TransferInfo {
uint256 amount;
address destination;
uint256 fee;
address exchange;
uint256 minExchange;
}
struct BridgeToken {
address addr;
string name;
string symbol;
uint8 decimals;
}
/* =============== INIT =============== */
function init(bytes32 _fxBridgeId, uint256 _powerThreshold, address[] memory _validators, uint256[] memory _powers) public initializer {
__Pausable_init();
__Ownable_init();
__ReentrancyGuard_init();
require(_validators.length == _powers.length, "Malformed current validator set");
uint256 cumulativePower = 0;
for (uint256 i = 0; i < _powers.length; i++) {
cumulativePower = cumulativePower + _powers[i];
if (cumulativePower > _powerThreshold) {
break;
}
}
require(cumulativePower > _powerThreshold, "Submitted validator set signatures do not have enough power.");
bytes32 newCheckpoint = makeCheckpoint(_validators, _powers, 0, _fxBridgeId);
state_fxBridgeId = _fxBridgeId;
state_powerThreshold = _powerThreshold;
state_lastValsetCheckpoint = newCheckpoint;
state_lastValsetNonce = 0;
state_lastEventNonce = 1;
emit ValsetUpdatedEvent(state_lastValsetNonce, state_lastEventNonce, _validators, _powers);
}
/* =============== MUTATIVE FUNCTIONS =============== */
function setFxOriginatedToken(address _tokenAddr) public onlyOwner returns (bool) {
require(_tokenAddr != state_fxOriginatedToken, 'Invalid bridge token');
state_fxOriginatedToken = _tokenAddr;
state_lastEventNonce = state_lastEventNonce.add(1);
emit FxOriginatedTokenEvent(_tokenAddr, IERC20MetadataUpgradeable(_tokenAddr).name(), IERC20MetadataUpgradeable(_tokenAddr).symbol(), IERC20MetadataUpgradeable(_tokenAddr).decimals(), state_lastEventNonce);
return true;
}
function addBridgeToken(address _tokenAddr) public onlyOwner returns (bool) {
require(_tokenAddr != address(0), "Invalid address");
require(_tokenAddr != state_fxOriginatedToken, 'Invalid bridge token');
require(!_isContainToken(bridgeTokens, _tokenAddr), "Token already exists");
bridgeTokens.push(_tokenAddr);
return true;
}
function delBridgeToken(address _tokenAddr) public onlyOwner returns (bool) {
require(_isContainToken(bridgeTokens, _tokenAddr), "Token not exists");
for (uint i = 0; i < bridgeTokens.length; i++) {
if (_tokenAddr == bridgeTokens[i]) {
bridgeTokens[i] = bridgeTokens[bridgeTokens.length - 1];
bridgeTokens.pop();
return true;
}
}
return false;
}
function updateValset(address[] memory _newValidators, uint256[] memory _newPowers, uint256 _newValsetNonce,
address[] memory _currentValidators, uint256[] memory _currentPowers, uint256 _currentValsetNonce,
uint8[] memory _v, bytes32[] memory _r, bytes32[] memory _s
) public {
require(_newValsetNonce > _currentValsetNonce, "New valset nonce must be greater than the current nonce");
require(_newValidators.length == _newPowers.length, "Malformed new validator set");
require(
_currentValidators.length == _currentPowers.length &&
_currentValidators.length == _v.length &&
_currentValidators.length == _r.length &&
_currentValidators.length == _s.length,
"Malformed current validator set"
);
require(
makeCheckpoint(_currentValidators, _currentPowers, _currentValsetNonce, state_fxBridgeId) == state_lastValsetCheckpoint,
"Supplied current validators and powers do not match checkpoint."
);
bytes32 newCheckpoint = makeCheckpoint(_newValidators, _newPowers, _newValsetNonce, state_fxBridgeId);
checkValidatorSignatures(_currentValidators, _currentPowers, _v, _r, _s, newCheckpoint, state_powerThreshold);
state_lastValsetCheckpoint = newCheckpoint;
state_lastValsetNonce = _newValsetNonce;
state_lastEventNonce = state_lastEventNonce.add(1);
emit ValsetUpdatedEvent(_newValsetNonce, state_lastEventNonce, _newValidators, _newPowers);
}
function sendToFx(address _tokenContract, bytes32 _destination, bytes32 _targetIBC, uint256 _amount) public nonReentrant whenNotPaused {
require(checkAssetStatus(_tokenContract), "Unsupported token address");
IERC20MetadataUpgradeable(_tokenContract).transferFrom(msg.sender, address(this), _amount);
if (_tokenContract == state_fxOriginatedToken) {
IERC20MetadataUpgradeable(_tokenContract).burn(_amount);
}
state_lastEventNonce = state_lastEventNonce.add(1);
emit SendToFxEvent(_tokenContract, msg.sender, _destination, _targetIBC, _amount, state_lastEventNonce);
}
function submitBatch(address[] memory _currentValidators, uint256[] memory _currentPowers,
uint8[] memory _v, bytes32[] memory _r, bytes32[] memory _s,
uint256[] memory _amounts, address[] memory _destinations, uint256[] memory _fees,
uint256[2] memory _nonceArray, address _tokenContract, uint256 _batchTimeout, address _feeReceive
) public nonReentrant {
{
require(checkAssetStatus(_tokenContract), "Unsupported token address.");
require(
state_lastBatchNonces[_tokenContract] < _nonceArray[1],
"New batch nonce must be greater than the current nonce."
);
require(
block.number < _batchTimeout,
"Batch timeout must be greater than the current block height."
);
require(
_currentValidators.length == _currentPowers.length &&
_currentValidators.length == _v.length &&
_currentValidators.length == _r.length &&
_currentValidators.length == _s.length,
"Malformed current validator set."
);
require(
makeCheckpoint(_currentValidators, _currentPowers, _nonceArray[0], state_fxBridgeId) == state_lastValsetCheckpoint,
"Supplied current validators and powers do not match checkpoint."
);
require(
_amounts.length == _destinations.length && _amounts.length == _fees.length,
"Malformed batch of transactions."
);
checkValidatorSignatures(
_currentValidators,
_currentPowers,
_v,
_r,
_s,
keccak256(abi.encode(
state_fxBridgeId,
// bytes32 encoding of "transactionBatch"
0x7472616e73616374696f6e426174636800000000000000000000000000000000,
_amounts,
_destinations,
_fees,
_nonceArray[1],
_tokenContract,
_batchTimeout,
_feeReceive
)),
state_powerThreshold
);
state_lastBatchNonces[_tokenContract] = _nonceArray[1];
{
uint256 totalFee;
for (uint256 i = 0; i < _amounts.length; i++) {
if (_tokenContract == state_fxOriginatedToken) {
IERC20MetadataUpgradeable(state_fxOriginatedToken).mint(_destinations[i], _amounts[i]);
} else {
IERC20MetadataUpgradeable(_tokenContract).safeTransfer(_destinations[i], _amounts[i]);
}
totalFee = totalFee.add(_fees[i]);
}
if (_tokenContract == state_fxOriginatedToken) {
IERC20MetadataUpgradeable(state_fxOriginatedToken).mint(_feeReceive, totalFee);
} else {
IERC20MetadataUpgradeable(_tokenContract).safeTransfer(_feeReceive, totalFee);
}
}
}
{
state_lastEventNonce = state_lastEventNonce.add(1);
emit TransactionBatchExecutedEvent(_nonceArray[1], _tokenContract, state_lastEventNonce);
}
}
function transferOwner(address _token, address _newOwner) public onlyOwner returns (bool){
IERC20MetadataUpgradeable(_token).transferOwnership(_newOwner);
emit TransferOwnerEvent(_token, _newOwner);
return true;
}
/* =============== QUERY FUNCTIONS =============== */
function lastBatchNonce(address _erc20Address) public view returns (uint256) {
return state_lastBatchNonces[_erc20Address];
}
function getBridgeTokenList() public view returns (BridgeToken[] memory) {
BridgeToken[] memory result = new BridgeToken[](bridgeTokens.length);
for (uint256 i = 0; i < bridgeTokens.length; i++) {
address _tokenAddr = address(bridgeTokens[i]);
BridgeToken memory bridgeToken = BridgeToken(
_tokenAddr,
IERC20MetadataUpgradeable(_tokenAddr).name(),
IERC20MetadataUpgradeable(_tokenAddr).symbol(),
IERC20MetadataUpgradeable(_tokenAddr).decimals());
result[i] = bridgeToken;
}
return result;
}
function checkAssetStatus(address _tokenAddr) public view returns (bool){
if (state_fxOriginatedToken == _tokenAddr) {
return true;
}
return _isContainToken(bridgeTokens, _tokenAddr);
}
/* ============== HELP FUNCTIONS =============== */
function _isContainToken(address[] memory list, address _tokenAddr) private pure returns (bool) {
for (uint i = 0; i < list.length; i++) {
if (list[i] == _tokenAddr) {
return true;
}
}
return false;
}
function verifySig(address _signer, bytes32 _theHash, uint8 _v, bytes32 _r, bytes32 _s) private pure returns (bool) {
bytes32 messageDigest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _theHash));
return _signer == ecrecover(messageDigest, _v, _r, _s);
}
function makeCheckpoint(address[] memory _validators, uint256[] memory _powers, uint256 _valsetNonce, bytes32 _fxBridgeId) public pure returns (bytes32) {
// bytes32 encoding of the string "checkpoint"
bytes32 methodName = 0x636865636b706f696e7400000000000000000000000000000000000000000000;
return keccak256(abi.encode(_fxBridgeId, methodName, _valsetNonce, _validators, _powers));
}
function checkValidatorSignatures(address[] memory _currentValidators, uint256[] memory _currentPowers,
uint8[] memory _v, bytes32[] memory _r, bytes32[] memory _s, bytes32 _theHash, uint256 _powerThreshold
) public pure {
uint256 cumulativePower = 0;
for (uint256 i = 0; i < _currentValidators.length; i++) {
if (_v[i] != 0) {
require(verifySig(_currentValidators[i], _theHash, _v[i], _r[i], _s[i]), "Validator signature does not match.");
cumulativePower = cumulativePower + _currentPowers[i];
if (cumulativePower > _powerThreshold) {
break;
}
}
}
require(cumulativePower > _powerThreshold, "Submitted validator set signatures do not have enough power.");
}
function pause() public onlyOwner whenNotPaused {
_pause();
}
function unpause() public onlyOwner whenPaused {
_unpause();
}
/* =============== EVENTS =============== */
event TransactionBatchExecutedEvent(
uint256 indexed _batchNonce,
address indexed _token,
uint256 _eventNonce
);
event SendToFxEvent(
address indexed _tokenContract,
address indexed _sender,
bytes32 indexed _destination,
bytes32 _targetIBC,
uint256 _amount,
uint256 _eventNonce
);
event FxOriginatedTokenEvent(
address indexed _tokenContract,
string _name,
string _symbol,
uint8 _decimals,
uint256 _eventNonce
);
event ValsetUpdatedEvent(
uint256 indexed _newValsetNonce,
uint256 _eventNonce,
address[] _validators,
uint256[] _powers
);
event TransferOwnerEvent(
address _token,
address _newOwner
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
function mint(address account, uint256 amount) external;
function burn(uint256 amount) external;
function transferOwnership(address newOwner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "./SafeMathUpgradeable.sol";
import "./AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "./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.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "./AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
| Interface for the optional metadata functions from the ERC20 standard. _Available since v4.1._/ | interface IERC20MetadataUpgradeable is IERC20Upgradeable {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function mint(address account, uint256 amount) external;
function burn(uint256 amount) external;
function transferOwnership(address newOwner) external;
}
| 10,058,922 |
/**
*Submitted for verification at Etherscan.io on 2021-09-20
*/
pragma solidity 0.8.4;
/*
* @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;
}
}
/**
* @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);
}
}
/**
* @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 Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev 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());
}
}
}
/**
* @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 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);
}
/**
* @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 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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @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
/**
* Users can purchase tokens after sale started and claim after sale ended
*/
contract IDOSale is AccessControl, Pausable, ReentrancyGuard {
using SafeERC20 for IERC20;
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
// Contract owner address
address public owner;
// Proposed new contract owner address
address public newOwner;
// user address => whitelisted status
mapping(address => bool) public whitelist;
// user address => purchased token amount
mapping(address => uint256) public purchasedAmounts;
// user address => claimed token amount
mapping(address => uint256) public claimedAmounts;
// Once-whitelisted user address array, even removed users still remain
address[] private _whitelistedUsers;
// IDO token price
uint256 public idoPrice;
// IDO token address
IERC20 public ido;
// USDT address
IERC20 public purchaseToken;
// The cap amount each user can purchase IDO up to
uint256 public purchaseCap;
// The total purchased amount
uint256 public totalPurchasedAmount;
// Date timestamp when token sale start
uint256 public startTime;
// Date timestamp when token sale ends
uint256 public endTime;
// Used for returning purchase history
struct Purchase {
address account;
uint256 amount;
}
// ERC20Permit
struct PermitRequest {
uint256 nonce;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event IdoPriceChanged(uint256 idoPrice);
event PurchaseCapChanged(uint256 purchaseCap);
event WhitelistAdded(address indexed account);
event WhitelistRemoved(address indexed account);
event Deposited(address indexed sender, uint256 amount);
event Purchased(address indexed sender, uint256 amount);
event Claimed(address indexed sender, uint256 amount);
event Swept(address indexed sender, uint256 amount);
constructor(
IERC20 _ido,
IERC20 _purchaseToken,
uint256 _idoPrice,
uint256 _purchaseCap,
uint256 _startTime,
uint256 _endTime
) {
require(address(_ido) != address(0), "IDOSale: IDO_ADDRESS_INVALID");
require(address(_purchaseToken) != address(0), "IDOSale: PURCHASE_TOKEN_ADDRESS_INVALID");
require(_idoPrice > 0, "IDOSale: TOKEN_PRICE_INVALID");
require(_purchaseCap > 0, "IDOSale: PURCHASE_CAP_INVALID");
require(block.timestamp <= _startTime && _startTime < _endTime, "IDOSale: TIMESTAMP_INVALID");
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(OPERATOR_ROLE, _msgSender());
ido = _ido;
purchaseToken = _purchaseToken;
owner = _msgSender();
idoPrice = _idoPrice;
purchaseCap = _purchaseCap;
startTime = _startTime;
endTime = _endTime;
emit OwnershipTransferred(address(0), _msgSender());
}
/**************************|
| Setters |
|_________________________*/
/**
* @dev Set ido token price in purchaseToken
*/
function setIdoPrice(uint256 _idoPrice) external onlyOwner {
idoPrice = _idoPrice;
emit IdoPriceChanged(_idoPrice);
}
/**
* @dev Set purchase cap for each user
*/
function setPurchaseCap(uint256 _purchaseCap) external onlyOwner {
purchaseCap = _purchaseCap;
emit PurchaseCapChanged(_purchaseCap);
}
/****************************|
| Ownership |
|___________________________*/
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == _msgSender(), "IDOSale: CALLER_NO_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() external onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
/**
* @dev Transfer the contract ownership.
* The new owner still needs to accept the transfer.
* can only be called by the contract owner.
*
* @param _newOwner new contract owner.
*/
function transferOwnership(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "IDOSale: INVALID_ADDRESS");
require(_newOwner != owner, "IDOSale: OWNERSHIP_SELF_TRANSFER");
newOwner = _newOwner;
}
/**
* @dev The new owner accept an ownership transfer.
*/
function acceptOwnership() external {
require(_msgSender() == newOwner, "IDOSale: CALLER_NO_NEW_OWNER");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
/***********************|
| Role |
|______________________*/
/**
* @dev Restricted to members of the operator role.
*/
modifier onlyOperator() {
require(hasRole(OPERATOR_ROLE, _msgSender()), "IDOSale: CALLER_NO_OPERATOR_ROLE");
_;
}
/**
* @dev Add an account to the operator role.
* @param account address
*/
function addOperator(address account) public onlyOwner {
require(!hasRole(OPERATOR_ROLE, account), "IDOSale: ALREADY_OERATOR_ROLE");
grantRole(OPERATOR_ROLE, account);
}
/**
* @dev Remove an account from the operator role.
* @param account address
*/
function removeOperator(address account) public onlyOwner {
require(hasRole(OPERATOR_ROLE, account), "IDOSale: NO_OPERATOR_ROLE");
revokeRole(OPERATOR_ROLE, account);
}
/**
* @dev Check if an account is operator.
* @param account address
*/
function checkOperator(address account) public view returns (bool) {
return hasRole(OPERATOR_ROLE, account);
}
/***************************|
| Pausable |
|__________________________*/
/**
* @dev Pause the sale
*/
function pause() external onlyOperator {
super._pause();
}
/**
* @dev Unpause the sale
*/
function unpause() external onlyOperator {
super._unpause();
}
/****************************|
| Whitelist |
|___________________________*/
/**
* @dev Return whitelisted users
* The result array can include zero address
*/
function whitelistedUsers() external view returns (address[] memory) {
address[] memory __whitelistedUsers = new address[](_whitelistedUsers.length);
for (uint256 i = 0; i < _whitelistedUsers.length; i++) {
if (!whitelist[_whitelistedUsers[i]]) {
continue;
}
__whitelistedUsers[i] = _whitelistedUsers[i];
}
return __whitelistedUsers;
}
/**
* @dev Add wallet to whitelist
* If wallet is added, removed and added to whitelist, the account is repeated
*/
function addWhitelist(address[] memory accounts) external onlyOperator whenNotPaused {
for (uint256 i = 0; i < accounts.length; i++) {
require(accounts[i] != address(0), "IDOSale: ZERO_ADDRESS");
if (!whitelist[accounts[i]]) {
whitelist[accounts[i]] = true;
_whitelistedUsers.push(accounts[i]);
emit WhitelistAdded(accounts[i]);
}
}
}
/**
* @dev Remove wallet from whitelist
* Removed wallets still remain in `_whitelistedUsers` array
*/
function removeWhitelist(address[] memory accounts) external onlyOperator whenNotPaused {
for (uint256 i = 0; i < accounts.length; i++) {
require(accounts[i] != address(0), "IDOSale: ZERO_ADDRESS");
if (whitelist[accounts[i]]) {
whitelist[accounts[i]] = false;
emit WhitelistRemoved(accounts[i]);
}
}
}
/***************************|
| Purchase |
|__________________________*/
/**
* @dev Return purchase history (wallet address, amount)
* The result array can include zero amount item
*/
function purchaseHistory() external view returns (Purchase[] memory) {
Purchase[] memory purchases = new Purchase[](_whitelistedUsers.length);
for (uint256 i = 0; i < _whitelistedUsers.length; i++) {
purchases[i].account = _whitelistedUsers[i];
purchases[i].amount = purchasedAmounts[_whitelistedUsers[i]];
}
return purchases;
}
/**
* @dev Deposit IDO token to the sale contract
*/
function depositTokens(uint256 amount) external onlyOperator whenNotPaused {
require(amount > 0, "IDOSale: DEPOSIT_AMOUNT_INVALID");
ido.safeTransferFrom(_msgSender(), address(this), amount);
emit Deposited(_msgSender(), amount);
}
/**
* @dev Permit and deposit IDO token to the sale contract
* If token does not have `permit` function, this function does not work
*/
function permitAndDepositTokens(
uint256 amount,
PermitRequest calldata permitOptions
) external onlyOperator whenNotPaused {
require(amount > 0, "IDOSale: DEPOSIT_AMOUNT_INVALID");
// Permit
IERC20Permit(address(ido)).permit(_msgSender(), address(this), amount, permitOptions.deadline, permitOptions.v, permitOptions.r, permitOptions.s);
ido.safeTransferFrom(_msgSender(), address(this), amount);
emit Deposited(_msgSender(), amount);
}
/**
* @dev Purchase IDO token
* Only whitelisted users can purchase within `purchcaseCap` amount
*/
function purchase(uint256 amount) external nonReentrant whenNotPaused {
require(startTime <= block.timestamp, "IDOSale: SALE_NOT_STARTED");
require(block.timestamp < endTime, "IDOSale: SALE_ALREADY_ENDED");
require(amount > 0, "IDOSale: PURCHASE_AMOUNT_INVALID");
require(whitelist[_msgSender()], "IDOSale: CALLER_NO_WHITELIST");
require(purchasedAmounts[_msgSender()] + amount <= purchaseCap, "IDOSale: PURCHASE_CAP_EXCEEDED");
uint256 idoBalance = ido.balanceOf(address(this));
require(totalPurchasedAmount + amount <= idoBalance, "IDOSale: INSUFFICIENT_SELL_BALANCE");
uint256 purchaseTokenAmount = amount * idoPrice / (10 ** 18);
require(purchaseTokenAmount <= purchaseToken.balanceOf(_msgSender()), "IDOSale: INSUFFICIENT_FUNDS");
purchasedAmounts[_msgSender()] += amount;
totalPurchasedAmount += amount;
purchaseToken.safeTransferFrom(_msgSender(), address(this), purchaseTokenAmount);
emit Purchased(_msgSender(), amount);
}
/**
* @dev Purchase IDO token
* Only whitelisted users can purchase within `purchcaseCap` amount
* If `purchaseToken` does not have `permit` function, this function does not work
*/
function permitAndPurchase(
uint256 amount,
PermitRequest calldata permitOptions
) external nonReentrant whenNotPaused {
require(startTime <= block.timestamp, "IDOSale: SALE_NOT_STARTED");
require(block.timestamp < endTime, "IDOSale: SALE_ALREADY_ENDED");
require(amount > 0, "IDOSale: PURCHASE_AMOUNT_INVALID");
require(whitelist[_msgSender()], "IDOSale: CALLER_NO_WHITELIST");
require(purchasedAmounts[_msgSender()] + amount <= purchaseCap, "IDOSale: PURCHASE_CAP_EXCEEDED");
uint256 idoBalance = ido.balanceOf(address(this));
require(totalPurchasedAmount + amount <= idoBalance, "IDOSale: INSUFFICIENT_SELL_BALANCE");
uint256 purchaseTokenAmount = amount * idoPrice / (10 ** 18);
require(purchaseTokenAmount <= purchaseToken.balanceOf(_msgSender()), "IDOSale: INSUFFICIENT_FUNDS");
purchasedAmounts[_msgSender()] += amount;
totalPurchasedAmount += amount;
IERC20Permit(address(purchaseToken)).permit(_msgSender(), address(this), amount, permitOptions.deadline, permitOptions.v, permitOptions.r, permitOptions.s);
purchaseToken.safeTransferFrom(_msgSender(), address(this), purchaseTokenAmount);
emit Purchased(_msgSender(), amount);
}
/************************|
| Claim |
|_______________________*/
/**
* @dev Users claim purchased tokens after token sale ended
*/
function claim(uint256 amount) external nonReentrant whenNotPaused {
require(endTime <= block.timestamp, "IDOSale: SALE_NOT_ENDED");
require(amount > 0, "IDOSale: CLAIM_AMOUNT_INVALID");
require(claimedAmounts[_msgSender()] + amount <= purchasedAmounts[_msgSender()], "IDOSale: CLAIM_AMOUNT_EXCEEDED");
claimedAmounts[_msgSender()] += amount;
ido.safeTransfer(_msgSender(), amount);
emit Claimed(_msgSender(), amount);
}
/**
* @dev `Operator` sweeps `purchaseToken` from the sale contract to `to` address
*/
function sweep(address to) external onlyOwner {
require(to != address(0), "IDOSale: ADDRESS_INVALID");
require(endTime <= block.timestamp, "IDOSale: SALE_NOT_ENDED");
uint256 bal = purchaseToken.balanceOf(address(this));
purchaseToken.transfer(to, bal);
emit Swept(to, bal);
}
} | Remove wallet from whitelist Removed wallets still remain in `_whitelistedUsers` array/ | function removeWhitelist(address[] memory accounts) external onlyOperator whenNotPaused {
for (uint256 i = 0; i < accounts.length; i++) {
require(accounts[i] != address(0), "IDOSale: ZERO_ADDRESS");
if (whitelist[accounts[i]]) {
whitelist[accounts[i]] = false;
emit WhitelistRemoved(accounts[i]);
}
}
}
|__________________________*/
| 6,732,758 |
pragma solidity ^0.4.24;
/* CKBC
// Cinnamomum Kanehirae BlockChain (CKBC)
// ERC20 Contract with Timelock capabilities
// The big intricate timelock mechanisms out here
// ---
// ---
*/
/* an owner is required */
contract Owned {
address public owner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function setOwner(address _owner) onlyOwner public {
owner = _owner;
}
}
/* SafeMath implementation to guard against overflows */
contract SafeMath {
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
assert(c >= _a); // checks for overflow
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_a >= _b); // guard against overflow
return _a - _b;
}
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a * _b;
assert(_a == 0 || c / _a == _b); // checks for overflow
return c;
}
}
/* The main contract for the timelock capable ERC20 token */
contract Token is SafeMath, Owned {
uint256 constant DAY_IN_SECONDS = 86400;
string public constant standard = "0.777";
string public name = "";
string public symbol = "";
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceP;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => uint256[]) public lockTime;
mapping (address => uint256[]) public lockValue;
mapping (address => uint256) public lockNum;
mapping (address => bool) public locker;
uint256 public later = 0;
uint256 public earlier = 0;
/* standard ERC20 events */
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/* custom lock-related events */
event TransferredLocked(address indexed _from, address indexed _to, uint256 _time, uint256 _value);
event TokenUnlocked(address indexed _address, uint256 _value);
/* ERC20 constructor */
function Token(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0);
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
balanceP[msg.sender] = _totalSupply;
}
/* don't allow zero address */
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
/* owner may add & remove optional locker contract */
function addLocker(address _address) public validAddress(_address) onlyOwner {
locker[_address] = true;
}
function removeLocker(address _address) public validAddress(_address) onlyOwner {
locker[_address] = false;
}
/* owner may fast-forward or delay ALL timelocks */
function setUnlockEarlier(uint256 _earlier) public onlyOwner {
earlier = add(earlier, _earlier);
}
function setUnlockLater(uint256 _later) public onlyOwner {
later = add(later, _later);
}
/* shows unlocked balance */
function balanceUnlocked(address _address) public view returns (uint256 _balance) {
_balance = balanceP[_address];
uint256 i = 0;
while (i < lockNum[_address]) {
if (add(now, earlier) > add(lockTime[_address][i], later)) _balance = add(_balance, lockValue[_address][i]);
i++;
}
return _balance;
}
/* shows locked balance */
function balanceLocked(address _address) public view returns (uint256 _balance) {
_balance = 0;
uint256 i = 0;
while (i < lockNum[_address]) {
if (add(now, earlier) < add(lockTime[_address][i], later)) _balance = add(_balance, lockValue[_address][i]);
i++;
}
return _balance;
}
/* standard ERC20 compatible balance accessor */
function balanceOf(address _address) public view returns (uint256 _balance) {
_balance = balanceP[_address];
uint256 i = 0;
while (i < lockNum[_address]) {
_balance = add(_balance, lockValue[_address][i]);
i++;
}
return _balance;
}
/* show the timelock periods and locked values */
function showTime(address _address) public view validAddress(_address) returns (uint256[] _time) {
uint i = 0;
uint256[] memory tempLockTime = new uint256[](lockNum[_address]);
while (i < lockNum[_address]) {
tempLockTime[i] = sub(add(lockTime[_address][i], later), earlier);
i++;
}
return tempLockTime;
}
function showValue(address _address) public view validAddress(_address) returns (uint256[] _value) {
return lockValue[_address];
}
/* calculates and handles the timelocks before related operations */
function calcUnlock(address _address) private {
uint256 i = 0;
uint256 j = 0;
uint256[] memory currentLockTime;
uint256[] memory currentLockValue;
uint256[] memory newLockTime = new uint256[](lockNum[_address]);
uint256[] memory newLockValue = new uint256[](lockNum[_address]);
currentLockTime = lockTime[_address];
currentLockValue = lockValue[_address];
while (i < lockNum[_address]) {
if (add(now, earlier) > add(currentLockTime[i], later)) {
balanceP[_address] = add(balanceP[_address], currentLockValue[i]);
/* emit timelock expiration event */
emit TokenUnlocked(_address, currentLockValue[i]);
} else {
newLockTime[j] = currentLockTime[i];
newLockValue[j] = currentLockValue[i];
j++;
}
i++;
}
uint256[] memory trimLockTime = new uint256[](j);
uint256[] memory trimLockValue = new uint256[](j);
i = 0;
while (i < j) {
trimLockTime[i] = newLockTime[i];
trimLockValue[i] = newLockValue[i];
i++;
}
lockTime[_address] = trimLockTime;
lockValue[_address] = trimLockValue;
lockNum[_address] = j;
}
/* ERC20 compliant transfer method */
function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) {
if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);
if (balanceP[msg.sender] >= _value && _value > 0) {
balanceP[msg.sender] = sub(balanceP[msg.sender], _value);
balanceP[_to] = add(balanceP[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
/* custom timelocked transfer method */
function transferLocked(address _to, uint256[] _time, uint256[] _value) public validAddress(_to) returns (bool success) {
require(_value.length == _time.length);
if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);
uint256 i = 0;
uint256 totalValue = 0;
while (i < _value.length) {
totalValue = add(totalValue, _value[i]);
i++;
}
if (balanceP[msg.sender] >= totalValue && totalValue > 0) {
i = 0;
while (i < _time.length) {
balanceP[msg.sender] = sub(balanceP[msg.sender], _value[i]);
lockTime[_to].length = lockNum[_to]+1;
lockValue[_to].length = lockNum[_to]+1;
lockTime[_to][lockNum[_to]] = add(now, _time[i]);
lockValue[_to][lockNum[_to]] = _value[i];
/* emit custom timelock event */
emit TransferredLocked(msg.sender, _to, lockTime[_to][lockNum[_to]], lockValue[_to][lockNum[_to]]);
/* emit standard transfer event */
emit Transfer(msg.sender, _to, lockValue[_to][lockNum[_to]]);
lockNum[_to]++;
i++;
}
return true;
}
else {
return false;
}
}
/* custom timelocked method */
function transferLockedFrom(address _from, address _to, uint256[] _time, uint256[] _value) public
validAddress(_from) validAddress(_to) returns (bool success) {
require(locker[msg.sender]);
require(_value.length == _time.length);
if (lockNum[_from] > 0) calcUnlock(_from);
uint256 i = 0;
uint256 totalValue = 0;
while (i < _value.length) {
totalValue = add(totalValue, _value[i]);
i++;
}
if (balanceP[_from] >= totalValue && totalValue > 0) {
i = 0;
while (i < _time.length) {
balanceP[_from] = sub(balanceP[_from], _value[i]);
lockTime[_to].length = lockNum[_to]+1;
lockValue[_to].length = lockNum[_to]+1;
lockTime[_to][lockNum[_to]] = add(now, _time[i]);
lockValue[_to][lockNum[_to]] = _value[i];
/* emit custom timelock event */
emit TransferredLocked(_from, _to, lockTime[_to][lockNum[_to]], lockValue[_to][lockNum[_to]]);
/* emit standard transfer event */
emit Transfer(_from, _to, lockValue[_to][lockNum[_to]]);
lockNum[_to]++;
i++;
}
return true;
}
else {
return false;
}
}
/* standard ERC20 compliant transferFrom method */
function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) {
if (lockNum[_from] > 0) calcUnlock(_from);
if (balanceP[_from] >= _value && _value > 0) {
allowance[_from][msg.sender] = sub(allowance[_from][msg.sender], _value);
balanceP[_from] = sub(balanceP[_from], _value);
balanceP[_to] = add(balanceP[_to], _value);
emit Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
/* standard ERC20 compliant approve method */
function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success) {
require(_value == 0 || allowance[msg.sender][_spender] == 0);
if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/* safety method against ether transfer */
function () public payable {
revert();
}
} | standard ERC20 events / custom lock-related events / ERC20 constructor / | function Token(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0);
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
balanceP[msg.sender] = _totalSupply;
}
| 10,405,383 |
./full_match/3/0x7295C2BE0Fabca03ED3514C3dd99658EbC25f3f3/sources/browser/Contract_Code_v2_Min.sol | set param value Authorization Required _index param index _value param value/ onlyOwnercheck index | function setParam(uint _index, uint _value)
public
onlyIfWhitelisted
{
require(_index > 100, "invalid index range");
paramsMapping[_index] = _value;
}
| 8,114,090 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./base/EternalStorage.sol";
import "./base/Controller.sol";
import "./base/IDiamondFacet.sol";
import "./base/IPolicyTrancheTokensFacet.sol";
import "./base/IMarket.sol";
import "./base/IMarketObserver.sol";
import "./base/IMarketObserverDataTypes.sol";
import "./base/AccessControl.sol";
import "./base/SafeMath.sol";
import "./base/Address.sol";
import "./base/Strings.sol";
import "./base/Uint.sol";
import "./base/IERC20.sol";
import "./PolicyFacetBase.sol";
/**
* @dev Business-logic for Policy commissions
*/
contract PolicyTrancheTokensFacet is EternalStorage, Controller, IDiamondFacet, IPolicyTrancheTokensFacet, PolicyFacetBase, IMarketObserver, IMarketObserverDataTypes {
using SafeMath for uint;
using Uint for uint;
using Address for address;
using Strings for string;
/**
* Constructor
*/
constructor (address _settings) Controller(_settings) public {
// empty
}
// IDiamondFacet
function getSelectors () public pure override returns (bytes memory) {
return abi.encodePacked(
IPolicyTrancheTokensFacet.tknName.selector,
IPolicyTrancheTokensFacet.tknSymbol.selector,
IPolicyTrancheTokensFacet.tknTotalSupply.selector,
IPolicyTrancheTokensFacet.tknBalanceOf.selector,
IPolicyTrancheTokensFacet.tknAllowance.selector,
IPolicyTrancheTokensFacet.tknApprove.selector,
IPolicyTrancheTokensFacet.tknTransfer.selector,
IMarketObserver.handleTrade.selector,
IMarketObserver.handleClosure.selector
);
}
// IPolicyTrancheTokensFacet
function tknName(uint256 _index) public view override returns (string memory) {
return string(abi.encodePacked("NAYMS-", address(this).toString(), "-TRANCHE-", uint256(_index + 1).toString()));
}
function tknSymbol(uint256 _index) public view override returns (string memory) {
// max len = 11 chars
return string(abi.encodePacked("N-", address(this).toString().substring(6), "-", uint256(_index + 1).toString()));
}
function tknTotalSupply(uint256 _index) public view override returns (uint256) {
return dataUint256[__i(_index, "numShares")];
}
function tknBalanceOf(uint256 _index, address _owner) public view override returns (uint256) {
string memory k = __ia(_index, _owner, "balance");
return dataUint256[k];
}
function tknAllowance(uint256 _index, address _spender, address _owner) public view override returns (uint256) {
string memory k = __iaa(_index, _owner, _spender, "allowance");
return dataUint256[k];
}
function tknApprove(uint256 /*_index*/, address _spender, address /*_from*/, uint256 /*_value*/) public override {
require(_spender == settings().getRootAddress(SETTING_MARKET), 'only nayms market is allowed to transfer');
}
function tknTransfer(uint256 _index, address _spender, address _from, address _to, uint256 _value) public override {
require(_spender == settings().getRootAddress(SETTING_MARKET), 'only nayms market is allowed to transfer');
_transfer(_index, _from, _to, _value);
}
// Internal functions
function _transfer(uint _index, address _from, address _to, uint256 _value) private {
// when token holder is sending to the market
address market = settings().getRootAddress(SETTING_MARKET);
// if this is a transfer to the market
if (market == _to) {
// and the sender is not the initial holder of the token
address initialHolder = dataAddress[__i(_index, "initialHolder")];
if (initialHolder != _from) {
// then the sender must be a trader, in which case ony allow this if the policy is active
require(dataUint256["state"] == POLICY_STATE_ACTIVE, 'can only trade when policy is active');
}
}
string memory fromKey = __ia(_index, _from, "balance");
string memory toKey = __ia(_index, _to, "balance");
require(dataUint256[fromKey] >= _value, 'not enough balance');
dataUint256[fromKey] = dataUint256[fromKey].sub(_value);
dataUint256[toKey] = dataUint256[toKey].add(_value);
}
function handleTrade(
uint256 _offerId,
uint256 _soldAmount,
uint256 _boughtAmount,
address /*_feeToken*/,
uint256 /*_feeAmount*/,
address /*_buyer*/,
bytes memory _data
) external override {
if (_data.length == 0) {
return;
}
// get data type
(uint256 t) = abi.decode(_data, (uint256));
if (t == MODT_TRANCHE_SALE) {
// get policy address and tranche id
(, address policy, uint256 trancheId) = abi.decode(_data, (uint256, address, uint256));
// if we created this offer
if (policy == address(this)) {
// if we are in the initial sale period
if (dataUint256[__i(trancheId, "state")] == TRANCHE_STATE_SELLING) {
// check tranche token matches sell token
(, address sellToken, , , , , , , , ,) = _getMarket().getOffer(_offerId);
address trancheAddress = dataAddress[__i(trancheId, "address")];
require(trancheAddress == sellToken, "sell token must be tranche token");
// record how many "shares" were sold
dataUint256[__i(trancheId, "sharesSold")] = dataUint256[__i(trancheId, "sharesSold")].add(_soldAmount);
// update tranche balance
dataUint256[__i(trancheId, "balance")] = dataUint256[__i(trancheId, "balance")].add(_boughtAmount);
// tell treasury to add tranche balance value to overall policy balance
_getTreasury().incPolicyBalance(_boughtAmount);
// if the tranche has fully sold out
if (dataUint256[__i(trancheId, "sharesSold")] == dataUint256[__i(trancheId, "numShares")]) {
// flip tranche state to ACTIVE
_setTrancheState(trancheId, TRANCHE_STATE_ACTIVE);
}
}
}
}
}
function handleClosure(
uint256 _offerId,
uint256 /*_unsoldAmount*/,
uint256 /*_unboughtAmount*/,
bytes memory _data
) external override {
if (_data.length == 0) {
return;
}
// get data type
(uint256 t) = abi.decode(_data, (uint256));
// if it's a tranche token buyback trade
if (t == MODT_TRANCHE_BUYBACK) {
// get policy address and tranche id
(, address policy, uint256 trancheId) = abi.decode(_data, (uint256, address, uint256));
// if we created this offer
if (policy == address(this)) {
// if we are in the policy buyback state
if (dataUint256["state"] == POLICY_STATE_BUYBACK) {
// check tranche token matches buy token
(, , , , address buyToken, , , , , ,) = _getMarket().getOffer(_offerId);
address trancheAddress = dataAddress[__i(trancheId, "address")];
require(trancheAddress == buyToken, "buy token must be tranche token");
// NOTE: we're assuming that an order never gets closed until it is sold out
// Sold out = only <=dusk amount remaining (see market for dusk level)
// mark buyback as complete
dataBool[__i(trancheId, "buybackCompleted")] = true;
dataUint256["numTranchesBoughtBack"] += 1;
// if all tranches have been bought back
if (dataUint256["numTranchesBoughtBack"] == dataUint256["numTranches"]) {
// policy is now "closed"
_setPolicyState(POLICY_STATE_CLOSED);
}
}
}
}
}
function _getMarket () internal view returns (IMarket) {
return IMarket(settings().getRootAddress(SETTING_MARKET));
}
}
| if it's a tranche token buyback trade get policy address and tranche id if we created this offer if we are in the policy buyback state check tranche token matches buy token NOTE: we're assuming that an order never gets closed until it is sold out Sold out = only <=dusk amount remaining (see market for dusk level) mark buyback as complete if all tranches have been bought back policy is now "closed" | function handleClosure(
uint256 _offerId,
uint256 /*_unsoldAmount*/,
uint256 /*_unboughtAmount*/,
bytes memory _data
) external override {
if (_data.length == 0) {
return;
}
if (t == MODT_TRANCHE_BUYBACK) {
(, address policy, uint256 trancheId) = abi.decode(_data, (uint256, address, uint256));
if (policy == address(this)) {
if (dataUint256["state"] == POLICY_STATE_BUYBACK) {
(, , , , address buyToken, , , , , ,) = _getMarket().getOffer(_offerId);
address trancheAddress = dataAddress[__i(trancheId, "address")];
require(trancheAddress == buyToken, "buy token must be tranche token");
dataBool[__i(trancheId, "buybackCompleted")] = true;
dataUint256["numTranchesBoughtBack"] += 1;
if (dataUint256["numTranchesBoughtBack"] == dataUint256["numTranches"]) {
_setPolicyState(POLICY_STATE_CLOSED);
}
}
}
}
}
| 7,313,174 |
pragma solidity ^0.4.24;
/**
* @summary: CryptoRome Land ERC-998 Bottom-Up Composable NFT Contract (and additional helper contracts)
* @author: GigLabs, LLC
*/
/**
* @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;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @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 */ {
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _tokenOwner, address indexed _approved, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _tokenOwner, address indexed _operator, bool _approved);
function balanceOf(address _tokenOwner) external view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) external view returns (address _tokenOwner);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external;
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 setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address _operator);
function isApprovedForAll(address _tokenOwner, address _operator) external view returns (bool);
}
/**
* @notice Query if a contract implements an interface
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
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);
}
/**
* @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 */ {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
/**
* @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 */ {
function totalSupply() external view returns (uint256);
function tokenByIndex(uint256 _index) external view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/**
* @title ERC998ERC721 Bottom-Up Composable Non-Fungible Token
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md
* Note: the ERC-165 identifier for this interface is 0xa1b23002
*/
interface ERC998ERC721BottomUp {
event TransferToParent(address indexed _toContract, uint256 indexed _toTokenId, uint256 _tokenId);
event TransferFromParent(address indexed _fromContract, uint256 indexed _fromTokenId, uint256 _tokenId);
function rootOwnerOf(uint256 _tokenId) public view returns (bytes32 rootOwner);
/**
* The tokenOwnerOf function gets the owner of the _tokenId which can be a user address or another ERC721 token.
* The tokenOwner address return value can be either a user address or an ERC721 contract address.
* If the tokenOwner address is a user address then parentTokenId will be 0 and should not be used or considered.
* If tokenOwner address is a user address then isParent is false, otherwise isChild is true, which means that
* tokenOwner is an ERC721 contract address and _tokenId is a child of tokenOwner and parentTokenId.
*/
function tokenOwnerOf(uint256 _tokenId) external view returns (bytes32 tokenOwner, uint256 parentTokenId, bool isParent);
// Transfers _tokenId as a child to _toContract and _toTokenId
function transferToParent(address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes _data) public;
// Transfers _tokenId from a parent ERC721 token to a user address.
function transferFromParent(address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId, bytes _data) public;
// Transfers _tokenId from a parent ERC721 token to a parent ERC721 token.
function transferAsChild(address _fromContract, uint256 _fromTokenId, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes _data) external;
}
/**
* @title ERC998ERC721 Bottom-Up Composable, optional enumerable extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md
* Note: The ERC-165 identifier for this interface is 0x8318b539
*/
interface ERC998ERC721BottomUpEnumerable {
function totalChildTokens(address _parentContract, uint256 _parentTokenId) external view returns (uint256);
function childTokenByIndex(address _parentContract, uint256 _parentTokenId, uint256 _index) external view returns (uint256);
}
contract ERC998ERC721BottomUpToken is ERC721, ERC721Metadata, ERC721Enumerable, ERC165, ERC998ERC721BottomUp, ERC998ERC721BottomUpEnumerable {
using SafeMath for uint256;
struct TokenOwner {
address tokenOwner;
uint256 parentTokenId;
}
// return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^
// this.tokenOwnerOf.selector ^ this.ownerOfChild.selector;
bytes32 constant ERC998_MAGIC_VALUE = 0xcd740db5;
// total number of tokens
uint256 internal tokenCount;
// tokenId => token owner
mapping(uint256 => TokenOwner) internal tokenIdToTokenOwner;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// root token owner address => (tokenId => approved address)
mapping(address => mapping(uint256 => address)) internal rootOwnerAndTokenIdToApprovedAddress;
// parent address => (parent tokenId => array of child tokenIds)
mapping(address => mapping(uint256 => uint256[])) internal parentToChildTokenIds;
// tokenId => position in childTokens array
mapping(uint256 => uint256) internal tokenIdToChildTokenIdsIndex;
// token owner => (operator address => bool)
mapping(address => mapping(address => bool)) internal tokenOwnerToOperators;
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Token URI
string internal tokenURIBase;
mapping(bytes4 => bool) internal supportedInterfaces;
//from zepellin ERC721Receiver.sol
//old version
bytes4 constant ERC721_RECEIVED = 0x150b7a02;
function isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly {size := extcodesize(_addr)}
return size > 0;
}
constructor () public {
//ERC165
supportedInterfaces[0x01ffc9a7] = true;
//ERC721
supportedInterfaces[0x80ac58cd] = true;
//ERC721Metadata
supportedInterfaces[0x5b5e139f] = true;
//ERC721Enumerable
supportedInterfaces[0x780e9d63] = true;
//ERC998ERC721BottomUp
supportedInterfaces[0xa1b23002] = true;
//ERC998ERC721BottomUpEnumerable
supportedInterfaces[0x8318b539] = true;
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC165Impl
//
/////////////////////////////////////////////////////////////////////////////
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return supportedInterfaces[_interfaceID];
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC721 implementation & ERC998 Authentication
//
/////////////////////////////////////////////////////////////////////////////
function balanceOf(address _tokenOwner) public view returns (uint256) {
require(_tokenOwner != address(0));
return ownedTokens[_tokenOwner].length;
}
// returns the immediate owner of the token
function ownerOf(uint256 _tokenId) public view returns (address) {
address tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(tokenOwner != address(0));
return tokenOwner;
}
function transferFrom(address _from, address _to, uint256 _tokenId) external {
require(_to != address(this));
_transferFromOwnerCheck(_from, _to, _tokenId);
_transferFrom(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external {
_transferFromOwnerCheck(_from, _to, _tokenId);
_transferFrom(_from, _to, _tokenId);
require(_checkAndCallSafeTransfer(_from, _to, _tokenId, ""));
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external {
_transferFromOwnerCheck(_from, _to, _tokenId);
_transferFrom(_from, _to, _tokenId);
require(_checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
function _checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal view returns (bool) {
if (!isContract(_to)) {
return true;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
function _transferFromOwnerCheck(address _from, address _to, uint256 _tokenId) internal {
require(_from != address(0));
require(_to != address(0));
require(tokenIdToTokenOwner[_tokenId].tokenOwner == _from);
require(tokenIdToTokenOwner[_tokenId].parentTokenId == 0);
// check child approved
address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId];
if(msg.sender != _from) {
bytes32 tokenOwner;
bool callSuccess;
// 0xeadb80b8 == ownerOfChild(address,uint256)
bytes memory calldata = abi.encodeWithSelector(0xed81cdda, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, _from, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
tokenOwner := mload(calldata)
}
}
if(callSuccess == true) {
require(tokenOwner >> 224 != ERC998_MAGIC_VALUE);
}
require(tokenOwnerToOperators[_from][msg.sender] || approvedAddress == msg.sender);
}
// clear approval
if (approvedAddress != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId];
emit Approval(_from, address(0), _tokenId);
}
}
function _transferFrom(address _from, address _to, uint256 _tokenId) internal {
// first remove the token from the owner list of owned tokens
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastTokenId = ownedTokens[_from][lastTokenIndex];
if (lastTokenId != _tokenId) {
// replace the _tokenId in the list of ownedTokens with the
// last token id in the list. Make sure ownedTokensIndex gets updated
// with the new position of the last token id as well.
uint256 tokenIndex = ownedTokensIndex[_tokenId];
ownedTokens[_from][tokenIndex] = lastTokenId;
ownedTokensIndex[lastTokenId] = tokenIndex;
}
// resize ownedTokens array (automatically deletes the last array entry)
ownedTokens[_from].length--;
// transfer token
tokenIdToTokenOwner[_tokenId].tokenOwner = _to;
// add token to the new owner's list of owned tokens
ownedTokensIndex[_tokenId] = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
emit Transfer(_from, _to, _tokenId);
}
function approve(address _approved, uint256 _tokenId) external {
address tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(tokenOwner != address(0));
address rootOwner = address(rootOwnerOf(_tokenId));
require(rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender]);
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved;
emit Approval(rootOwner, _approved, _tokenId);
}
function getApproved(uint256 _tokenId) public view returns (address) {
address rootOwner = address(rootOwnerOf(_tokenId));
return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
function setApprovalForAll(address _operator, bool _approved) external {
require(_operator != address(0));
tokenOwnerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
require(_owner != address(0));
require(_operator != address(0));
return tokenOwnerToOperators[_owner][_operator];
}
function _tokenOwnerOf(uint256 _tokenId) internal view returns (address tokenOwner, uint256 parentTokenId, bool isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(tokenOwner != address(0));
parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId;
if (parentTokenId > 0) {
isParent = true;
parentTokenId--;
}
else {
isParent = false;
}
return (tokenOwner, parentTokenId, isParent);
}
function tokenOwnerOf(uint256 _tokenId) external view returns (bytes32 tokenOwner, uint256 parentTokenId, bool isParent) {
address tokenOwnerAddress = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(tokenOwnerAddress != address(0));
parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId;
if (parentTokenId > 0) {
isParent = true;
parentTokenId--;
}
else {
isParent = false;
}
return (ERC998_MAGIC_VALUE << 224 | bytes32(tokenOwnerAddress), parentTokenId, isParent);
}
// Use Cases handled:
// Case 1: Token owner is this contract and no parent tokenId.
// Case 2: Token owner is this contract and token
// Case 3: Token owner is top-down composable
// Case 4: Token owner is an unknown contract
// Case 5: Token owner is a user
// Case 6: Token owner is a bottom-up composable
// Case 7: Token owner is ERC721 token owned by top-down token
// Case 8: Token owner is ERC721 token owned by unknown contract
// Case 9: Token owner is ERC721 token owned by user
function rootOwnerOf(uint256 _tokenId) public view returns (bytes32 rootOwner) {
address rootOwnerAddress = tokenIdToTokenOwner[_tokenId].tokenOwner;
require(rootOwnerAddress != address(0));
uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId;
bool isParent = parentTokenId > 0;
if (isParent) {
parentTokenId--;
}
if((rootOwnerAddress == address(this))) {
do {
if(isParent == false) {
// Case 1: Token owner is this contract and no token.
// This case should not happen.
return ERC998_MAGIC_VALUE << 224 | bytes32(rootOwnerAddress);
}
else {
// Case 2: Token owner is this contract and token
(rootOwnerAddress, parentTokenId, isParent) = _tokenOwnerOf(parentTokenId);
}
} while(rootOwnerAddress == address(this));
_tokenId = parentTokenId;
}
bytes memory calldata;
bool callSuccess;
if (isParent == false) {
// success if this token is owned by a top-down token
// 0xed81cdda == rootOwnerOfChild(address, uint256)
calldata = abi.encodeWithSelector(0xed81cdda, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
if(callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) {
// Case 3: Token owner is top-down composable
return rootOwner;
}
else {
// Case 4: Token owner is an unknown contract
// Or
// Case 5: Token owner is a user
return ERC998_MAGIC_VALUE << 224 | bytes32(rootOwnerAddress);
}
}
else {
// 0x43a61a8e == rootOwnerOf(uint256)
calldata = abi.encodeWithSelector(0x43a61a8e, parentTokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
if (callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) {
// Case 6: Token owner is a bottom-up composable
// Or
// Case 2: Token owner is top-down composable
return rootOwner;
}
else {
// token owner is ERC721
address childContract = rootOwnerAddress;
//0x6352211e == "ownerOf(uint256)"
calldata = abi.encodeWithSelector(0x6352211e, parentTokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwnerAddress := mload(calldata)
}
}
require(callSuccess);
// 0xed81cdda == rootOwnerOfChild(address,uint256)
calldata = abi.encodeWithSelector(0xed81cdda, childContract, parentTokenId);
assembly {
callSuccess := staticcall(gas, rootOwnerAddress, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
if(callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) {
// Case 7: Token owner is ERC721 token owned by top-down token
return rootOwner;
}
else {
// Case 8: Token owner is ERC721 token owned by unknown contract
// Or
// Case 9: Token owner is ERC721 token owned by user
return ERC998_MAGIC_VALUE << 224 | bytes32(rootOwnerAddress);
}
}
}
}
// List of all Land Tokens assigned to an address.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
return ownedTokens[_owner];
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC721MetadataImpl
//
/////////////////////////////////////////////////////////////////////////////
function tokenURI(uint256 _tokenId) external view returns (string) {
require (exists(_tokenId));
return _appendUintToString(tokenURIBase, _tokenId);
}
function name() external view returns (string) {
return name_;
}
function symbol() external view returns (string) {
return symbol_;
}
function _appendUintToString(string inStr, uint v) private pure 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);
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC721EnumerableImpl
//
/////////////////////////////////////////////////////////////////////////////
function exists(uint256 _tokenId) public view returns (bool) {
return _tokenId < tokenCount;
}
function totalSupply() external view returns (uint256) {
return tokenCount;
}
function tokenOfOwnerByIndex(address _tokenOwner, uint256 _index) external view returns (uint256 tokenId) {
require(_index < ownedTokens[_tokenOwner].length);
return ownedTokens[_tokenOwner][_index];
}
function tokenByIndex(uint256 _index) external view returns (uint256 tokenId) {
require(_index < tokenCount);
return _index;
}
function _mint(address _to, uint256 _tokenId) internal {
require (_to != address(0));
require (tokenIdToTokenOwner[_tokenId].tokenOwner == address(0));
tokenIdToTokenOwner[_tokenId].tokenOwner = _to;
ownedTokensIndex[_tokenId] = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
tokenCount++;
emit Transfer(address(0), _to, _tokenId);
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC998 Bottom-Up implementation (extenstion of ERC-721)
//
/////////////////////////////////////////////////////////////////////////////
function _removeChild(address _fromContract, uint256 _fromTokenId, uint256 _tokenId) internal {
uint256 lastChildTokenIndex = parentToChildTokenIds[_fromContract][_fromTokenId].length - 1;
uint256 lastChildTokenId = parentToChildTokenIds[_fromContract][_fromTokenId][lastChildTokenIndex];
if (_tokenId != lastChildTokenId) {
uint256 currentChildTokenIndex = tokenIdToChildTokenIdsIndex[_tokenId];
parentToChildTokenIds[_fromContract][_fromTokenId][currentChildTokenIndex] = lastChildTokenId;
tokenIdToChildTokenIdsIndex[lastChildTokenId] = currentChildTokenIndex;
}
parentToChildTokenIds[_fromContract][_fromTokenId].length--;
}
function _transferChild(address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId) internal {
tokenIdToTokenOwner[_tokenId].parentTokenId = _toTokenId.add(1);
uint256 index = parentToChildTokenIds[_toContract][_toTokenId].length;
parentToChildTokenIds[_toContract][_toTokenId].push(_tokenId);
tokenIdToChildTokenIdsIndex[_tokenId] = index;
_transferFrom(_from, _toContract, _tokenId);
require(ERC721(_toContract).ownerOf(_toTokenId) != address(0));
emit TransferToParent(_toContract, _toTokenId, _tokenId);
}
function _removeFromToken(address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId) internal {
require(_fromContract != address(0));
require(_to != address(0));
require(tokenIdToTokenOwner[_tokenId].tokenOwner == _fromContract);
uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId;
require(parentTokenId != 0);
require(parentTokenId - 1 == _fromTokenId);
// authenticate
address rootOwner = address(rootOwnerOf(_tokenId));
address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
require(rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || approvedAddress == msg.sender);
// clear approval
if (approvedAddress != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
emit Approval(rootOwner, address(0), _tokenId);
}
tokenIdToTokenOwner[_tokenId].parentTokenId = 0;
_removeChild(_fromContract, _fromTokenId, _tokenId);
emit TransferFromParent(_fromContract, _fromTokenId, _tokenId);
}
function transferFromParent(address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId, bytes _data) public {
_removeFromToken(_fromContract, _fromTokenId, _to, _tokenId);
delete tokenIdToChildTokenIdsIndex[_tokenId];
_transferFrom(_fromContract, _to, _tokenId);
require(_checkAndCallSafeTransfer(_fromContract, _to, _tokenId, _data));
}
function transferToParent(address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes _data) public {
_transferFromOwnerCheck(_from, _toContract, _tokenId);
_transferChild(_from, _toContract, _toTokenId, _tokenId);
}
function transferAsChild(address _fromContract, uint256 _fromTokenId, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes _data) external {
_removeFromToken(_fromContract, _fromTokenId, _toContract, _tokenId);
_transferChild(_fromContract, _toContract, _toTokenId, _tokenId);
}
/////////////////////////////////////////////////////////////////////////////
//
// ERC998 Bottom-Up Enumerable Implementation
//
/////////////////////////////////////////////////////////////////////////////
function totalChildTokens(address _parentContract, uint256 _parentTokenId) public view returns (uint256) {
return parentToChildTokenIds[_parentContract][_parentTokenId].length;
}
function childTokenByIndex(address _parentContract, uint256 _parentTokenId, uint256 _index) public view returns (uint256) {
require(parentToChildTokenIds[_parentContract][_parentTokenId].length > _index);
return parentToChildTokenIds[_parentContract][_parentTokenId][_index];
}
}
contract CryptoRomeControl {
// Emited when contract is upgraded or ownership changed
event ContractUpgrade(address newContract);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// Has control of (most) contract elements
address public ownerPrimary;
address public ownerSecondary;
// Address of owner wallet to transfer funds
address public ownerWallet;
address public cryptoRomeWallet;
// Contracts that need access for gameplay
// (state = 1 means access is active, state = 0 means disabled)
mapping(address => uint8) public otherOperators;
// Improvement contract is the only authorized address that can modify
// existing land data (ex. when player purchases a land improvement). No one else can
// modify land - even owners of this contract
address public improvementContract;
// Tracks if contract is paused or not. If paused, most actions are blocked
bool public paused = false;
constructor() public {
ownerPrimary = msg.sender;
ownerSecondary = msg.sender;
ownerWallet = msg.sender;
cryptoRomeWallet = msg.sender;
}
modifier onlyOwner() {
require (msg.sender == ownerPrimary || msg.sender == ownerSecondary);
_;
}
modifier anyOperator() {
require (
msg.sender == ownerPrimary ||
msg.sender == ownerSecondary ||
otherOperators[msg.sender] == 1
);
_;
}
modifier onlyOtherOperators() {
require (otherOperators[msg.sender] == 1);
_;
}
modifier onlyImprovementContract() {
require (msg.sender == improvementContract);
_;
}
function setPrimaryOwner(address _newOwner) external onlyOwner {
require (_newOwner != address(0));
emit OwnershipTransferred(ownerPrimary, _newOwner);
ownerPrimary = _newOwner;
}
function setSecondaryOwner(address _newOwner) external onlyOwner {
require (_newOwner != address(0));
emit OwnershipTransferred(ownerSecondary, _newOwner);
ownerSecondary = _newOwner;
}
function setOtherOperator(address _newOperator, uint8 _state) external onlyOwner {
require (_newOperator != address(0));
otherOperators[_newOperator] = _state;
}
function setImprovementContract(address _improvementContract) external onlyOwner {
require (_improvementContract != address(0));
emit OwnershipTransferred(improvementContract, _improvementContract);
improvementContract = _improvementContract;
}
function transferOwnerWalletOwnership(address newWalletAddress) onlyOwner external {
require(newWalletAddress != address(0));
ownerWallet = newWalletAddress;
}
function transferCryptoRomeWalletOwnership(address newWalletAddress) onlyOwner external {
require(newWalletAddress != address(0));
cryptoRomeWallet = newWalletAddress;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
}
function unpause() public onlyOwner whenPaused {
paused = false;
}
function withdrawBalance() public onlyOwner {
ownerWallet.transfer(address(this).balance);
}
}
contract CryptoRomeLandComposableNFT is ERC998ERC721BottomUpToken, CryptoRomeControl {
using SafeMath for uint256;
// Set in case the contract needs to be updated
address public newContractAddress;
struct LandInfo {
uint256 landType; // 0-4 unit, plot, village, town, city (unit unused)
uint256 landImprovements;
uint256 askingPrice;
}
mapping(uint256 => LandInfo) internal tokenIdToLand;
// for sale state of all tokens. tokens map to bits. 0 = not for sale; 1 = for sale
// 256 token states per index of this array
uint256[] internal allLandForSaleState;
// landType => land count
mapping(uint256 => uint256) internal landTypeToCount;
// total number of villages in existence is 50000 (no more can be created)
uint256 constant internal MAX_VILLAGES = 50000;
constructor () public {
paused = true;
name_ = "CryptoRome-Land-NFT";
symbol_ = "CRLAND";
}
function isCryptoRomeLandComposableNFT() external pure returns (bool) {
return true;
}
function getLandTypeCount(uint256 _landType) public view returns (uint256) {
return landTypeToCount[_landType];
}
function setTokenURI(string _tokenURI) external anyOperator {
tokenURIBase = _tokenURI;
}
function setNewAddress(address _v2Address) external onlyOwner {
require (_v2Address != address(0));
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/////////////////////////////////////////////////////////////////////////////
// Get Land
// Token Owner: Address of the token owner
// Parent Token Id: If parentTokenId is > 0, then this land
// token is owned by another token (i.e. it is attached bottom-up).
// parentTokenId is the id of the owner token, and tokenOwner
// address (the first parameter) is the ERC721 contract address of the
// parent token. If parentTokenId == 0, then this land token is owned
// by a user address.
// Land Types: village=1, town=2, city=3
// Land Improvements: improvements and upgrades
// to each land NFT are coded into a single uint256 value
// Asking Price (in wei): 0 if land is not for sale
/////////////////////////////////////////////////////////////////////////////
function getLand(uint256 _tokenId) external view
returns (
address tokenOwner,
uint256 parentTokenId,
uint256 landType,
uint256 landImprovements,
uint256 askingPrice
) {
TokenOwner storage owner = tokenIdToTokenOwner[_tokenId];
LandInfo storage land = tokenIdToLand[_tokenId];
parentTokenId = owner.parentTokenId;
if (parentTokenId > 0) {
parentTokenId--;
}
tokenOwner = owner.tokenOwner;
parentTokenId = owner.parentTokenId;
landType = land.landType;
landImprovements = land.landImprovements;
askingPrice = land.askingPrice;
}
/////////////////////////////////////////////////////////////////////////////
// Create Land NFT
// Land Types: village=1, town=2, city=3
// Land Improvements: improvements and upgrades
// to each land NFT are the coded into a uint256 value
/////////////////////////////////////////////////////////////////////////////
function _createLand (address _tokenOwner, uint256 _landType, uint256 _landImprovements) internal returns (uint256 tokenId) {
require(_tokenOwner != address(0));
require(landTypeToCount[1] < MAX_VILLAGES);
tokenId = tokenCount;
LandInfo memory land = LandInfo({
landType: _landType, // 1-3 village, town, city
landImprovements: _landImprovements,
askingPrice: 0
});
// map new tokenId to the newly created land
tokenIdToLand[tokenId] = land;
landTypeToCount[_landType]++;
if (tokenId % 256 == 0) {
// create new land sale state entry in storage
allLandForSaleState.push(0);
}
_mint(_tokenOwner, tokenId);
return tokenId;
}
function createLand (address _tokenOwner, uint256 _landType, uint256 _landImprovements) external anyOperator whenNotPaused returns (uint256 tokenId) {
return _createLand (_tokenOwner, _landType, _landImprovements);
}
////////////////////////////////////////////////////////////////////////////////
// Land Improvement Data
// This uint256 land "dna" value describes all improvements and upgrades
// to a piece of land. After land token distribution, only the Improvement
// Contract can ever update or modify the land improvement data of a piece
// of land (contract owner cannot modify land).
//
// For villages, improvementData is a uint256 value containing village
// improvement data with the following slot bit mapping
// 0-31: slot 1 improvement info
// 32-63: slot 2 improvement info
// 64-95: slot 3 improvement info
// 96-127: slot 4 improvement info
// 128-159: slot 5 improvement info
// 160-191: slot 6 improvement info
// 192-255: reserved for additional land information
//
// Each 32 bit slot in the above structure has the following bit mapping
// 0-7: improvement type (index to global list of possible types)
// 8-14: upgrade type 1 - level 0-99 (0 for no upgrade present)
// 15-21: upgrade type 2 - level 0-99 (0 for no upgrade present)
// 22: upgrade type 3 - 1 if upgrade present, 0 if not (no leveling)
////////////////////////////////////////////////////////////////////////////////
function getLandImprovementData(uint256 _tokenId) external view returns (uint256) {
return tokenIdToLand[_tokenId].landImprovements;
}
function updateLandImprovementData(uint256 _tokenId, uint256 _newLandImprovementData) external whenNotPaused onlyImprovementContract {
require(_tokenId <= tokenCount);
tokenIdToLand[_tokenId].landImprovements = _newLandImprovementData;
}
/////////////////////////////////////////////////////////////////////////////
// Land Compose/Decompose functions
// Towns are composed of 3 Villages
// Cities are composed of 3 Towns
/////////////////////////////////////////////////////////////////////////////
// Attach three child land tokens onto a parent land token (ex. 3 villages onto a town).
// This function is called when the parent does not exist yet, so create parent land token first
// Ownership of the child lands transfers from the existing owner (sender) to the parent land token
function composeNewLand(uint256 _landType, uint256 _childLand1, uint256 _childLand2, uint256 _childLand3) external whenNotPaused returns(uint256) {
uint256 parentTokenId = _createLand(msg.sender, _landType, 0);
return composeLand(parentTokenId, _childLand1, _childLand2, _childLand3);
}
// Attach three child land tokens onto a parent land token (ex. 3 villages into a town).
// All three children and an existing parent need to be passed into this function.
// Ownership of the child lands transfers from the existing owner (sender) to the parent land token
function composeLand(uint256 _parentLandId, uint256 _childLand1, uint256 _childLand2, uint256 _childLand3) public whenNotPaused returns(uint256) {
require (tokenIdToLand[_parentLandId].landType == 2 || tokenIdToLand[_parentLandId].landType == 3);
uint256 validChildLandType = tokenIdToLand[_parentLandId].landType.sub(1);
require(tokenIdToLand[_childLand1].landType == validChildLandType &&
tokenIdToLand[_childLand2].landType == validChildLandType &&
tokenIdToLand[_childLand3].landType == validChildLandType);
// transfer ownership of child land tokens to parent land token
transferToParent(tokenIdToTokenOwner[_childLand1].tokenOwner, address(this), _parentLandId, _childLand1, "");
transferToParent(tokenIdToTokenOwner[_childLand2].tokenOwner, address(this), _parentLandId, _childLand2, "");
transferToParent(tokenIdToTokenOwner[_childLand3].tokenOwner, address(this), _parentLandId, _childLand3, "");
// if this contract is owner of the parent land token, transfer ownership to msg.sender
if (tokenIdToTokenOwner[_parentLandId].tokenOwner == address(this)) {
_transferFrom(address(this), msg.sender, _parentLandId);
}
return _parentLandId;
}
// Decompose a parent land back to it's attached child land token components (ex. a town into 3 villages).
// The existing owner of the parent land becomes the owner of the three child tokens
// This contract takes over ownership of the parent land token (for later reuse)
// Loop to remove and transfer all land tokens in case other land tokens are attached.
function decomposeLand(uint256 _tokenId) external whenNotPaused {
uint256 numChildren = totalChildTokens(address(this), _tokenId);
require (numChildren > 0);
// it is lower gas cost to remove children starting from the end of the array
for (uint256 numChild = numChildren; numChild > 0; numChild--) {
uint256 childTokenId = childTokenByIndex(address(this), _tokenId, numChild-1);
// transfer ownership of underlying lands to msg.sender
transferFromParent(address(this), _tokenId, msg.sender, childTokenId, "");
}
// transfer ownership of parent land back to this contract owner for reuse
_transferFrom(msg.sender, address(this), _tokenId);
}
/////////////////////////////////////////////////////////////////////////////
// Sale functions
/////////////////////////////////////////////////////////////////////////////
function _updateSaleData(uint256 _tokenId, uint256 _askingPrice) internal {
tokenIdToLand[_tokenId].askingPrice = _askingPrice;
if (_askingPrice > 0) {
// Item is for sale - set bit
allLandForSaleState[_tokenId.div(256)] = allLandForSaleState[_tokenId.div(256)] | (1 << (_tokenId % 256));
} else {
// Item is no longer for sale - clear bit
allLandForSaleState[_tokenId.div(256)] = allLandForSaleState[_tokenId.div(256)] & ~(1 << (_tokenId % 256));
}
}
function sellLand(uint256 _tokenId, uint256 _askingPrice) public whenNotPaused {
require(tokenIdToTokenOwner[_tokenId].tokenOwner == msg.sender);
require(tokenIdToTokenOwner[_tokenId].parentTokenId == 0);
require(_askingPrice > 0);
// Put the land token on the market
_updateSaleData(_tokenId, _askingPrice);
}
function cancelLandSale(uint256 _tokenId) public whenNotPaused {
require(tokenIdToTokenOwner[_tokenId].tokenOwner == msg.sender);
// Take the land token off the market
_updateSaleData(_tokenId, 0);
}
function purchaseLand(uint256 _tokenId) public whenNotPaused payable {
uint256 price = tokenIdToLand[_tokenId].askingPrice;
require(price <= msg.value);
// Take the land token off the market
_updateSaleData(_tokenId, 0);
// Marketplace fee
uint256 marketFee = computeFee(price);
uint256 sellerProceeds = msg.value.sub(marketFee);
cryptoRomeWallet.transfer(marketFee);
// Return excess payment to sender
uint256 excessPayment = msg.value.sub(price);
msg.sender.transfer(excessPayment);
// Transfer proceeds to seller. Sale was removed above before this transfer()
// to guard against reentrancy attacks
tokenIdToTokenOwner[_tokenId].tokenOwner.transfer(sellerProceeds);
// Transfer token to buyer
_transferFrom(tokenIdToTokenOwner[_tokenId].tokenOwner, msg.sender, _tokenId);
}
function getAllForSaleStatus() external view returns(uint256[]) {
// return uint256[] bitmap values up to max tokenId (for ease of querying from UI for marketplace)
// index 0 of the uint256 holds first 256 land token status; index 1 is next 256 land tokens, etc
// value of 1 = For Sale; 0 = Not for Sale
return allLandForSaleState;
}
function computeFee(uint256 amount) internal pure returns(uint256) {
// 3% marketplace fee, most of which will be distributed to the Caesar and Senators of CryptoRome
return amount.mul(3).div(100);
}
}
contract CryptoRomeLandDistribution is CryptoRomeControl {
using SafeMath for uint256;
// Set in case the contract needs to be updated
address public newContractAddress;
CryptoRomeLandComposableNFT public cryptoRomeLandNFTContract;
ImprovementGeneration public improvementGenContract;
uint256 public villageInventoryPrice;
uint256 public numImprovementsPerVillage;
uint256 constant public LOWEST_VILLAGE_INVENTORY_PRICE = 100000000000000000; // 0.1 ETH
constructor (address _cryptoRomeLandNFTContractAddress, address _improvementGenContractAddress) public {
require (_cryptoRomeLandNFTContractAddress != address(0));
require (_improvementGenContractAddress != address(0));
paused = true;
cryptoRomeLandNFTContract = CryptoRomeLandComposableNFT(_cryptoRomeLandNFTContractAddress);
improvementGenContract = ImprovementGeneration(_improvementGenContractAddress);
villageInventoryPrice = LOWEST_VILLAGE_INVENTORY_PRICE;
numImprovementsPerVillage = 3;
}
function setNewAddress(address _v2Address) external onlyOwner {
require (_v2Address != address(0));
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
function setCryptoRomeLandNFTContract(address _cryptoRomeLandNFTContract) external onlyOwner {
require (_cryptoRomeLandNFTContract != address(0));
cryptoRomeLandNFTContract = CryptoRomeLandComposableNFT(_cryptoRomeLandNFTContract);
}
function setImprovementGenContract(address _improvementGenContractAddress) external onlyOwner {
require (_improvementGenContractAddress != address(0));
improvementGenContract = ImprovementGeneration(_improvementGenContractAddress);
}
function setVillageInventoryPrice(uint256 _price) external onlyOwner {
require(_price >= LOWEST_VILLAGE_INVENTORY_PRICE);
villageInventoryPrice = _price;
}
function setNumImprovementsPerVillage(uint256 _numImprovements) external onlyOwner {
require(_numImprovements <= 6);
numImprovementsPerVillage = _numImprovements;
}
function purchaseFromVillageInventory(uint256 _num) external whenNotPaused payable {
uint256 price = villageInventoryPrice.mul(_num);
require (msg.value >= price);
require (_num > 0 && _num <= 50);
// Marketplace fee
uint256 marketFee = computeFee(price);
cryptoRomeWallet.transfer(marketFee);
// Return excess payment to sender
uint256 excessPayment = msg.value.sub(price);
msg.sender.transfer(excessPayment);
for (uint256 i = 0; i < _num; i++) {
// create a new village w/ random improvements and transfer the NFT to caller
_createVillageWithImprovementsFromInv(msg.sender);
}
}
function computeFee(uint256 amount) internal pure returns(uint256) {
// 3% marketplace fee, most of which will be distributed to the Caesar and Senators of CryptoRome
return amount.mul(3).div(100);
}
function batchIssueLand(address _toAddress, uint256[] _landType) external onlyOwner {
require (_toAddress != address(0));
require (_landType.length > 0);
for (uint256 i = 0; i < _landType.length; i++) {
issueLand(_toAddress, _landType[i]);
}
}
function batchIssueVillages(address _toAddress, uint256 _num) external onlyOwner {
require (_toAddress != address(0));
require (_num > 0);
for (uint256 i = 0; i < _num; i++) {
_createVillageWithImprovements(_toAddress);
}
}
function issueLand(address _toAddress, uint256 _landType) public onlyOwner returns (uint256) {
require (_toAddress != address(0));
return _createLandWithImprovements(_toAddress, _landType);
}
function batchCreateLand(uint256[] _landType) external onlyOwner {
require (_landType.length > 0);
for (uint256 i = 0; i < _landType.length; i++) {
// land created is owned by this contract for staging purposes
// (must later use transferTo or batchTransferTo)
_createLandWithImprovements(address(this), _landType[i]);
}
}
function batchCreateVillages(uint256 _num) external onlyOwner {
require (_num > 0);
for (uint256 i = 0; i < _num; i++) {
// land created is owned by this contract for staging purposes
// (must later use transferTo or batchTransferTo)
_createVillageWithImprovements(address(this));
}
}
function createLand(uint256 _landType) external onlyOwner {
// land created is owned by this contract for staging purposes
// (must later use transferTo or batchTransferTo)
_createLandWithImprovements(address(this), _landType);
}
function batchTransferTo(uint256[] _tokenIds, address _to) external onlyOwner {
require (_tokenIds.length > 0);
require (_to != address(0));
for (uint256 i = 0; i < _tokenIds.length; ++i) {
// transfers staged land out of this contract to the owners
cryptoRomeLandNFTContract.transferFrom(address(this), _to, _tokenIds[i]);
}
}
function transferTo(uint256 _tokenId, address _to) external onlyOwner {
require (_to != address(0));
// transfers staged land out of this contract to the owners
cryptoRomeLandNFTContract.transferFrom(address(this), _to, _tokenId);
}
function issueVillageWithImprovementsForPromo(address _toAddress, uint256 numImprovements) external onlyOwner returns (uint256) {
uint256 landImprovements = improvementGenContract.genInitialResourcesForVillage(numImprovements, false);
return cryptoRomeLandNFTContract.createLand(_toAddress, 1, landImprovements);
}
function _createVillageWithImprovementsFromInv(address _toAddress) internal returns (uint256) {
uint256 landImprovements = improvementGenContract.genInitialResourcesForVillage(numImprovementsPerVillage, true);
return cryptoRomeLandNFTContract.createLand(_toAddress, 1, landImprovements);
}
function _createVillageWithImprovements(address _toAddress) internal returns (uint256) {
uint256 landImprovements = improvementGenContract.genInitialResourcesForVillage(3, false);
return cryptoRomeLandNFTContract.createLand(_toAddress, 1, landImprovements);
}
function _createLandWithImprovements(address _toAddress, uint256 _landType) internal returns (uint256) {
require (_landType > 0 && _landType < 4);
if (_landType == 1) {
return _createVillageWithImprovements(_toAddress);
} else if (_landType == 2) {
uint256 village1TokenId = _createLandWithImprovements(address(this), 1);
uint256 village2TokenId = _createLandWithImprovements(address(this), 1);
uint256 village3TokenId = _createLandWithImprovements(address(this), 1);
uint256 townTokenId = cryptoRomeLandNFTContract.createLand(_toAddress, 2, 0);
cryptoRomeLandNFTContract.composeLand(townTokenId, village1TokenId, village2TokenId, village3TokenId);
return townTokenId;
} else if (_landType == 3) {
uint256 town1TokenId = _createLandWithImprovements(address(this), 2);
uint256 town2TokenId = _createLandWithImprovements(address(this), 2);
uint256 town3TokenId = _createLandWithImprovements(address(this), 2);
uint256 cityTokenId = cryptoRomeLandNFTContract.createLand(_toAddress, 3, 0);
cryptoRomeLandNFTContract.composeLand(cityTokenId, town1TokenId, town2TokenId, town3TokenId);
return cityTokenId;
}
}
}
interface RandomNumGeneration {
function getRandomNumber(uint256 seed) external returns (uint256);
}
contract ImprovementGeneration is CryptoRomeControl {
using SafeMath for uint256;
// Set in case the contract needs to be updated
address public newContractAddress;
RandomNumGeneration public randomNumberSource;
uint256 public rarityValueMax;
uint256 public latestPseudoRandomNumber;
uint8 public numResourceImprovements;
mapping(uint8 => uint256) private improvementIndexToRarityValue;
constructor () public {
// Starting Improvements
// improvement => rarity value (lower number = higher rarity)
improvementIndexToRarityValue[1] = 256; // Wheat
improvementIndexToRarityValue[2] = 256; // Wood
improvementIndexToRarityValue[3] = 128; // Grapes
improvementIndexToRarityValue[4] = 128; // Stone
improvementIndexToRarityValue[5] = 64; // Clay
improvementIndexToRarityValue[6] = 64; // Fish
improvementIndexToRarityValue[7] = 32; // Horse
improvementIndexToRarityValue[8] = 16; // Iron
improvementIndexToRarityValue[9] = 8; // Marble
// etc --> More can be added in the future
// max resource improvement types is 63
numResourceImprovements = 9;
rarityValueMax = 952;
}
function setNewAddress(address _v2Address) external onlyOwner {
require (_v2Address != address(0));
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
function setRandomNumGenerationContract(address _randomNumberGenAddress) external onlyOwner {
require (_randomNumberGenAddress != address(0));
randomNumberSource = RandomNumGeneration(_randomNumberGenAddress);
}
function genInitialResourcesForVillage(uint256 numImprovements, bool useRandomInput) external anyOperator returns(uint256) {
require(numImprovements <= 6);
uint256 landImprovements;
// each improvement takes up one village slot (max 6 slots)
for (uint256 i = 0; i < numImprovements; i++) {
uint8 newImprovement = generateImprovement(useRandomInput);
// each slot is a 32 bit section in the 256 bit landImprovement value
landImprovements |= uint256(newImprovement) << (32*i);
}
return landImprovements;
}
function generateImprovement(bool useRandomSource) public anyOperator returns (uint8 newImprovement) {
// seed does not need to be anything super fancy for initial improvement generation for villages...
// players will not be performing that operation, so this should be random enough
uint256 seed = latestPseudoRandomNumber.add(now);
if (useRandomSource) {
// for cases where players are generating land (i.e. after initial distribution of villages), there
// will need to be a better source of randomness
seed = randomNumberSource.getRandomNumber(seed);
}
latestPseudoRandomNumber = addmod(uint256(blockhash(block.number-1)), seed, rarityValueMax);
// do lookup for the improvement
newImprovement = lookupImprovementTypeByRarity(latestPseudoRandomNumber);
}
function lookupImprovementTypeByRarity(uint256 rarityNum) public view returns (uint8 improvementType) {
uint256 rarityIndexValue;
for (uint8 i = 1; i <= numResourceImprovements; i++) {
rarityIndexValue += improvementIndexToRarityValue[i];
if (rarityNum < rarityIndexValue) {
return i;
}
}
return 0;
}
function addNewResourceImprovementType(uint256 rarityValue) external onlyOwner {
require(rarityValue > 0);
require(numResourceImprovements < 63);
numResourceImprovements++;
rarityValueMax += rarityValue;
improvementIndexToRarityValue[numResourceImprovements] = rarityValue;
}
function updateImprovementRarityValue(uint256 rarityValue, uint8 improvementIndex) external onlyOwner {
require(rarityValue > 0);
require(improvementIndex <= numResourceImprovements);
rarityValueMax -= improvementIndexToRarityValue[improvementIndex];
rarityValueMax += rarityValue;
improvementIndexToRarityValue[improvementIndex] = rarityValue;
}
} | Attach three child land tokens onto a parent land token (ex. 3 villages onto a town). This function is called when the parent does not exist yet, so create parent land token first Ownership of the child lands transfers from the existing owner (sender) to the parent land token | function composeNewLand(uint256 _landType, uint256 _childLand1, uint256 _childLand2, uint256 _childLand3) external whenNotPaused returns(uint256) {
uint256 parentTokenId = _createLand(msg.sender, _landType, 0);
return composeLand(parentTokenId, _childLand1, _childLand2, _childLand3);
}
| 1,090,726 |
./full_match/4/0x7026EC198e26724e73198fc8B6B4d054a561e3d4/sources/WarApes_-_Working_Safe_Math.sol | GET ALL BANANAS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH Return an empty array | function warApeNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new string[](0);
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = warApeNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
| 13,294,608 |
pragma solidity ^0.4.18;
/**
* @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;
}
}
contract ForeignToken {
function balanceOf(address owner) constant public returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title 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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* TorusCoin pre-sell contract.
*
*/
contract TorusCoin is StandardToken {
using SafeMath for uint256;
string public name = "Torus";
string public symbol = "TORUS";
uint256 public decimals = 18;
uint256 public startDatetime;
uint256 public endDatetime;
// Initial founder address (set in constructor)
// All deposited ETH will be instantly forwarded to this address.
address public founder;
// administrator address
address public admin;
uint256 public coinAllocation = 700 * 10**8 * 10**decimals; //70000M tokens supply for pre-sell
uint256 public founderAllocation = 300 * 10**8 * 10**decimals; //30000M of token supply allocated for the team allocation
bool public founderAllocated = false; //this will change to true when the founder fund is allocated
uint256 public saleTokenSupply = 0; //this will keep track of the token supply created during the pre-sell
uint256 public salesVolume = 0; //this will keep track of the Ether raised during the pre-sell
bool public halted = false; //the admin address can set this to true to halt the pre-sell due to emergency
event Buy(address sender, address recipient, uint256 eth, uint256 tokens);
event AllocateFounderTokens(address sender, address founder, uint256 tokens);
event AllocateInflatedTokens(address sender, address holder, uint256 tokens);
modifier onlyAdmin {
require(msg.sender == admin);
_;
}
modifier duringCrowdSale {
require(block.timestamp >= startDatetime && block.timestamp < endDatetime);
_;
}
/**
*
* Integer value representing the number of seconds since 1 January 1970 00:00:00 UTC
*/
function TorusCoin(uint256 startDatetimeInSeconds, address founderWallet) public {
admin = msg.sender;
founder = founderWallet;
startDatetime = startDatetimeInSeconds;
endDatetime = startDatetime + 16 * 1 days;
}
/**
* allow anyone sends funds to the contract
*/
function() public payable {
buy(msg.sender);
}
/**
* Main token buy function.
* Buy for the sender itself or buy on the behalf of somebody else (third party address).
*/
function buy(address recipient) payable public duringCrowdSale {
require(!halted);
require(msg.value >= 0.01 ether);
uint256 tokens = msg.value.mul(35e4);
require(tokens > 0);
require(saleTokenSupply.add(tokens)<=coinAllocation );
balances[recipient] = balances[recipient].add(tokens);
totalSupply_ = totalSupply_.add(tokens);
saleTokenSupply = saleTokenSupply.add(tokens);
salesVolume = salesVolume.add(msg.value);
if (!founder.call.value(msg.value)()) revert(); //immediately send Ether to founder address
Buy(msg.sender, recipient, msg.value, tokens);
}
/**
* Set up founder address token balance.
*/
function allocateFounderTokens() public onlyAdmin {
require( block.timestamp > endDatetime );
require(!founderAllocated);
balances[founder] = balances[founder].add(founderAllocation);
totalSupply_ = totalSupply_.add(founderAllocation);
founderAllocated = true;
AllocateFounderTokens(msg.sender, founder, founderAllocation);
}
/**
* Emergency Stop crowdsale.
*/
function halt() public onlyAdmin {
halted = true;
}
function unhalt() public onlyAdmin {
halted = false;
}
/**
* Change admin address.
*/
function changeAdmin(address newAdmin) public onlyAdmin {
admin = newAdmin;
}
/**
* Change founder address.
*/
function changeFounder(address newFounder) public onlyAdmin {
founder = newFounder;
}
/**
* Inflation
*/
function inflate(address holder, uint256 tokens) public onlyAdmin {
require( block.timestamp > endDatetime );
require(saleTokenSupply.add(tokens) <= coinAllocation );
balances[holder] = balances[holder].add(tokens);
saleTokenSupply = saleTokenSupply.add(tokens);
totalSupply_ = totalSupply_.add(tokens);
AllocateInflatedTokens(msg.sender, holder, tokens);
}
/**
* withdraw foreign tokens
*/
function withdrawForeignTokens(address tokenContract) onlyAdmin public returns (bool) {
ForeignToken token = ForeignToken(tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(admin, amount);
}
} | allow anyone sends funds to the contract/ | function() public payable {
buy(msg.sender);
}
| 1,132,025 |
pragma solidity 0.8.6;
import "./IBondingCurve.sol";
contract BuySell {
constructor(
IErc20BondingCurve _usdc20BondingCurve,
IETHBondingCurve _ethBondingCurve
) {
usdc20BondingCurve = _usdc20BondingCurve;
ethBondingCurve = _ethBondingCurve;
}
IErc20BondingCurve usdc20BondingCurve;
IETHBondingCurve ethBondingCurve;
function buysellInOneTxnETH(uint256 tokenAmount) public payable {
ethBondingCurve.buy{value: msg.value}(tokenAmount);
ethBondingCurve.sell(tokenAmount);
}
function buysellInOneTxnUSDC(uint256 tokenAmount) public {
usdc20BondingCurve.buy(tokenAmount);
usdc20BondingCurve.sell(tokenAmount);
}
}
pragma solidity 0.8.6;
interface IETHBondingCurve {
function buy(uint256 tokenAmount) external payable;
function sell(uint256 tokenAmount) external;
}
interface IErc20BondingCurve {
function buy(uint256 tokenAmount) external;
function sell(uint256 tokenAmount) external;
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
*/
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Linear.sol";
import "./IBondingCurve.sol";
contract ETHBondingCurve is LinearBondingCurve, IETHBondingCurve {
using SafeERC20 for IERC20;
IERC20 public immutable token;
uint256 public soldAmount;
uint256 public comissionShare = 20;
address payable public hegicDevelopmentFund;
event Bought(address indexed account, uint256 amount, uint256 ethAmount);
event Sold(
address indexed account,
uint256 amount,
uint256 ethAmount,
uint256 comission
);
constructor(
IERC20 _token,
uint256 k,
uint256 startPrice
) LinearBondingCurve(k, startPrice) {
token = _token;
hegicDevelopmentFund = payable(msg.sender);
_setupRole(LBC_ADMIN_ROLE, msg.sender);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function buy(uint256 tokenAmount) external payable override {
uint256 nextSold = soldAmount + tokenAmount;
uint256 ethAmount = s(soldAmount, nextSold);
soldAmount = nextSold;
require(msg.value >= ethAmount, "Value is too small");
token.safeTransfer(msg.sender, tokenAmount);
if (msg.value > ethAmount)
payable(msg.sender).transfer(msg.value - ethAmount);
emit Bought(msg.sender, tokenAmount, ethAmount);
}
function sell(uint256 tokenAmount) external override {
uint256 nextSold = soldAmount - tokenAmount;
uint256 ethAmount = s(nextSold, soldAmount);
uint256 comission = (ethAmount * comissionShare) / 100;
uint256 refund = ethAmount - comission;
require(comission > 0, "Amount is too small");
soldAmount = nextSold;
token.safeTransferFrom(msg.sender, address(this), tokenAmount);
hegicDevelopmentFund.transfer(comission);
payable(msg.sender).transfer(refund);
emit Sold(msg.sender, tokenAmount, refund, comission);
}
function setHDF(address payable value)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
hegicDevelopmentFund = value;
}
function setCommissionShare(uint256 value)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
comissionShare = value;
}
function destruct() external onlyRole(DEFAULT_ADMIN_ROLE) {
selfdestruct(hegicDevelopmentFund);
}
function withdawERC20(IERC20 token) external onlyRole(DEFAULT_ADMIN_ROLE) {
token.transfer(hegicDevelopmentFund, token.balanceOf(address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2020 Hegic Protocol
*
* 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/>.
*/
import "@openzeppelin/contracts/access/AccessControl.sol";
contract LinearBondingCurve is AccessControl {
uint256 public K; // Inf
uint256 public START_PRICE; // 0.000018e8
bytes32 public constant LBC_ADMIN_ROLE = keccak256("LBC_ADMIN_ROLE");
constructor(uint256 k, uint256 startPrice) public {
K = k;
START_PRICE = startPrice;
}
function s(uint256 x0, uint256 x1) public view returns (uint256) {
require(x1 > x0, "Hegic Amount need higher then 0");
return
(((x1 + x0) * (x1 - x0)) / 2 / K + START_PRICE * (x1 - x0)) / 1e18;
}
function setParams(uint256 _K, uint256 _START_PRICE)
external
onlyRole(LBC_ADMIN_ROLE)
{
K = _K;
START_PRICE = _START_PRICE;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "../Interfaces/Interfaces.sol";
import "../Interfaces/IOptionsManager.sol";
import "../Interfaces/Interfaces.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Main Pool Contract
* @notice One of the main contracts that manages the pools and the options parameters,
* accumulates the funds from the liquidity providers and makes the withdrawals for them,
* sells the options contracts to the options buyers and collateralizes them,
* exercises the ITM (in-the-money) options with the unrealized P&L and settles them,
* unlocks the expired options and distributes the premiums among the liquidity providers.
**/
abstract contract HegicPool is
IHegicPool,
ERC721,
AccessControl,
ReentrancyGuard
{
using SafeERC20 for IERC20;
bytes32 public constant SELLER_ROLE = keccak256("SELLER_ROLE");
uint256 public constant INITIAL_RATE = 1e20;
IOptionsManager public immutable optionsManager;
AggregatorV3Interface public immutable priceProvider;
IPriceCalculator public override pricer;
uint256 public lockupPeriod = 30 days;
uint256 public maxUtilizationRate = 100;
uint256 public override collateralizationRatio = 20;
uint256 public override lockedAmount;
uint256 public maxDepositAmount = type(uint256).max;
uint256 public totalShare = 0;
uint256 public override totalBalance = 0;
ISettlementFeeRecipient public settlementFeeRecipient;
Tranche[] public override tranches;
mapping(uint256 => Option) public override options;
IERC20 public override token;
constructor(
IERC20 _token,
string memory name,
string memory symbol,
IOptionsManager manager,
IPriceCalculator _pricer,
ISettlementFeeRecipient _settlementFeeRecipient,
AggregatorV3Interface _priceProvider
) ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
priceProvider = _priceProvider;
settlementFeeRecipient = _settlementFeeRecipient;
pricer = _pricer;
token = _token;
optionsManager = manager;
}
/**
* @notice Used for setting the liquidity lock-up periods during which
* the liquidity providers who deposited the funds into the pools contracts
* won't be able to withdraw them. Note that different lock-ups could
* be set for the hedged and unhedged — classic — liquidity tranches.
* @param value Liquidity tranches lock-up in seconds
**/
function setLockupPeriod(uint256 value)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(value <= 60 days, "The lockup period is too long");
lockupPeriod = value;
}
/**
* @notice Used for setting the total maximum amount
* that could be deposited into the pools contracts.
* Note that different total maximum amounts could be set
* for the hedged and unhedged — classic — liquidity tranches.
* @param total Maximum amount of assets in the pool
* in hedged and unhedged (classic) liquidity tranches combined
**/
function setMaxDepositAmount(uint256 total)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
maxDepositAmount = total;
}
/**
* @notice Used for setting the maximum share of the pool
* size that could be utilized as a collateral in the options.
*
* Example: if `MaxUtilizationRate` = 50, then only 50%
* of liquidity on the pools contracts would be used for
* collateralizing options while 50% will be sitting idle
* available for withdrawals by the liquidity providers.
* @param value The utilization ratio in a range of 50% — 100%
**/
function setMaxUtilizationRate(uint256 value)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
50 <= value && value <= 100,
"Pool error: Wrong utilization rate limitation value"
);
maxUtilizationRate = value;
}
/**
* @notice Used for setting the collateralization ratio for the option
* collateral size that will be locked at the moment of buying them.
*
* Example: if `CollateralizationRatio` = 50, then 50% of an option's
* notional size will be locked in the pools at the moment of buying it:
* say, 1 ETH call option will be collateralized with 0.5 ETH (50%).
* Note that if an option holder's net P&L USD value (as options
* are cash-settled) will exceed the amount of the collateral locked
* in the option, she will receive the required amount at the moment
* of exercising the option using the pool's unutilized (unlocked) funds.
* @param value The collateralization ratio in a range of 30% — 100%
**/
function setCollateralizationRatio(uint256 value)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
collateralizationRatio = value;
}
/**
* @dev See EIP-165: ERC-165 Standard Interface Detection
* https://eips.ethereum.org/EIPS/eip-165.
**/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, AccessControl, IERC165)
returns (bool)
{
return
interfaceId == type(IHegicPool).interfaceId ||
AccessControl.supportsInterface(interfaceId) ||
ERC721.supportsInterface(interfaceId);
}
/**
* @notice Used for selling the options contracts
* with the parameters chosen by the option buyer
* such as the period of holding, option size (amount),
* strike price and the premium to be paid for the option.
* @param holder The option buyer address
* @param period The option period
* @param amount The option size
* @param strike The option strike
* @return id ID of ERC721 token linked to the option
**/
function sellOption(
address holder,
uint256 period,
uint256 amount,
uint256 strike
) external override onlyRole(SELLER_ROLE) returns (uint256 id) {
if (strike == 0) strike = _currentPrice();
uint256 balance = totalBalance;
uint256 amountToBeLocked = _calculateLockedAmount(amount);
require(period >= 1 days, "Pool Error: The period is too short");
require(period <= 90 days, "Pool Error: The period is too long");
require(
(lockedAmount + amountToBeLocked) * 100 <=
balance * maxUtilizationRate,
"Pool Error: The amount is too large"
);
(uint256 settlementFee, uint256 premium) =
_calculateTotalPremium(period, amount, strike);
//
// uint256 hedgedPremiumTotal = (premium * hedgedBalance) / balance;
// uint256 hedgeFee = (hedgedPremiumTotal * hedgeFeeRate) / 100;
// uint256 hedgePremium = hedgedPremiumTotal - hedgeFee;
// uint256 unhedgePremium = premium - hedgedPremiumTotal;
lockedAmount += amountToBeLocked;
id = optionsManager.createOptionFor(holder);
options[id] = Option(
OptionState.Active,
uint112(strike),
uint120(amount),
uint120(amountToBeLocked),
uint40(block.timestamp + period),
uint120(premium)
);
token.safeTransferFrom(
_msgSender(),
address(this),
premium + settlementFee
);
if (settlementFee > 0) {
token.safeTransfer(address(settlementFeeRecipient), settlementFee);
settlementFeeRecipient.distributeUnrealizedRewards();
}
emit Acquired(id, settlementFee, premium);
}
/**
* @notice Used for setting the price calculator
* contract that will be used for pricing the options.
* @param pc A new price calculator contract address
**/
function setPriceCalculator(IPriceCalculator pc)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
pricer = pc;
}
/**
* @notice Used for exercising the ITM (in-the-money)
* options contracts in case of having the unrealized profits
* accrued during the period of holding the option contract.
* @param id ID of ERC721 token linked to the option
**/
function exercise(uint256 id) external override {
Option storage option = options[id];
uint256 profit = _profitOf(option);
require(
optionsManager.isApprovedOrOwner(_msgSender(), id),
"Pool Error: msg.sender can't exercise this option"
);
require(
option.expired > block.timestamp,
"Pool Error: The option has already expired"
);
require(
profit > 0,
"Pool Error: There are no unrealized profits for this option"
);
_unlock(option);
option.state = OptionState.Exercised;
_send(optionsManager.ownerOf(id), profit);
emit Exercised(id, profit);
}
function _send(address to, uint256 transferAmount) private {
require(to != address(0));
totalBalance -= transferAmount;
token.safeTransfer(to, transferAmount);
}
/**
* @notice Used for unlocking the expired OTM (out-of-the-money)
* options contracts in case if there was no unrealized P&L
* accrued during the period of holding a particular option.
* Note that the `unlock` function releases the liquidity that
* was locked in the option when it was active and the premiums
* that are distributed pro rata among the liquidity providers.
* @param id ID of ERC721 token linked to the option
**/
function unlock(uint256 id) external override {
Option storage option = options[id];
require(
option.expired < block.timestamp,
"Pool Error: The option has not expired yet"
);
_unlock(option);
option.state = OptionState.Expired;
emit Expired(id);
}
function _unlock(Option storage option) internal {
require(
option.state == OptionState.Active,
"Pool Error: The option with such an ID has already been exercised or expired"
);
lockedAmount -= option.lockedAmount;
totalBalance += option.premium;
}
function _calculateLockedAmount(uint256 amount)
internal
virtual
returns (uint256)
{
return (amount * collateralizationRatio) / 100;
}
/**
* @notice Used for depositing the funds into the pool
* and minting the liquidity tranche ERC721 token
* which represents the liquidity provider's share
* in the pool and her unrealized P&L for this tranche.
* @param account The liquidity provider's address
* @param amount The size of the liquidity tranche
* @param minShare The minimum share in the pool for the user
**/
function provideFrom(
address account,
uint256 amount,
bool,
uint256 minShare
) external override nonReentrant returns (uint256 share) {
uint256 balance = totalBalance;
share = totalShare > 0 && balance > 0
? (amount * totalShare) / balance
: amount * INITIAL_RATE;
uint256 limit = maxDepositAmount - totalBalance;
require(share >= minShare, "Pool Error: The mint limit is too large");
require(share > 0, "Pool Error: The amount is too small");
require(
amount <= limit,
"Pool Error: Depositing into the pool is not available"
);
totalShare += share;
totalBalance += amount;
uint256 trancheID = tranches.length;
tranches.push(
Tranche(TrancheState.Open, share, amount, block.timestamp)
);
_safeMint(account, trancheID);
token.safeTransferFrom(_msgSender(), address(this), amount);
}
/**
* @notice Used for withdrawing the funds from the pool
* plus the net positive P&L earned or
* minus the net negative P&L lost on
* providing liquidity and selling options.
* @param trancheID The liquidity tranche ID
* @return amount The amount received after the withdrawal
**/
function withdraw(uint256 trancheID)
external
override
nonReentrant
returns (uint256 amount)
{
address owner = ownerOf(trancheID);
Tranche memory t = tranches[trancheID];
amount = _withdraw(owner, trancheID);
emit Withdrawn(owner, trancheID, amount);
}
/**
* @notice Used for withdrawing the funds from the pool
* by the hedged liquidity tranches providers
* in case of an urgent need to withdraw the liquidity
* without receiving the loss compensation from
* the hedging pool: the net difference between
* the amount deposited and the withdrawal amount.
* @param trancheID ID of liquidity tranche
* @return amount The amount received after the withdrawal
**/
function withdrawWithoutHedge(uint256 trancheID)
external
override
nonReentrant
returns (uint256 amount)
{
address owner = ownerOf(trancheID);
amount = _withdraw(owner, trancheID);
emit Withdrawn(owner, trancheID, amount);
}
function _withdraw(address owner, uint256 trancheID)
internal
returns (uint256 amount)
{
Tranche storage t = tranches[trancheID];
// uint256 lockupPeriod =
// t.hedged
// ? lockupPeriodForHedgedTranches
// : lockupPeriodForUnhedgedTranches;
// require(t.state == TrancheState.Open);
require(_isApprovedOrOwner(_msgSender(), trancheID));
require(
block.timestamp > t.creationTimestamp + lockupPeriod,
"Pool Error: The withdrawal is locked up"
);
t.state = TrancheState.Closed;
// if (t.hedged) {
// amount = (t.share * hedgedBalance) / hedgedShare;
// hedgedShare -= t.share;
// hedgedBalance -= amount;
// } else {
amount = (t.share * totalBalance) / totalShare;
totalShare -= t.share;
totalBalance -= amount;
// }
token.safeTransfer(owner, amount);
}
/**
* @return balance Returns the amount of liquidity available for withdrawing
**/
function availableBalance() public view returns (uint256 balance) {
return totalBalance - lockedAmount;
}
// /**
// * @return balance Returns the total balance of liquidity provided to the pool
// **/
// function totalBalance() public view override returns (uint256 balance) {
// return hedgedBalance + unhedgedBalance;
// }
function _beforeTokenTransfer(
address,
address,
uint256 id
) internal view override {
require(
tranches[id].state == TrancheState.Open,
"Pool Error: The closed tranches can not be transferred"
);
}
/**
* @notice Returns the amount of unrealized P&L of the option
* that could be received by the option holder in case
* if she exercises it as an ITM (in-the-money) option.
* @param id ID of ERC721 token linked to the option
**/
function profitOf(uint256 id) external view returns (uint256) {
return _profitOf(options[id]);
}
function _profitOf(Option memory option)
internal
view
virtual
returns (uint256 amount);
/**
* @notice Used for calculating the `TotalPremium`
* for the particular option with regards to
* the parameters chosen by the option buyer
* such as the period of holding, size (amount)
* and strike price.
* @param period The period of holding the option
* @param period The size of the option
**/
function calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) external view override returns (uint256 settlementFee, uint256 premium) {
return _calculateTotalPremium(period, amount, strike);
}
function _calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) internal view virtual returns (uint256 settlementFee, uint256 premium) {
(settlementFee, premium) = pricer.calculateTotalPremium(
period,
amount,
strike
);
}
/**
* @notice Used for changing the `settlementFeeRecipient`
* contract address for distributing the settlement fees
* (staking rewards) among the staking participants.
* @param recipient New staking contract address
**/
function setSettlementFeeRecipient(IHegicStaking recipient)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(address(recipient) != address(0));
settlementFeeRecipient = recipient;
}
function _currentPrice() internal view returns (uint256 price) {
(, int256 latestPrice, , , ) = priceProvider.latestRoundData();
price = uint256(latestPrice);
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
// /**
// * @author 0mllwntrmt3
// * @title Hegic Protocol V8888 Interface
// * @notice The interface for the price calculator,
// * options, pools and staking contracts.
// **/
/**
* @notice The interface fot the contract that calculates
* the options prices (the premiums) that are adjusted
* through balancing the `ImpliedVolRate` parameter.
**/
interface IPriceCalculator {
/**
* @param period The option period
* @param amount The option size
* @param strike The option strike
**/
function calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) external view returns (uint256 settlementFee, uint256 premium);
}
/**
* @notice The interface for the contract that manages pools and the options parameters,
* accumulates the funds from the liquidity providers and makes the withdrawals for them,
* sells the options contracts to the options buyers and collateralizes them,
* exercises the ITM (in-the-money) options with the unrealized P&L and settles them,
* unlocks the expired options and distributes the premiums among the liquidity providers.
**/
interface IHegicPool is IERC721, IPriceCalculator {
enum OptionState {Invalid, Active, Exercised, Expired}
enum TrancheState {Invalid, Open, Closed}
/**
* @param state The state of the option: Invalid, Active, Exercised, Expired
* @param strike The option strike
* @param amount The option size
* @param lockedAmount The option collateral size locked
* @param expired The option expiration timestamp
* @param hedgePremium The share of the premium paid for hedging from the losses
* @param unhedgePremium The share of the premium paid to the hedged liquidity provider
**/
struct Option {
OptionState state; // 8
uint112 strike; // 120
uint120 amount; // 128
uint120 lockedAmount; // 108
uint40 expired; // 40
uint120 premium; // 108
}
/**
* @param state The state of the liquidity tranche: Invalid, Open, Closed
* @param share The liquidity provider's share in the pool
* @param amount The size of liquidity provided
* @param creationTimestamp The liquidity deposit timestamp
* @param hedged The liquidity tranche type: hedged or unhedged (classic)
**/
struct Tranche {
TrancheState state;
uint256 share;
uint256 amount;
uint256 creationTimestamp;
}
/**
* @param id The ERC721 token ID linked to the option
* @param settlementFee The part of the premium that
* is distributed among the HEGIC staking participants
* @param premium The part of the premium that
* is distributed among the liquidity providers
**/
event Acquired(uint256 indexed id, uint256 settlementFee, uint256 premium);
/**
* @param id The ERC721 token ID linked to the option
* @param profit The profits of the option if exercised
**/
event Exercised(uint256 indexed id, uint256 profit);
/**
* @param id The ERC721 token ID linked to the option
**/
event Expired(uint256 indexed id);
/**
* @param account The liquidity provider's address
* @param trancheID The liquidity tranche ID
**/
event Withdrawn(
address indexed account,
uint256 indexed trancheID,
uint256 amount
);
/**
* @param id The ERC721 token ID linked to the option
**/
function unlock(uint256 id) external;
/**
* @param id The ERC721 token ID linked to the option
**/
function exercise(uint256 id) external;
function setLockupPeriod(uint256) external;
function collateralizationRatio() external view returns (uint256);
/**
* @param trancheID The liquidity tranche ID
* @return amount The liquidity to be received with
* the positive or negative P&L earned or lost during
* the period of holding the liquidity tranche considered
**/
function withdraw(uint256 trancheID) external returns (uint256 amount);
function pricer() external view returns (IPriceCalculator);
/**
* @param account The liquidity provider's address
* @param amount The size of the liquidity tranche
* @param hedged The type of the liquidity tranche
* @param minShare The minimum share in the pool of the user
**/
function provideFrom(
address account,
uint256 amount,
bool hedged,
uint256 minShare
) external returns (uint256 share);
/**
* @param holder The option buyer address
* @param period The option period
* @param amount The option size
* @param strike The option strike
**/
function sellOption(
address holder,
uint256 period,
uint256 amount,
uint256 strike
) external returns (uint256 id);
/**
* @param trancheID The liquidity tranche ID
* @return amount The amount to be received after the withdrawal
**/
function withdrawWithoutHedge(uint256 trancheID)
external
returns (uint256 amount);
/**
* @return amount The total liquidity provided into the pool
**/
function totalBalance() external view returns (uint256 amount);
/**
* @return amount The total liquidity locked in the pool
**/
function lockedAmount() external view returns (uint256 amount);
function token() external view returns (IERC20);
/**
* @return state The state of the option: Invalid, Active, Exercised, Expired
* @return strike The option strike
* @return amount The option size
* @return lockedAmount The option collateral size locked
* @return expired The option expiration timestamp
* @return premium The share of the premium paid to the liquidity provider
**/
function options(uint256 id)
external
view
returns (
OptionState state,
uint112 strike,
uint120 amount,
uint120 lockedAmount,
uint40 expired,
uint120 premium
);
/**
* @return state The state of the liquidity tranche: Invalid, Open, Closed
* @return share The liquidity provider's share in the pool
* @return amount The size of liquidity provided
* @return creationTimestamp The liquidity deposit timestamp
**/
function tranches(uint256 id)
external
view
returns (
TrancheState state,
uint256 share,
uint256 amount,
uint256 creationTimestamp
);
}
interface ISettlementFeeRecipient {
function distributeUnrealizedRewards() external;
}
/**
* @notice The interface for the contract that stakes HEGIC tokens
* through buying microlots (any amount of HEGIC tokens per microlot)
* and staking lots (888,000 HEGIC per lot), accumulates the staking
* rewards (settlement fees) and distributes the staking rewards among
* the microlots and staking lots holders (should be claimed manually).
**/
interface IHegicStaking is ISettlementFeeRecipient {
event Claim(address indexed account, uint256 amount);
event Profit(uint256 amount);
event MicroLotsAcquired(address indexed account, uint256 amount);
event MicroLotsSold(address indexed account, uint256 amount);
function claimProfits(address account) external returns (uint256 profit);
function buyStakingLot(uint256 amount) external;
function sellStakingLot(uint256 amount) external;
function profitOf(address account) external view returns (uint256);
}
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 value) external;
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/**
* @notice The interface for the contract
* that tokenizes options as ERC721.
**/
interface IOptionsManager is IERC721 {
/**
* @param holder The option buyer address
**/
function createOptionFor(address holder) external returns (uint256);
/**
* @param tokenId The ERC721 token ID linked to the option
**/
function tokenPool(uint256 tokenId) external returns (address pool);
/**
* @param spender The option buyer address or another address
* with the granted permission to buy/exercise options on the user's behalf
* @param tokenId The ERC721 token ID linked to the option
**/
function isApprovedOrOwner(address spender, uint256 tokenId)
external
view
returns (bool);
}
// 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 "./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 default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// 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.7.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/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);
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "./HegicPool.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Put Liquidity Pool Contract
* @notice The Put Liquidity Pool Contract
**/
contract HegicSTRIP is HegicPool {
uint256 private immutable SpotDecimals; // 1e18
uint256 private constant TokenDecimals = 1e6; // 1e6
/**
* @param name The pool contract name
* @param symbol The pool ticker for the ERC721 options
**/
constructor(
IERC20 _token,
string memory name,
string memory symbol,
IOptionsManager manager,
IPriceCalculator _pricer,
IHegicStaking _settlementFeeRecipient,
AggregatorV3Interface _priceProvider,
uint8 spotDecimals
)
HegicPool(
_token,
name,
symbol,
manager,
_pricer,
_settlementFeeRecipient,
_priceProvider
)
{
SpotDecimals = 10**spotDecimals;
}
function _profitOf(Option memory option)
internal
view
override
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
if (currentPrice > option.strike) {
return _profitOfCall(option);
} else if (currentPrice < option.strike) {
return _profitOfPut(option);
}
return 0;
}
function _profitOfPut(Option memory option)
internal
view
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
if (currentPrice > option.strike) return 0;
return
((option.strike - currentPrice) *
(2 * option.amount) *
TokenDecimals) /
SpotDecimals /
1e8;
}
function _profitOfCall(Option memory option)
internal
view
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
if (currentPrice < option.strike) return 0;
return
((currentPrice - option.strike) * option.amount * TokenDecimals) /
SpotDecimals /
1e8;
}
function _calculateLockedAmount(uint256 amount)
internal
view
override
returns (uint256)
{
return
(amount *
collateralizationRatio *
_currentPrice() *
TokenDecimals) /
SpotDecimals /
1e8 /
100;
}
function _calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) internal view override returns (uint256 settlementFee, uint256 premium) {
uint256 currentPrice = _currentPrice();
(settlementFee, premium) = pricer.calculateTotalPremium(
period,
amount,
strike
);
settlementFee =
(settlementFee * currentPrice * TokenDecimals) /
1e8 /
SpotDecimals;
premium = (premium * currentPrice * TokenDecimals) / 1e8 / SpotDecimals;
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "./HegicPool.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Put Liquidity Pool Contract
* @notice The Put Liquidity Pool Contract
**/
contract HegicSTRAP is HegicPool {
uint256 private immutable SpotDecimals; // 1e18
uint256 private constant TokenDecimals = 1e6; // 1e6
/**
* @param name The pool contract name
* @param symbol The pool ticker for the ERC721 options
**/
constructor(
IERC20 _token,
string memory name,
string memory symbol,
IOptionsManager manager,
IPriceCalculator _pricer,
IHegicStaking _settlementFeeRecipient,
AggregatorV3Interface _priceProvider,
uint8 spotDecimals
)
HegicPool(
_token,
name,
symbol,
manager,
_pricer,
_settlementFeeRecipient,
_priceProvider
)
{
SpotDecimals = 10**spotDecimals;
}
function _profitOf(Option memory option)
internal
view
override
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
if (currentPrice > option.strike) {
return _profitOfCall(option);
} else if (currentPrice < option.strike) {
return _profitOfPut(option);
}
return 0;
}
function _profitOfPut(Option memory option)
internal
view
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
if (currentPrice > option.strike) return 0;
return
((option.strike - currentPrice) * option.amount * TokenDecimals) /
SpotDecimals /
1e8;
}
function _profitOfCall(Option memory option)
internal
view
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
if (currentPrice < option.strike) return 0;
return
((currentPrice - option.strike) *
(2 * option.amount) *
TokenDecimals) /
SpotDecimals /
1e8;
}
function _calculateLockedAmount(uint256 amount)
internal
view
override
returns (uint256)
{
return
(amount *
collateralizationRatio *
_currentPrice() *
TokenDecimals) /
SpotDecimals /
1e8 /
100;
}
function _calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) internal view override returns (uint256 settlementFee, uint256 premium) {
uint256 currentPrice = _currentPrice();
(settlementFee, premium) = pricer.calculateTotalPremium(
period,
amount,
strike
);
settlementFee =
(settlementFee * currentPrice * TokenDecimals) /
1e8 /
SpotDecimals;
premium = (premium * currentPrice * TokenDecimals) / 1e8 / SpotDecimals;
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "./HegicPool.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Put Liquidity Pool Contract
* @notice The Put Liquidity Pool Contract
**/
contract HegicSTRADDLE is HegicPool {
uint256 private immutable SpotDecimals; // 1e18
uint256 private constant TokenDecimals = 1e6; // 1e6
/**
* @param name The pool contract name
* @param symbol The pool ticker for the ERC721 options
**/
constructor(
IERC20 _token,
string memory name,
string memory symbol,
IOptionsManager manager,
IPriceCalculator _pricer,
IHegicStaking _settlementFeeRecipient,
AggregatorV3Interface _priceProvider,
uint8 spotDecimals
)
HegicPool(
_token,
name,
symbol,
manager,
_pricer,
_settlementFeeRecipient,
_priceProvider
)
{
SpotDecimals = 10**spotDecimals;
}
function _profitOf(Option memory option)
internal
view
override
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
if (currentPrice > option.strike) {
return _profitOfCall(option);
} else if (currentPrice < option.strike) {
return _profitOfPut(option);
}
return 0;
}
function _profitOfPut(Option memory option)
internal
view
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
return
((option.strike - currentPrice) * option.amount * TokenDecimals) /
SpotDecimals /
1e8;
}
function _profitOfCall(Option memory option)
internal
view
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
return
((currentPrice - option.strike) * option.amount * TokenDecimals) /
SpotDecimals /
1e8;
}
function _calculateLockedAmount(uint256 amount)
internal
view
override
returns (uint256)
{
return
(amount *
collateralizationRatio *
_currentPrice() *
TokenDecimals) /
SpotDecimals /
1e8 /
100;
}
function _calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) internal view override returns (uint256 settlementFee, uint256 premium) {
uint256 currentPrice = _currentPrice();
(settlementFee, premium) = pricer.calculateTotalPremium(
period,
amount,
strike
);
settlementFee =
(settlementFee * currentPrice * TokenDecimals) /
1e8 /
SpotDecimals;
premium = (premium * currentPrice * TokenDecimals) / 1e8 / SpotDecimals;
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "./HegicPool.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Put Liquidity Pool Contract
* @notice The Put Liquidity Pool Contract
**/
contract HegicPUT is HegicPool {
uint256 private immutable SpotDecimals;
uint256 private immutable TokenDecimals; // 1e6
/**
* @param name The pool contract name
* @param symbol The pool ticker for the ERC721 options
**/
constructor(
IERC20 _token,
string memory name,
string memory symbol,
IOptionsManager manager,
IPriceCalculator _pricer,
IHegicStaking _settlementFeeRecipient,
AggregatorV3Interface _priceProvider,
uint8 spotDecimals,
uint8 tokenDecimals
)
HegicPool(
_token,
name,
symbol,
manager,
_pricer,
_settlementFeeRecipient,
_priceProvider
)
{
SpotDecimals = 10**spotDecimals;
TokenDecimals = 10**tokenDecimals;
}
function _profitOf(Option memory option)
internal
view
override
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
if (currentPrice > option.strike) return 0;
uint256 priceDecimals = 10**priceProvider.decimals();
return
((option.strike - currentPrice) * option.amount * TokenDecimals) /
SpotDecimals /
priceDecimals;
}
function _calculateLockedAmount(uint256 amount)
internal
view
override
returns (uint256)
{
return
(amount *
collateralizationRatio *
_currentPrice() *
TokenDecimals) /
SpotDecimals /
1e8 /
100;
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "../Interfaces/IOptionsManager.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Options Manager Contract
* @notice The contract that buys the options contracts for the options holders
* as well as checks whether the contract that is used for buying/exercising
* options has been been granted with the permission to do it on the user's behalf.
**/
contract OptionsManager is
IOptionsManager,
ERC721("Hegic V8888 Options (Tokenized)", "HOT8888"),
AccessControl
{
bytes32 public constant HEGIC_POOL_ROLE = keccak256("HEGIC_POOL_ROLE");
uint256 public nextTokenId = 0;
mapping(uint256 => address) public override tokenPool;
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @dev See EIP-165: ERC-165 Standard Interface Detection
* https://eips.ethereum.org/EIPS/eip-165
**/
function createOptionFor(address holder)
public
override
onlyRole(HEGIC_POOL_ROLE)
returns (uint256 id)
{
id = nextTokenId++;
tokenPool[id] = msg.sender;
_safeMint(holder, id);
}
/**
* @dev See EIP-165: ERC-165 Standard Interface Detection
* https://eips.ethereum.org/EIPS/eip-165
**/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, AccessControl, IERC165)
returns (bool)
{
return
interfaceId == type(IOptionsManager).interfaceId ||
AccessControl.supportsInterface(interfaceId) ||
ERC721.supportsInterface(interfaceId);
}
/**
* @notice Used for checking whether the user has approved
* the contract to buy/exercise the options on her behalf.
* @param spender The address of the contract
* that is used for exercising the options
* @param tokenId The ERC721 token ID that is linked to the option
**/
function isApprovedOrOwner(address spender, uint256 tokenId)
external
view
virtual
override
returns (bool)
{
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "../Interfaces/Interfaces.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract SettlementFeeDistributor is ISettlementFeeRecipient, Ownable {
using SafeERC20 for IERC20;
ISettlementFeeRecipient public immutable staking;
IERC20 public immutable token;
address public immutable HLTPs;
uint128 public totalShare = 24;
uint128 public stakingShare = 19;
constructor(
ISettlementFeeRecipient staking_,
IERC20 token_,
address HLTPs_
) {
staking = staking_;
token = token_;
HLTPs = HLTPs_;
}
function setShares(uint128 stakingShare_, uint128 totalShare_)
external
onlyOwner
{
require(
totalShare_ != 0,
"SettlementFeeDistributor: totalShare is zero"
);
require(
stakingShare_ <= totalShare,
"SettlementFeeDistributor: stakingShare is too large"
);
totalShare = totalShare_;
stakingShare = stakingShare_;
}
function distributeUnrealizedRewards() external override {
uint256 amount = token.balanceOf(address(this));
require(amount > 0, "SettlementFeeDistributor: Amount is zero");
uint256 stakingAmount = (amount * stakingShare) / totalShare;
token.safeTransfer(HLTPs, amount - stakingAmount);
token.safeTransfer(address(staking), stakingAmount);
staking.distributeUnrealizedRewards();
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../Interfaces/Interfaces.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Staking Contract
* @notice The contract that stakes the HEGIC tokens through
* buying the microlots (any amount of HEGIC tokens per microlot)
* and the staking lots (888,000 HEGIC per lot), accumulates the staking
* rewards (settlement fees) and distributes the staking rewards among
* the microlots and staking lots holders (should be claimed manually).
**/
contract HegicStaking is ERC20, IHegicStaking {
using SafeERC20 for IERC20;
IERC20 public immutable HEGIC;
IERC20 public immutable token;
uint256 public constant STAKING_LOT_PRICE = 888_000e18;
uint256 internal constant ACCURACY = 1e30;
uint256 internal realisedBalance;
uint256 public microLotsTotal = 0;
mapping(address => uint256) public microBalance;
uint256 public totalProfit = 0;
mapping(address => uint256) internal lastProfit;
uint256 public microLotsProfits = 0;
mapping(address => uint256) internal lastMicroLotProfits;
mapping(address => uint256) internal savedProfit;
uint256 public classicLockupPeriod = 1 days;
uint256 public microLockupPeriod = 1 days;
mapping(address => uint256) public lastBoughtTimestamp;
mapping(address => uint256) public lastMicroBoughtTimestamp;
mapping(address => bool) public _revertTransfersInLockUpPeriod;
constructor(
ERC20 _hegic,
ERC20 _token,
string memory name,
string memory short
) ERC20(name, short) {
HEGIC = _hegic;
token = _token;
}
function decimals() public pure override returns (uint8) {
return 0;
}
/**
* @notice Used by the HEGIC microlots holders
* or staking lots holders for claiming
* the accumulated staking rewards.
**/
function claimProfits(address account)
external
override
returns (uint256 profit)
{
saveProfits(account);
profit = savedProfit[account];
require(profit > 0, "Zero profit");
savedProfit[account] = 0;
realisedBalance -= profit;
token.safeTransfer(account, profit);
emit Claim(account, profit);
}
/**
* @notice Used for staking any amount of the HEGIC tokens
* higher than zero in the form of buying the microlot
* for receiving a pro rata share of 20% of the total staking
* rewards (settlement fees) generated by the protocol.
**/
function buyMicroLot(uint256 amount) external {
require(amount > 0, "Amount is zero");
saveProfits(msg.sender);
lastMicroBoughtTimestamp[msg.sender] = block.timestamp;
microLotsTotal += amount;
microBalance[msg.sender] += amount;
HEGIC.safeTransferFrom(msg.sender, address(this), amount);
emit MicroLotsAcquired(msg.sender, amount);
}
/**
* @notice Used for unstaking the HEGIC tokens
* in the form of selling the microlot.
**/
function sellMicroLot(uint256 amount) external {
require(amount > 0, "Amount is zero");
require(
lastMicroBoughtTimestamp[msg.sender] + microLockupPeriod <
block.timestamp,
"The action is suspended due to the lockup"
);
saveProfits(msg.sender);
microLotsTotal -= amount;
microBalance[msg.sender] -= amount;
HEGIC.safeTransfer(msg.sender, amount);
emit MicroLotsSold(msg.sender, amount);
}
/**
* @notice Used for staking the fixed amount of 888,000 HEGIC
* tokens in the form of buying the staking lot (transferrable)
* for receiving a pro rata share of 80% of the total staking
* rewards (settlement fees) generated by the protocol.
**/
function buyStakingLot(uint256 amount) external override {
lastBoughtTimestamp[msg.sender] = block.timestamp;
require(amount > 0, "Amount is zero");
_mint(msg.sender, amount);
HEGIC.safeTransferFrom(
msg.sender,
address(this),
amount * STAKING_LOT_PRICE
);
}
/**
* @notice Used for unstaking 888,000 HEGIC
* tokens in the form of selling the staking lot.
**/
function sellStakingLot(uint256 amount) external override lockupFree {
_burn(msg.sender, amount);
HEGIC.safeTransfer(msg.sender, amount * STAKING_LOT_PRICE);
}
function revertTransfersInLockUpPeriod(bool value) external {
_revertTransfersInLockUpPeriod[msg.sender] = value;
}
/**
* @notice Returns the amount of unclaimed staking rewards.
**/
function profitOf(address account)
external
view
override
returns (uint256)
{
(uint256 profit, uint256 micro) = getUnsavedProfits(account);
return savedProfit[account] + profit + micro;
}
/**
* @notice Used for calculating the amount of accumulated
* staking rewards before the share of the staking participant
* changes higher (buying more microlots or staking lots)
* or lower (selling more microlots or staking lots).
**/
function getUnsavedProfits(address account)
internal
view
returns (uint256 total, uint256 micro)
{
total =
((totalProfit - lastProfit[account]) * balanceOf(account)) /
ACCURACY;
micro =
((microLotsProfits - lastMicroLotProfits[account]) *
microBalance[account]) /
ACCURACY;
}
/**
* @notice Used for saving the amount of accumulated
* staking rewards before the staking participant's share
* changes higher (buying more microlots or staking lots)
* or lower (selling more microlots or staking lots).
**/
function saveProfits(address account) internal {
(uint256 unsaved, uint256 micro) = getUnsavedProfits(account);
lastProfit[account] = totalProfit;
lastMicroLotProfits[account] = microLotsProfits;
savedProfit[account] += unsaved;
savedProfit[account] += micro;
}
function _beforeTokenTransfer(
address from,
address to,
uint256
) internal override {
if (from != address(0)) saveProfits(from);
if (to != address(0)) saveProfits(to);
if (
lastBoughtTimestamp[from] + classicLockupPeriod > block.timestamp &&
lastBoughtTimestamp[from] > lastBoughtTimestamp[to]
) {
require(
!_revertTransfersInLockUpPeriod[to],
"The recipient does not agree to accept the locked funds"
);
lastBoughtTimestamp[to] = lastBoughtTimestamp[from];
}
}
/**
* @notice Used for distributing the staking rewards
* among the microlots and staking lots holders.
**/
function distributeUnrealizedRewards() external override {
uint256 amount = token.balanceOf(address(this)) - realisedBalance;
realisedBalance += amount;
uint256 _totalSupply = totalSupply();
if (microLotsTotal + _totalSupply > 0) {
if (microLotsTotal == 0) {
totalProfit += (amount * ACCURACY) / _totalSupply;
} else if (_totalSupply == 0) {
microLotsProfits += (amount * ACCURACY) / microLotsTotal;
} else {
uint256 microAmount = amount / 5;
uint256 baseAmount = amount - microAmount;
microLotsProfits += (microAmount * ACCURACY) / microLotsTotal;
totalProfit += (baseAmount * ACCURACY) / _totalSupply;
}
emit Profit(amount);
}
}
modifier lockupFree {
require(
lastBoughtTimestamp[msg.sender] + classicLockupPeriod <=
block.timestamp,
"The action is suspended due to the lockup"
);
_;
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic
*
* 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/>.
**/
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract ERC20Mock is ERC20 {
uint8 private immutable _decimals;
constructor(
string memory name,
string memory symbol,
uint8 __decimals
) ERC20(name, symbol) {
_decimals = __decimals;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function mintTo(address account, uint256 amount) public {
_mint(account, amount);
}
function mint(uint256 amount) public {
_mint(msg.sender, amount);
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic
*
* 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/>.
**/
import "./ERC20Mock.sol";
contract WETHMock is ERC20Mock("WETH", "Wrapped Ether", 18) {
function deposit() external payable {
_mint(msg.sender, msg.value);
}
function withdraw(uint256 amount) external {
_burn(msg.sender, amount);
payable(msg.sender).transfer(amount);
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic
*
* 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/>.
**/
import "./ERC20Mock.sol";
import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV3Interface.sol";
contract UniswapRouterMock {
ERC20Mock public immutable WBTC;
ERC20Mock public immutable USDC;
AggregatorV3Interface public immutable WBTCPriceProvider;
AggregatorV3Interface public immutable ETHPriceProvider;
constructor(
ERC20Mock _wbtc,
ERC20Mock _usdc,
AggregatorV3Interface wpp,
AggregatorV3Interface epp
) {
WBTC = _wbtc;
USDC = _usdc;
WBTCPriceProvider = wpp;
ETHPriceProvider = epp;
}
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 /*deadline*/
) external payable returns (uint256[] memory amounts) {
require(path.length == 2, "UniswapMock: wrong path");
require(
path[1] == address(USDC) || path[1] == address(WBTC),
"UniswapMock: too small value"
);
amounts = getAmountsIn(amountOut, path);
require(msg.value >= amounts[0], "UniswapMock: too small value");
if (msg.value > amounts[0])
payable(msg.sender).transfer(msg.value - amounts[0]);
ERC20Mock(path[1]).mintTo(to, amountOut);
}
function getAmountsIn(uint256 amountOut, address[] calldata path)
public
view
returns (uint256[] memory amounts)
{
require(path.length == 2, "UniswapMock: wrong path");
uint256 amount;
if (path[1] == address(USDC)) {
(, int256 ethPrice, , , ) = ETHPriceProvider.latestRoundData();
amount = (amountOut * 1e8) / uint256(ethPrice);
} else if (path[1] == address(WBTC)) {
(, int256 ethPrice, , , ) = ETHPriceProvider.latestRoundData();
(, int256 wbtcPrice, , , ) = WBTCPriceProvider.latestRoundData();
amount = (amountOut * uint256(wbtcPrice)) / uint256(ethPrice);
} else {
revert("UniswapMock: wrong path");
}
amounts = new uint256[](2);
amounts[0] = (amount * 103) / 100;
amounts[1] = amountOut;
}
}
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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.8.6;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev A contract that allows to lock-up the rewards in
* the Hegic Long-Term Pools during a certain period of time.
*/
contract HLTPs {
using SafeERC20 for IERC20;
// The beneficiary of rewards after they are released
address private immutable _beneficiary;
// The timestamp when the rewards release will be enabled
uint256 private immutable _releaseTime;
constructor(uint256 releaseTime_) {
_beneficiary = msg.sender;
_releaseTime = releaseTime_;
}
/**
* @return The beneficiary address that will distribute the rewards.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return The point of time when the rewards will be released.
*/
function releaseTime() public view returns (uint256) {
return _releaseTime;
}
/**
* @notice Transfers tokens locked by timelock to beneficiary.
*/
function release(IERC20 token) public {
require(
block.timestamp >= releaseTime(),
"HLTPs: Current time is earlier than the release time"
);
uint256 amount = token.balanceOf(address(this));
require(amount > 0, "HLTPs: No rewards to be released");
token.safeTransfer(beneficiary(), amount);
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
*/
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Linear.sol";
import "./IBondingCurve.sol";
contract Erc20BondingCurve is LinearBondingCurve {
using SafeERC20 for IERC20;
IERC20 public immutable saleToken;
IERC20 public immutable purchaseToken;
uint256 public soldAmount;
uint256 public comissionShare = 20;
address payable public hegicDevelopmentFund;
event Bought(address indexed account, uint256 amount, uint256 ethAmount);
event Sold(
address indexed account,
uint256 amount,
uint256 ethAmount,
uint256 comission
);
constructor(
IERC20 _saleToken,
IERC20 _purchaseToken,
uint256 k,
uint256 startPrice
) LinearBondingCurve(k, startPrice) {
saleToken = _saleToken;
purchaseToken = _purchaseToken;
hegicDevelopmentFund = payable(msg.sender);
_setupRole(LBC_ADMIN_ROLE, msg.sender);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function buy(uint256 tokenAmount) external {
uint256 nextSold = soldAmount + tokenAmount;
uint256 purchaseAmount = s(soldAmount, nextSold);
soldAmount = nextSold;
purchaseToken.safeTransferFrom(
msg.sender,
address(this),
purchaseAmount
);
saleToken.safeTransfer(msg.sender, tokenAmount);
emit Bought(msg.sender, tokenAmount, purchaseAmount);
}
function sell(uint256 tokenAmount) external {
uint256 nextSold = soldAmount - tokenAmount;
uint256 saleAmount = s(nextSold, soldAmount);
uint256 comission = (saleAmount * comissionShare) / 100;
uint256 refund = saleAmount - comission;
require(comission > 0, "Amount is too small");
soldAmount = nextSold;
saleToken.safeTransferFrom(msg.sender, address(this), tokenAmount);
purchaseToken.safeTransfer(hegicDevelopmentFund, comission);
purchaseToken.safeTransfer(msg.sender, refund);
emit Sold(msg.sender, tokenAmount, refund, comission);
}
function setHDF(address payable value)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
hegicDevelopmentFund = value;
}
function setCommissionShare(uint256 value)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
comissionShare = value;
}
function destruct() external onlyRole(DEFAULT_ADMIN_ROLE) {
selfdestruct(hegicDevelopmentFund);
}
function withdawERC20(IERC20 token) external onlyRole(DEFAULT_ADMIN_ROLE) {
token.transfer(hegicDevelopmentFund, token.balanceOf(address(this)));
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "../Interfaces/Interfaces.sol";
import "../utils/Math.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Price Calculator Contract
* @notice The contract that calculates the options prices (the premiums)
* that are adjusted through the `ImpliedVolRate` parameter.
**/
contract PriceCalculatorUtilization is IPriceCalculator, Ownable {
using HegicMath for uint256;
uint256 public impliedVolRate;
uint256 internal constant PRICE_DECIMALS = 1e8;
uint256 internal constant PRICE_MODIFIER_DECIMALS = 1e8;
uint256 public utilizationRate = 0;
uint256 public settlementFeeShare = 24;
AggregatorV3Interface public priceProvider;
IHegicPool pool;
constructor(
uint256 initialRate,
AggregatorV3Interface _priceProvider,
IHegicPool _pool
) {
pool = _pool;
priceProvider = _priceProvider;
impliedVolRate = initialRate;
}
/**
* @notice Used for adjusting the options prices (the premiums)
* while balancing the asset's implied volatility rate.
* @param value New IVRate value
**/
function setImpliedVolRate(uint256 value) external onlyOwner {
impliedVolRate = value;
}
/**
* @notice Used for adjusting the options prices (the premiums)
* while balancing the asset's implied volatility rate.
* @param value New IVRate value
**/
function setSettlementFeeShare(uint256 value) external onlyOwner {
require(value <= 100, "The value is too large");
settlementFeeShare = value;
}
/**
* @notice Used for updating utilizationRate value
* @param value New utilizationRate value
**/
function setUtilizationRate(uint256 value) external onlyOwner {
utilizationRate = value;
}
/**
* @notice Used for calculating the options prices
* @param period The option period in seconds (1 days <= period <= 90 days)
* @param amount The option size
* @param strike The option strike
* @return settlementFee The part of the premium that
* is distributed among the HEGIC staking participants
* @return premium The part of the premium that
* is distributed among the liquidity providers
**/
function calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) public view override returns (uint256 settlementFee, uint256 premium) {
uint256 currentPrice = _currentPrice();
if (strike == 0) strike = currentPrice;
require(
strike == currentPrice,
"Only ATM options are currently available"
);
uint256 total = _calculatePeriodFee(amount, period);
settlementFee = (total * settlementFeeShare) / 100;
premium = total - settlementFee;
}
/**
* @notice Calculates and prices in the time value of the option
* @param amount Option size
* @param period The option period in seconds (1 days <= period <= 90 days)
* @return fee The premium size to be paid
**/
function _calculatePeriodFee(uint256 amount, uint256 period)
internal
view
virtual
returns (uint256 fee)
{
return
(amount * _priceModifier(amount, period, pool)) /
PRICE_DECIMALS /
PRICE_MODIFIER_DECIMALS;
}
/**
* @notice Calculates `periodFee` of the option
* @param amount The option size
* @param period The option period in seconds (1 days <= period <= 90 days)
**/
function _priceModifier(
uint256 amount,
uint256 period,
IHegicPool pool
) internal view returns (uint256 iv) {
uint256 poolBalance = pool.totalBalance();
require(poolBalance > 0, "Pool Error: The pool is empty");
iv = impliedVolRate * period.sqrt();
uint256 lockedAmount = pool.lockedAmount() + amount;
uint256 utilization = (lockedAmount * 100e8) / poolBalance;
if (utilization > 40e8) {
iv += (iv * (utilization - 40e8) * utilizationRate) / 40e16;
}
}
/**
* @notice Used for requesting the current price of the asset
* using the ChainLink data feeds contracts.
* See https://feeds.chain.link/
* @return price Price
**/
function _currentPrice() internal view returns (uint256 price) {
(, int256 latestPrice, , , ) = priceProvider.latestRoundData();
price = uint256(latestPrice);
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
library HegicMath {
/**
* @dev Calculates a square root of the number.
* Responds with an "invalid opcode" at uint(-1).
**/
function sqrt(uint256 x) internal pure returns (uint256 result) {
result = x;
uint256 k = (x >> 1) + 1;
while (k < result) (result, k) = (k, (x / k + k) >> 1);
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "../Interfaces/Interfaces.sol";
import "../utils/Math.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Price Calculator Contract
* @notice The contract that calculates the options prices (the premiums)
* that are adjusted through the `ImpliedVolRate` parameter.
**/
contract PriceCalculator is IPriceCalculator, Ownable {
using HegicMath for uint256;
uint256 public impliedVolRate;
uint256 internal immutable PRICE_DECIMALS;
uint256 internal constant IVL_DECIMALS = 1e8;
uint256 public settlementFeeShare = 0;
uint256 public maxPeriod = 30 days;
AggregatorV3Interface public priceProvider;
constructor(uint256 initialRate, AggregatorV3Interface _priceProvider) {
priceProvider = _priceProvider;
impliedVolRate = initialRate;
PRICE_DECIMALS = 10**priceProvider.decimals();
}
/**
* @notice Used for adjusting the options prices (the premiums)
* while balancing the asset's implied volatility rate.
* @param value New IVRate value
**/
function setImpliedVolRate(uint256 value) external onlyOwner {
impliedVolRate = value;
}
/**
* @notice Used for adjusting the options prices (the premiums)
* while balancing the asset's implied volatility rate.
* @param value New settlementFeeShare value
**/
function setSettlementFeeShare(uint256 value) external onlyOwner {
require(value <= 100, "The value is too large");
settlementFeeShare = value;
}
function setMaxPeriod(uint256 value) external onlyOwner {
maxPeriod = value;
}
/**
* @notice Used for calculating the options prices
* @param period The option period in seconds (1 days <= period <= 90 days)
* @param amount The option size
* @param strike The option strike
* @return settlementFee The part of the premium that
* is distributed among the HEGIC staking participants
* @return premium The part of the premium that
* is distributed among the liquidity providers
**/
function calculateTotalPremium(
uint256 period,
uint256 amount,
uint256 strike
) public view override returns (uint256 settlementFee, uint256 premium) {
uint256 currentPrice = _currentPrice();
if (strike == 0) strike = currentPrice;
require(period <= maxPeriod, "PriceCalculator: Period is too long");
require(
strike == currentPrice,
"Only ATM options are currently available"
);
uint256 total = _calculatePeriodFee(amount, period);
settlementFee = (total * settlementFeeShare) / 100;
premium = total - settlementFee;
}
/**
* @notice Calculates and prices in the time value of the option
* @param amount Option size
* @param period The option period in seconds (1 days <= period <= 90 days)
* @return fee The premium size to be paid
**/
function _calculatePeriodFee(uint256 amount, uint256 period)
internal
view
virtual
returns (uint256 fee)
{
return
(amount * impliedVolRate * period.sqrt()) /
PRICE_DECIMALS /
IVL_DECIMALS;
}
/**
* @notice Used for requesting the current price of the asset
* using the ChainLink data feeds contracts.
* See https://feeds.chain.link/
* @return price Price
**/
function _currentPrice() internal view returns (uint256 price) {
(, int256 latestPrice, , , ) = priceProvider.latestRoundData();
price = uint256(latestPrice);
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "./SimplePriceCalculator.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Price Calculator Contract
* @notice The contract that calculates the options prices (the premiums)
* that are adjusted through the `ImpliedVolRate` parameter.
**/
contract AdaptivePriceCalculator is PriceCalculator {
IHegicPool public immutable pool;
uint256 internal constant PRICE_MODIFIER_DECIMALS = 1e8;
uint256 public utilizationRate = 0;
// uint256 public utilizationRate = 1e8;
constructor(
uint256 initialRate,
AggregatorV3Interface _priceProvider,
IHegicPool _pool
) PriceCalculator(initialRate, _priceProvider) {
pool = _pool;
}
/**
* @notice Calculates and prices in the time value of the option
* @param amount Option size
* @param period The option period in seconds (1 days <= period <= 90 days)
* @return fee The premium size to be paid
**/
function _calculatePeriodFee(uint256 amount, uint256 period)
internal
view
override
returns (uint256 fee)
{
return
(super._calculatePeriodFee(amount, period) *
_priceModifier(amount)) / PRICE_MODIFIER_DECIMALS;
}
/**
* @notice Calculates `periodFee` of the option
* @param amount The option size
**/
function _priceModifier(uint256 amount) internal view returns (uint256 iv) {
uint256 poolBalance = pool.totalBalance();
if (poolBalance == 0) return PRICE_MODIFIER_DECIMALS;
uint256 lockedAmount = pool.lockedAmount() + _lockedAmount(amount);
uint256 utilization = (lockedAmount * 100e8) / poolBalance;
if (utilization < 40e8) return PRICE_MODIFIER_DECIMALS;
return
PRICE_MODIFIER_DECIMALS +
(PRICE_MODIFIER_DECIMALS * (utilization - 40e8) * utilizationRate) /
60e16;
}
function _lockedAmount(uint256 amount)
internal
view
virtual
returns (uint256)
{
return amount;
}
function setUtilizationRate(uint256 value) external onlyOwner {
utilizationRate = value;
}
}
contract AdaptivePutPriceCalculator is AdaptivePriceCalculator {
uint256 private immutable SpotDecimals;
uint256 private constant TokenDecimals = 1e6;
constructor(
uint256 initialRate,
AggregatorV3Interface _priceProvider,
IHegicPool _pool,
uint8 spotDecimals
) AdaptivePriceCalculator(initialRate, _priceProvider, _pool) {
SpotDecimals = 10**spotDecimals;
}
function _lockedAmount(uint256 amount)
internal
view
override
returns (uint256)
{
return
(amount *
pool.collateralizationRatio() *
_currentPrice() *
TokenDecimals) /
SpotDecimals /
1e8 /
100;
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "../Interfaces/Interfaces.sol";
import "../Interfaces/IOptionsManager.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Facade Contract
* @notice The contract that calculates the options prices,
* conducts the process of buying options, converts the premiums
* into the token that the pool is denominated in and grants
* permissions to the contracts such as GSN (Gas Station Network).
**/
contract Facade is Ownable {
using SafeERC20 for IERC20;
IWETH public immutable WETH;
IUniswapV2Router01 public immutable exchange;
IOptionsManager public immutable optionsManager;
address public _trustedForwarder;
constructor(
IWETH weth,
IUniswapV2Router01 router,
IOptionsManager manager,
address trustedForwarder
) {
WETH = weth;
exchange = router;
_trustedForwarder = trustedForwarder;
optionsManager = manager;
}
/**
* @notice Used for calculating the option price (the premium) and using
* the swap router (if needed) to convert the tokens with which the user
* pays the premium into the token in which the pool is denominated.
* @param period The option period
* @param amount The option size
* @param strike The option strike
* @param total The total premium
* @param baseTotal The part of the premium that
* is distributed among the liquidity providers
* @param settlementFee The part of the premium that
* is distributed among the HEGIC staking participants
**/
function getOptionPrice(
IHegicPool pool,
uint256 period,
uint256 amount,
uint256 strike,
address[] calldata swappath
)
public
view
returns (
uint256 total,
uint256 baseTotal,
uint256 settlementFee,
uint256 premium
)
{
(uint256 _baseTotal, uint256 baseSettlementFee, uint256 basePremium) =
getBaseOptionCost(pool, period, amount, strike);
if (swappath.length > 1)
total = exchange.getAmountsIn(_baseTotal, swappath)[0];
else total = _baseTotal;
baseTotal = _baseTotal;
settlementFee = (total * baseSettlementFee) / baseTotal;
premium = (total * basePremium) / baseTotal;
}
/**
* @notice Used for calculating the option price (the premium)
* in the token in which the pool is denominated.
* @param period The option period
* @param amount The option size
* @param strike The option strike
**/
function getBaseOptionCost(
IHegicPool pool,
uint256 period,
uint256 amount,
uint256 strike
)
public
view
returns (
uint256 total,
uint256 settlementFee,
uint256 premium
)
{
(settlementFee, premium) = pool.calculateTotalPremium(
period,
amount,
strike
);
total = premium + settlementFee;
}
/**
* @notice Used for approving the pools contracts addresses.
**/
function poolApprove(IHegicPool pool) external {
pool.token().safeApprove(address(pool), 0);
pool.token().safeApprove(address(pool), type(uint256).max);
}
/**
* @notice Used for buying the option contract and converting
* the buyer's tokens (the total premium) into the token
* in which the pool is denominated.
* @param period The option period
* @param amount The option size
* @param strike The option strike
* @param acceptablePrice The highest acceptable price
**/
function createOption(
IHegicPool pool,
uint256 period,
uint256 amount,
uint256 strike,
address[] calldata swappath,
uint256 acceptablePrice
) external {
address buyer = _msgSender();
(uint256 optionPrice, uint256 rawOptionPrice, , ) =
getOptionPrice(pool, period, amount, strike, swappath);
require(
optionPrice <= acceptablePrice,
"Facade Error: The option price is too high"
);
IERC20 paymentToken = IERC20(swappath[0]);
paymentToken.safeTransferFrom(buyer, address(this), optionPrice);
if (swappath.length > 1) {
if (
paymentToken.allowance(address(this), address(exchange)) <
optionPrice
) {
paymentToken.safeApprove(address(exchange), 0);
paymentToken.safeApprove(address(exchange), type(uint256).max);
}
exchange.swapTokensForExactTokens(
rawOptionPrice,
optionPrice,
swappath,
address(this),
block.timestamp
);
}
pool.sellOption(buyer, period, amount, strike);
}
/**
* @notice Used for converting the liquidity provider's Ether (ETH)
* into Wrapped Ether (WETH) and providing the funds into the pool.
* @param hedged The liquidity tranche type: hedged or unhedged (classic)
**/
function provideEthToPool(
IHegicPool pool,
bool hedged,
uint256 minShare
) external payable returns (uint256) {
WETH.deposit{value: msg.value}();
if (WETH.allowance(address(this), address(pool)) < msg.value)
WETH.approve(address(pool), type(uint256).max);
return pool.provideFrom(msg.sender, msg.value, hedged, minShare);
}
/**
* @notice Unlocks the array of options.
* @param optionIDs The array of options
**/
function unlockAll(IHegicPool pool, uint256[] calldata optionIDs) external {
uint256 arrayLength = optionIDs.length;
for (uint256 i = 0; i < arrayLength; i++) {
pool.unlock(optionIDs[i]);
}
}
/**
* @notice Used for granting the GSN (Gas Station Network) contract
* the permission to pay the gas (transaction) fees for the users.
* @param forwarder GSN (Gas Station Network) contract address
**/
function isTrustedForwarder(address forwarder) public view returns (bool) {
return forwarder == _trustedForwarder;
}
function claimAllStakingProfits(
IHegicStaking[] calldata stakings,
address account
) external {
uint256 arrayLength = stakings.length;
for (uint256 i = 0; i < arrayLength; i++) {
IHegicStaking s = stakings[i];
if (s.profitOf(account) > 0) s.claimProfits(account);
}
}
function _msgSender() internal view override returns (address signer) {
signer = msg.sender;
if (msg.data.length >= 20 && isTrustedForwarder(signer)) {
assembly {
signer := shr(96, calldataload(sub(calldatasize(), 20)))
}
}
}
function exercise(uint256 optionId) external {
require(
optionsManager.isApprovedOrOwner(_msgSender(), optionId),
"Facade Error: _msgSender is not eligible to exercise the option"
);
IHegicPool(optionsManager.tokenPool(optionId)).exercise(optionId);
}
function versionRecipient() external pure returns (string memory) {
return "2.2.2";
}
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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;
}
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, 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');
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "./Interfaces/IOptionsManager.sol";
import "./Interfaces/Interfaces.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Exerciser Contract
* @notice The contract that allows to automatically exercise options half an hour before expiration
**/
contract Exerciser {
IOptionsManager immutable optionsManager;
constructor(IOptionsManager manager) {
optionsManager = manager;
}
function exercise(uint256 optionId) external {
IHegicPool pool = IHegicPool(optionsManager.tokenPool(optionId));
(, , , , uint256 expired, ) = pool.options(optionId);
require(
block.timestamp > expired - 30 minutes,
"Facade Error: Automatically exercise for this option is not available yet"
);
pool.exercise(optionId);
}
}
pragma solidity 0.8.6;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* Hegic
* Copyright (C) 2021 Hegic Protocol
*
* 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/>.
**/
import "./HegicPool.sol";
/**
* @author 0mllwntrmt3
* @title Hegic Protocol V8888 Call Liquidity Pool Contract
* @notice The Call Liquidity Pool Contract
**/
contract HegicCALL is HegicPool {
/**
* @param name The pool contract name
* @param symbol The pool ticker for the ERC721 options
**/
constructor(
IERC20 _token,
string memory name,
string memory symbol,
IOptionsManager manager,
IPriceCalculator _pricer,
IHegicStaking _settlementFeeRecipient,
AggregatorV3Interface _priceProvider
)
HegicPool(
_token,
name,
symbol,
manager,
_pricer,
_settlementFeeRecipient,
_priceProvider
)
{}
function _profitOf(Option memory option)
internal
view
override
returns (uint256 amount)
{
uint256 currentPrice = _currentPrice();
if (currentPrice < option.strike) return 0;
return ((currentPrice - option.strike) * option.amount) / currentPrice;
}
} | Calculates and prices in the time value of the option amount Option size period The option period in seconds (1 days <= period <= 90 days) return fee The premium size to be paid/ | function _calculatePeriodFee(uint256 amount, uint256 period)
internal
view
virtual
returns (uint256 fee)
{
return
(amount * _priceModifier(amount, period, pool)) /
PRICE_DECIMALS /
PRICE_MODIFIER_DECIMALS;
}
| 11,680,257 |
./full_match/137/0x1d87438CD3c7d0B9d18F899aa831D1DDaBd3AB83/sources/src/MintpadERC1155Evolve.sol | Set the number to burn to get a evolved NFT | function setNumberToBurn(uint256 _amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
numberToBurn = _amount;
}
| 3,746,740 |
pragma solidity >=0.5.0 <0.6.0;
contract LockRedeem {
//Flag to pause and unpause contract
bool ACTIVE = false;
// numValidators holds the total number of validators
uint public numValidators;
// mapping to store the validators to the ether they have earne from signing trasactions
struct ValidatorDetails {
uint votingPower;
uint validatorFee;
}
mapping (address => ValidatorDetails) public validators;
address [] initialValidatorList;
// Require this amount of signatures to push a proposal through,Set only in constructor
uint votingThreshold;
uint activeThreshold;
//the base cost of a transaction (21000 gas)
//the cost of a contract deployment (32000 gas) [Not relevant for sign trasaction]
//the cost for every zero byte of data or code for a transaction.
//the cost of every non-zero byte of data or code for a transaction.
uint trasactionCost = 23192 ;
uint additionalGasCost = 37692 ;
uint redeem_gas_charge = 1000000000000000000;
// numValidators holds the total number of validators
uint public migrationSignatures;
// mapping to store the validators to a bool ,which accounts to the fact they have signed.
mapping (address => bool) public migrationSigners;
mapping (address => uint) migrationAddressMap;
address [] migrationAddressList;
uint constant DEFAULT_VALIDATOR_POWER = 50;
uint constant MIN_VALIDATORS = 0;
uint256 LOCK_PERIOD = 28800;
struct RedeemTX {
address payable recipient;
mapping (address => bool) votes;
uint256 amount;
uint256 signature_count;
bool isCompleted ;
uint256 until;
uint redeemFee;
}
mapping (address => RedeemTX) redeemRequests;
event RedeemRequest(
address indexed recepient,
uint256 amount_requested
);
event ValidatorSignedRedeem(
address indexed recipient,
address validator_addresss,
uint256 amount,
uint gasReturned
);
event Lock(
address sender,
uint256 amount_received
);
event ValidatorMigrated(
address validator,
address NewSmartContractAddress
);
event AddValidator(
address indexed _address
);
modifier isActive() {
require(ACTIVE);
_;
}
modifier isInactive() {
require(!ACTIVE);
_;
}
modifier onlyValidator() {
require(validators[msg.sender].votingPower >0 ,"validator not present in List");
_; // Continues control flow after this is validates
}
function isValidator(address v) public view returns (bool) {
return validators[v].votingPower > 0;
}
// function migrate (address newSmartContractAddress) public onlyValidator {
// require(migrationSigners[msg.sender]==false,"Validator Signed already");
// migrationSigners[msg.sender] = true ;
// //MigratefromOl can be used to migrate validator to new contract address.
// (bool status,) = newSmartContractAddress.call(abi.encodePacked(bytes4(keccak256("MigrateFromOld()"))));
// require(status,"Unable to Migrate Validator new Smart contract");
// emit ValidatorMigrated(msg.sender,newSmartContractAddress);
// //migrationSignatures = migrationSignatures + 1;
// if(migrationAddressMap[newSmartContractAddress]==0)
// {
// migrationAddressList.push(newSmartContractAddress);
// }
// migrationAddressMap[newSmartContractAddress] += 1;
//
// if (migrationAddressMap[newSmartContractAddress] > activeThreshold) {
// ACTIVE = false ;
// }
// if (migrationAddressMap[newSmartContractAddress] > votingThreshold) {
// (bool success, ) = maxVotedAddress.call.value(address(this).balance)("");
// }
// Global flag ,needs to be set only once
// if (migrationSignatures == activeThreshold) {
// ACTIVE = false ;
// }
//
//
// // Trasfer needs to be done only once
// if (migrationSignatures == votingThreshold) {
// uint voteCount = 0 ;
// address maxVotedAddress ;
// for(uint i=0;i< migrationAddressList.length;i++){
// if (migrationAddressMap[migrationAddressList[i]] > voteCount){
// voteCount = migrationAddressMap[migrationAddressList[i]];
// maxVotedAddress = migrationAddressList[i];
// }
// }
// if (voteCount >= votingThreshold) {
// (bool success, ) = maxVotedAddress.call.value(address(this).balance)("");
// }
// require(success, "Transfer failed");
// }
// }
// function called by user
function lock() payable public isActive {
require(msg.value >= 0, "Must pay a balance more than 0");
emit Lock(msg.sender,msg.value);
}
// function called by user
function redeem(uint256 amount_) payable public isActive {
require(redeemRequests[msg.sender].amount == uint256(0));
require(msg.value >= redeem_gas_charge,"Redeem Fees not supplied");
require(amount_ > 0, "amount should be bigger than 0");
require(redeemRequests[msg.sender].until < block.number, "request is locked, not available");
redeemRequests[msg.sender].isCompleted = false;
redeemRequests[msg.sender].signature_count = uint256(0);
redeemRequests[msg.sender].recipient = msg.sender;
redeemRequests[msg.sender].amount = amount_ ;
redeemRequests[msg.sender].redeemFee += msg.value;
redeemRequests[msg.sender].until = block.number + LOCK_PERIOD;
emit RedeemRequest(redeemRequests[msg.sender].recipient,redeemRequests[msg.sender].amount);
}
//function called by Validators using protocol to sign on RedeemRequests
function sign(uint amount_, address payable recipient_) public isActive onlyValidator {
uint startGas = gasleft();
require(!redeemRequests[recipient_].isCompleted, "redeem request is completed");
require(redeemRequests[recipient_].amount == amount_,"redeem amount is different" );
require(!redeemRequests[recipient_].votes[msg.sender]);
require(redeemRequests[recipient_].until > block.number, "request has expired");
// update votes
redeemRequests[recipient_].votes[msg.sender] = true;
redeemRequests[recipient_].signature_count += 1;
//validators[msg.sender].validatorFee = validators[msg.sender].validatorFee + tx.gasprice * avg_gas;
// if threshold is reached then transfer the amount
if (redeemRequests[recipient_].signature_count >= votingThreshold ) {
(bool success, ) = redeemRequests[recipient_].recipient.call.value((redeemRequests[recipient_].amount))("");
require(success, "Transfer failed.");
redeemRequests[recipient_].amount = 0;
redeemRequests[recipient_].isCompleted = true;
}
// Trasaction Cost is a an average trasaction cost .
// additionalGasCost is the extra gas used by the lines of code after gas calculation is done.
// This is an approximate calcualtion and actuall cost might vary sightly .
uint gasUsed = startGas - gasleft() + trasactionCost + additionalGasCost ;
validators[msg.sender].validatorFee = gasUsed;
uint gasFee = gasUsed * tx.gasprice;
(bool success, ) = msg.sender.call.value(gasFee)("");
require(success, "Transfer back to validator failed");
redeemRequests[recipient_].redeemFee -= gasFee;
emit ValidatorSignedRedeem(recipient_, msg.sender, amount_,gasUsed);
}
function validatorFee() public view isActive onlyValidator returns(uint) {
return validators[msg.sender].validatorFee;
}
function collectUserFee() public isActive{
require(redeemRequests[msg.sender].isCompleted = true, "request signing is still in progress");
(bool success, ) = msg.sender.call.value(redeemRequests[msg.sender].redeemFee)("");
require(success, "Transfer failed.");
}
// Function used by protocol and wallet
function isredeemAvailable (address recepient_) public view returns (bool){
return redeemRequests[recepient_].until == 0 || redeemRequests[recepient_].until < block.number;
}
// Function used by protocol
function hasValidatorSigned(address recipient_) public view returns(bool) {
return redeemRequests[recipient_].votes[msg.sender];
}
// Function used by protocol
function verifyRedeem(address recipient_) public view returns(bool){
return redeemRequests[recipient_].isCompleted;
}
// Function used by protocol
function getSignatureCount(address recipient_) public view returns(uint256){
return redeemRequests[recipient_].signature_count;
}
function getTotalEthBalance() public view returns(uint) {
return address(this).balance ;
}
function getOLTEthAddress() public view returns(address){
return address(this);
}
function addValidator(address v) internal {
validators[v].votingPower = DEFAULT_VALIDATOR_POWER;
validators[v].validatorFee = 0;
numValidators += 1;
emit AddValidator(v);
}
}
| function called by Validators using protocol to sign on RedeemRequests update votesvalidators[msg.sender].validatorFee = validators[msg.sender].validatorFee + tx.gasprice avg_gas; if threshold is reached then transfer the amount | function sign(uint amount_, address payable recipient_) public isActive onlyValidator {
uint startGas = gasleft();
require(!redeemRequests[recipient_].isCompleted, "redeem request is completed");
require(redeemRequests[recipient_].amount == amount_,"redeem amount is different" );
require(!redeemRequests[recipient_].votes[msg.sender]);
require(redeemRequests[recipient_].until > block.number, "request has expired");
redeemRequests[recipient_].votes[msg.sender] = true;
redeemRequests[recipient_].signature_count += 1;
if (redeemRequests[recipient_].signature_count >= votingThreshold ) {
(bool success, ) = redeemRequests[recipient_].recipient.call.value((redeemRequests[recipient_].amount))("");
require(success, "Transfer failed.");
redeemRequests[recipient_].amount = 0;
redeemRequests[recipient_].isCompleted = true;
}
validators[msg.sender].validatorFee = gasUsed;
uint gasFee = gasUsed * tx.gasprice;
(bool success, ) = msg.sender.call.value(gasFee)("");
require(success, "Transfer back to validator failed");
redeemRequests[recipient_].redeemFee -= gasFee;
emit ValidatorSignedRedeem(recipient_, msg.sender, amount_,gasUsed);
}
| 12,877,130 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { RolesMods } from "./RolesMods.sol";
import { RolesLib } from "./RolesLib.sol";
import { ADMIN } from "../../../shared/roles.sol";
contract RolesFacet is RolesMods {
/**
* @notice Checks if an account has a specific role.
* @param role Encoding of the role to check.
* @param account Address to check the {role} for.
*/
function hasRole(bytes32 role, address account)
external
view
returns (bool)
{
return RolesLib.hasRole(role, account);
}
/**
* @notice Grants an account a new role.
* @param role Encoding of the role to give.
* @param account Address to give the {role} to.
*
* Requirements:
* - Sender must be role admin.
*/
function grantRole(bytes32 role, address account)
external
authorized(ADMIN, msg.sender)
{
RolesLib.grantRole(role, account);
}
/**
* @notice Removes a role from an account.
* @param role Encoding of the role to remove.
* @param account Address to remove the {role} from.
*
* Requirements:
* - Sender must be role admin.
*/
function revokeRole(bytes32 role, address account)
external
authorized(ADMIN, msg.sender)
{
RolesLib.revokeRole(role, account);
}
/**
* @notice Removes a role from the sender.
* @param role Encoding of the role to remove.
*/
function renounceRole(bytes32 role) external {
RolesLib.revokeRole(role, msg.sender);
}
}
| Removes a role from an account. role Encoding of the role to remove. account Address to remove the {role} from. Requirements: - Sender must be role admin./ | function revokeRole(bytes32 role, address account)
external
authorized(ADMIN, msg.sender)
{
RolesLib.revokeRole(role, account);
}
| 5,446,998 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IERC20Ubiquity.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "./interfaces/IExcessDollarsDistributor.sol";
import "./interfaces/IMetaPool.sol";
import "./UbiquityAlgorithmicDollarManager.sol";
import "./SushiSwapPool.sol";
import "./libs/ABDKMathQuad.sol";
/// @title An excess dollar distributor which sends dollars to treasury,
/// lp rewards and inflation rewards
contract ExcessDollarsDistributor is IExcessDollarsDistributor {
using SafeERC20 for IERC20Ubiquity;
using SafeERC20 for IERC20;
using ABDKMathQuad for uint256;
using ABDKMathQuad for bytes16;
UbiquityAlgorithmicDollarManager public manager;
uint256 private immutable _minAmountToDistribute = 100 ether;
IUniswapV2Router02 private immutable _router =
IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiV2Router02
/// @param _manager the address of the manager contract so we can fetch variables
constructor(address _manager) {
manager = UbiquityAlgorithmicDollarManager(_manager);
}
function distributeDollars() external override {
//the excess dollars which were sent to this contract by the coupon manager
uint256 excessDollars =
IERC20Ubiquity(manager.dollarTokenAddress()).balanceOf(
address(this)
);
if (excessDollars > _minAmountToDistribute) {
address treasuryAddress = manager.treasuryAddress();
// curve uAD-3CRV liquidity pool
uint256 tenPercent =
excessDollars.fromUInt().div(uint256(10).fromUInt()).toUInt();
uint256 fiftyPercent =
excessDollars.fromUInt().div(uint256(2).fromUInt()).toUInt();
IERC20Ubiquity(manager.dollarTokenAddress()).safeTransfer(
treasuryAddress,
fiftyPercent
);
// convert uAD to uGOV-UAD LP on sushi and burn them
_governanceBuyBackLPAndBurn(tenPercent);
// convert remaining uAD to curve LP tokens
// and transfer the curve LP tokens to the bonding contract
_convertToCurveLPAndTransfer(
excessDollars - fiftyPercent - tenPercent
);
}
}
// swap half amount to uGOV
function _swapDollarsForGovernance(bytes16 amountIn)
internal
returns (uint256)
{
address[] memory path = new address[](2);
path[0] = manager.dollarTokenAddress();
path[1] = manager.governanceTokenAddress();
uint256[] memory amounts =
_router.swapExactTokensForTokens(
amountIn.toUInt(),
0,
path,
address(this),
block.timestamp + 100
);
return amounts[1];
}
// buy-back and burn uGOV
function _governanceBuyBackLPAndBurn(uint256 amount) internal {
bytes16 amountUAD = (amount.fromUInt()).div(uint256(2).fromUInt());
// we need to approve sushi router
IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove(
address(_router),
0
);
IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove(
address(_router),
amount
);
uint256 amountUGOV = _swapDollarsForGovernance(amountUAD);
IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove(
address(_router),
0
);
IERC20Ubiquity(manager.governanceTokenAddress()).safeApprove(
address(_router),
amountUGOV
);
// deposit liquidity and transfer to zero address (burn)
_router.addLiquidity(
manager.dollarTokenAddress(),
manager.governanceTokenAddress(),
amountUAD.toUInt(),
amountUGOV,
0,
0,
address(0),
block.timestamp + 100
);
}
// @dev convert to curve LP
// @param amount to convert to curve LP by swapping to 3CRV
// and deposit the 3CRV as liquidity to get uAD-3CRV LP tokens
// the LP token are sent to the bonding contract
function _convertToCurveLPAndTransfer(uint256 amount)
internal
returns (uint256)
{
// we need to approve metaPool
IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove(
manager.stableSwapMetaPoolAddress(),
0
);
IERC20Ubiquity(manager.dollarTokenAddress()).safeApprove(
manager.stableSwapMetaPoolAddress(),
amount
);
// swap amount of uAD => 3CRV
uint256 amount3CRVReceived =
IMetaPool(manager.stableSwapMetaPoolAddress()).exchange(
0,
1,
amount,
0
);
// approve metapool to transfer our 3CRV
IERC20(manager.curve3PoolTokenAddress()).safeApprove(
manager.stableSwapMetaPoolAddress(),
0
);
IERC20(manager.curve3PoolTokenAddress()).safeApprove(
manager.stableSwapMetaPoolAddress(),
amount3CRVReceived
);
// deposit liquidity
uint256 res =
IMetaPool(manager.stableSwapMetaPoolAddress()).add_liquidity(
[0, amount3CRVReceived],
0,
manager.bondingContractAddress()
);
// update TWAP price
return res;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title ERC20 Ubiquiti preset interface
/// @author Ubiquity Algorithmic Dollar
interface IERC20Ubiquity is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(address indexed _burned, uint256 _amount);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
/// @title A mechanism for distributing excess dollars to relevant places
interface IExcessDollarsDistributor {
function distributeDollars() external;
}
// SPDX-License-Identifier: UNLICENSED
// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !!
pragma solidity ^0.8.3;
interface IMetaPool {
event Transfer(
address indexed sender,
address indexed receiver,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event TokenExchange(
address indexed buyer,
int128 sold_id,
uint256 tokens_sold,
int128 bought_id,
uint256 tokens_bought
);
event TokenExchangeUnderlying(
address indexed buyer,
int128 sold_id,
uint256 tokens_sold,
int128 bought_id,
uint256 tokens_bought
);
event AddLiquidity(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 invariant,
uint256 token_supply
);
event RemoveLiquidity(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 token_supply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 token_amount,
uint256 coin_amount,
uint256 token_supply
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 invariant,
uint256 token_supply
);
event CommitNewAdmin(uint256 indexed deadline, address indexed admin);
event NewAdmin(address indexed admin);
event CommitNewFee(
uint256 indexed deadline,
uint256 fee,
uint256 admin_fee
);
event NewFee(uint256 fee, uint256 admin_fee);
event RampA(
uint256 old_A,
uint256 new_A,
uint256 initial_time,
uint256 future_time
);
event StopRampA(uint256 A, uint256 t);
function initialize(
string memory _name,
string memory _symbol,
address _coin,
uint256 _decimals,
uint256 _A,
uint256 _fee,
address _admin
) external;
function decimals() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function get_previous_balances() external view returns (uint256[2] memory);
function get_balances() external view returns (uint256[2] memory);
function get_twap_balances(
uint256[2] memory _first_balances,
uint256[2] memory _last_balances,
uint256 _time_elapsed
) external view returns (uint256[2] memory);
function get_price_cumulative_last()
external
view
returns (uint256[2] memory);
function admin_fee() external view returns (uint256);
function A() external view returns (uint256);
function A_precise() external view returns (uint256);
function get_virtual_price() external view returns (uint256);
function calc_token_amount(uint256[2] memory _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_token_amount(
uint256[2] memory _amounts,
bool _is_deposit,
bool _previous
) external view returns (uint256);
function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount)
external
returns (uint256);
function add_liquidity(
uint256[2] memory _amounts,
uint256 _min_mint_amount,
address _receiver
) external returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx,
uint256[2] memory _balances
) external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx,
uint256[2] memory _balances
) external view returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address _receiver
) external returns (uint256);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address _receiver
) external returns (uint256);
function remove_liquidity(
uint256 _burn_amount,
uint256[2] memory _min_amounts
) external returns (uint256[2] memory);
function remove_liquidity(
uint256 _burn_amount,
uint256[2] memory _min_amounts,
address _receiver
) external returns (uint256[2] memory);
function remove_liquidity_imbalance(
uint256[2] memory _amounts,
uint256 _max_burn_amount
) external returns (uint256);
function remove_liquidity_imbalance(
uint256[2] memory _amounts,
uint256 _max_burn_amount,
address _receiver
) external returns (uint256);
function calc_withdraw_one_coin(uint256 _burn_amount, int128 i)
external
view
returns (uint256);
function calc_withdraw_one_coin(
uint256 _burn_amount,
int128 i,
bool _previous
) external view returns (uint256);
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received
) external returns (uint256);
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received,
address _receiver
) external returns (uint256);
function ramp_A(uint256 _future_A, uint256 _future_time) external;
function stop_ramp_A() external;
function admin_balances(uint256 i) external view returns (uint256);
function withdraw_admin_fees() external;
function admin() external view returns (address);
function coins(uint256 arg0) external view returns (address);
function balances(uint256 arg0) external view returns (uint256);
function fee() external view returns (uint256);
function block_timestamp_last() external view returns (uint256);
function initial_A() external view returns (uint256);
function future_A() external view returns (uint256);
function initial_A_time() external view returns (uint256);
function future_A_time() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function balanceOf(address arg0) external view returns (uint256);
function allowance(address arg0, address arg1)
external
view
returns (uint256);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IUbiquityAlgorithmicDollar.sol";
import "./interfaces/ICurveFactory.sol";
import "./interfaces/IMetaPool.sol";
import "./TWAPOracle.sol";
/// @title A central config for the uAD system. Also acts as a central
/// access control manager.
/// @notice For storing constants. For storing variables and allowing them to
/// be changed by the admin (governance)
/// @dev This should be used as a central access control manager which other
/// contracts use to check permissions
contract UbiquityAlgorithmicDollarManager is AccessControl {
using SafeERC20 for IERC20;
bytes32 public constant UBQ_MINTER_ROLE = keccak256("UBQ_MINTER_ROLE");
bytes32 public constant UBQ_BURNER_ROLE = keccak256("UBQ_BURNER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant COUPON_MANAGER_ROLE = keccak256("COUPON_MANAGER");
bytes32 public constant BONDING_MANAGER_ROLE = keccak256("BONDING_MANAGER");
bytes32 public constant INCENTIVE_MANAGER_ROLE =
keccak256("INCENTIVE_MANAGER");
bytes32 public constant UBQ_TOKEN_MANAGER_ROLE =
keccak256("UBQ_TOKEN_MANAGER_ROLE");
address public twapOracleAddress;
address public debtCouponAddress;
address public dollarTokenAddress; // uAD
address public couponCalculatorAddress;
address public dollarMintingCalculatorAddress;
address public bondingShareAddress;
address public bondingContractAddress;
address public stableSwapMetaPoolAddress;
address public curve3PoolTokenAddress; // 3CRV
address public treasuryAddress;
address public governanceTokenAddress; // uGOV
address public sushiSwapPoolAddress; // sushi pool uAD-uGOV
address public masterChefAddress;
address public formulasAddress;
address public autoRedeemTokenAddress; // uAR
address public uarCalculatorAddress; // uAR calculator
//key = address of couponmanager, value = excessdollardistributor
mapping(address => address) private _excessDollarDistributors;
modifier onlyAdmin() {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"uADMGR: Caller is not admin"
);
_;
}
constructor(address _admin) {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(UBQ_MINTER_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
_setupRole(COUPON_MANAGER_ROLE, _admin);
_setupRole(BONDING_MANAGER_ROLE, _admin);
_setupRole(INCENTIVE_MANAGER_ROLE, _admin);
_setupRole(UBQ_TOKEN_MANAGER_ROLE, address(this));
}
// TODO Add a generic setter for extra addresses that needs to be linked
function setTwapOracleAddress(address _twapOracleAddress)
external
onlyAdmin
{
twapOracleAddress = _twapOracleAddress;
// to be removed
TWAPOracle oracle = TWAPOracle(twapOracleAddress);
oracle.update();
}
function setuARTokenAddress(address _uarTokenAddress) external onlyAdmin {
autoRedeemTokenAddress = _uarTokenAddress;
}
function setDebtCouponAddress(address _debtCouponAddress)
external
onlyAdmin
{
debtCouponAddress = _debtCouponAddress;
}
function setIncentiveToUAD(address _account, address _incentiveAddress)
external
onlyAdmin
{
IUbiquityAlgorithmicDollar(dollarTokenAddress).setIncentiveContract(
_account,
_incentiveAddress
);
}
function setDollarTokenAddress(address _dollarTokenAddress)
external
onlyAdmin
{
dollarTokenAddress = _dollarTokenAddress;
}
function setGovernanceTokenAddress(address _governanceTokenAddress)
external
onlyAdmin
{
governanceTokenAddress = _governanceTokenAddress;
}
function setSushiSwapPoolAddress(address _sushiSwapPoolAddress)
external
onlyAdmin
{
sushiSwapPoolAddress = _sushiSwapPoolAddress;
}
function setUARCalculatorAddress(address _uarCalculatorAddress)
external
onlyAdmin
{
uarCalculatorAddress = _uarCalculatorAddress;
}
function setCouponCalculatorAddress(address _couponCalculatorAddress)
external
onlyAdmin
{
couponCalculatorAddress = _couponCalculatorAddress;
}
function setDollarMintingCalculatorAddress(
address _dollarMintingCalculatorAddress
) external onlyAdmin {
dollarMintingCalculatorAddress = _dollarMintingCalculatorAddress;
}
function setExcessDollarsDistributor(
address debtCouponManagerAddress,
address excessCouponDistributor
) external onlyAdmin {
_excessDollarDistributors[
debtCouponManagerAddress
] = excessCouponDistributor;
}
function setMasterChefAddress(address _masterChefAddress)
external
onlyAdmin
{
masterChefAddress = _masterChefAddress;
}
function setFormulasAddress(address _formulasAddress) external onlyAdmin {
formulasAddress = _formulasAddress;
}
function setBondingShareAddress(address _bondingShareAddress)
external
onlyAdmin
{
bondingShareAddress = _bondingShareAddress;
}
function setStableSwapMetaPoolAddress(address _stableSwapMetaPoolAddress)
external
onlyAdmin
{
stableSwapMetaPoolAddress = _stableSwapMetaPoolAddress;
}
/**
@notice set the bonding bontract smart contract address
@dev bonding contract participants deposit curve LP token
for a certain duration to earn uGOV and more curve LP token
@param _bondingContractAddress bonding contract address
*/
function setBondingContractAddress(address _bondingContractAddress)
external
onlyAdmin
{
bondingContractAddress = _bondingContractAddress;
}
/**
@notice set the treasury address
@dev the treasury fund is used to maintain the protocol
@param _treasuryAddress treasury fund address
*/
function setTreasuryAddress(address _treasuryAddress) external onlyAdmin {
treasuryAddress = _treasuryAddress;
}
/**
@notice deploy a new Curve metapools for uAD Token uAD/3Pool
@dev From the curve documentation for uncollateralized algorithmic
stablecoins amplification should be 5-10
@param _curveFactory MetaPool factory address
@param _crvBasePool Address of the base pool to use within the new metapool.
@param _crv3PoolTokenAddress curve 3Pool token Address
@param _amplificationCoefficient amplification coefficient. The smaller
it is the closer to a constant product we are.
@param _fee Trade fee, given as an integer with 1e10 precision.
*/
function deployStableSwapPool(
address _curveFactory,
address _crvBasePool,
address _crv3PoolTokenAddress,
uint256 _amplificationCoefficient,
uint256 _fee
) external onlyAdmin {
// Create new StableSwap meta pool (uAD <-> 3Crv)
address metaPool =
ICurveFactory(_curveFactory).deploy_metapool(
_crvBasePool,
ERC20(dollarTokenAddress).name(),
ERC20(dollarTokenAddress).symbol(),
dollarTokenAddress,
_amplificationCoefficient,
_fee
);
stableSwapMetaPoolAddress = metaPool;
// Approve the newly-deployed meta pool to transfer this contract's funds
uint256 crv3PoolTokenAmount =
IERC20(_crv3PoolTokenAddress).balanceOf(address(this));
uint256 uADTokenAmount =
IERC20(dollarTokenAddress).balanceOf(address(this));
// safe approve revert if approve from non-zero to non-zero allowance
IERC20(_crv3PoolTokenAddress).safeApprove(metaPool, 0);
IERC20(_crv3PoolTokenAddress).safeApprove(
metaPool,
crv3PoolTokenAmount
);
IERC20(dollarTokenAddress).safeApprove(metaPool, 0);
IERC20(dollarTokenAddress).safeApprove(metaPool, uADTokenAmount);
// coin at index 0 is uAD and index 1 is 3CRV
require(
IMetaPool(metaPool).coins(0) == dollarTokenAddress &&
IMetaPool(metaPool).coins(1) == _crv3PoolTokenAddress,
"uADMGR: COIN_ORDER_MISMATCH"
);
// Add the initial liquidity to the StableSwap meta pool
uint256[2] memory amounts =
[
IERC20(dollarTokenAddress).balanceOf(address(this)),
IERC20(_crv3PoolTokenAddress).balanceOf(address(this))
];
// set curve 3Pool address
curve3PoolTokenAddress = _crv3PoolTokenAddress;
IMetaPool(metaPool).add_liquidity(amounts, 0, msg.sender);
}
function getExcessDollarsDistributor(address _debtCouponManagerAddress)
external
view
returns (address)
{
return _excessDollarDistributors[_debtCouponManagerAddress];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "./UbiquityAlgorithmicDollarManager.sol";
contract SushiSwapPool {
IUniswapV2Factory public factory =
IUniswapV2Factory(0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac);
UbiquityAlgorithmicDollarManager public manager;
IUniswapV2Pair public pair;
constructor(address _manager) {
manager = UbiquityAlgorithmicDollarManager(_manager);
require(
manager.dollarTokenAddress() != address(0),
"Dollar address not set"
);
require(
manager.governanceTokenAddress() != address(0),
"uGOV Address not set"
);
// check if pair already exist
address pool =
factory.getPair(
manager.dollarTokenAddress(),
manager.governanceTokenAddress()
);
if (pool == address(0)) {
pool = factory.createPair(
manager.dollarTokenAddress(),
manager.governanceTokenAddress()
);
}
pair = IUniswapV2Pair(pool);
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math Quad Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with IEEE 754
* quadruple-precision binary floating-point numbers (quadruple precision
* numbers). As long as quadruple precision numbers are 16-bytes long, they are
* represented by bytes16 type.
*/
library ABDKMathQuad {
/*
* 0.
*/
bytes16 private constant _POSITIVE_ZERO =
0x00000000000000000000000000000000;
/*
* -0.
*/
bytes16 private constant _NEGATIVE_ZERO =
0x80000000000000000000000000000000;
/*
* +Infinity.
*/
bytes16 private constant _POSITIVE_INFINITY =
0x7FFF0000000000000000000000000000;
/*
* -Infinity.
*/
bytes16 private constant _NEGATIVE_INFINITY =
0xFFFF0000000000000000000000000000;
/*
* Canonical NaN value.
*/
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
/**
* Convert signed 256-bit integer number into quadruple precision number.
*
* @param x signed 256-bit integer number
* @return quadruple precision number
*/
function fromInt(int256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16383 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 256-bit integer number
* rounding towards zero. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 256-bit integer number
*/
function toInt(bytes16 x) internal pure returns (int256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16638); // Overflow
if (exponent < 16383) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(
result <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(result); // We rely on overflow behavior here
} else {
require(
result <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(result);
}
}
}
/**
* Convert unsigned 256-bit integer number into quadruple precision number.
*
* @param x unsigned 256-bit integer number
* @return quadruple precision number
*/
function fromUInt(uint256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
uint256 result = x;
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16383 + msb) << 112);
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into unsigned 256-bit integer number
* rounding towards zero. Revert on underflow. Note, that negative floating
* point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer
* without error, because they are rounded to zero.
*
* @param x quadruple precision number
* @return unsigned 256-bit integer number
*/
function toUInt(bytes16 x) internal pure returns (uint256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
if (exponent < 16383) return 0; // Underflow
require(uint128(x) < 0x80000000000000000000000000000000); // Negative
require(exponent <= 16638); // Overflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
return result;
}
}
/**
* Convert signed 128.128 bit fixed point number into quadruple precision
* number.
*
* @param x signed 128.128 bit fixed point number
* @return quadruple precision number
*/
function from128x128(int256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16255 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 128.128 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 128.128 bit fixed point number
*/
function to128x128(bytes16 x) internal pure returns (int256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16510); // Overflow
if (exponent < 16255) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16367) result >>= 16367 - exponent;
else if (exponent > 16367) result <<= exponent - 16367;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(
result <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(result); // We rely on overflow behavior here
} else {
require(
result <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(result);
}
}
}
/**
* Convert signed 64.64 bit fixed point number into quadruple precision
* number.
*
* @param x signed 64.64 bit fixed point number
* @return quadruple precision number
*/
function from64x64(int128 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint128(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16319 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 64.64 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 64.64 bit fixed point number
*/
function to64x64(bytes16 x) internal pure returns (int128) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x80000000000000000000000000000000);
return -int128(int256(result)); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(int256(result));
}
}
}
/**
* Convert octuple precision number into quadruple precision number.
*
* @param x octuple precision number
* @return quadruple precision number
*/
function fromOctuple(bytes32 x) internal pure returns (bytes16) {
unchecked {
bool negative =
x &
0x8000000000000000000000000000000000000000000000000000000000000000 >
0;
uint256 exponent = (uint256(x) >> 236) & 0x7FFFF;
uint256 significand =
uint256(x) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFFF) {
if (significand > 0) return NaN;
else return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
}
if (exponent > 278526)
return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else if (exponent < 245649)
return negative ? _NEGATIVE_ZERO : _POSITIVE_ZERO;
else if (exponent < 245761) {
significand =
(significand |
0x100000000000000000000000000000000000000000000000000000000000) >>
(245885 - exponent);
exponent = 0;
} else {
significand >>= 124;
exponent -= 245760;
}
uint128 result = uint128(significand | (exponent << 112));
if (negative) result |= 0x80000000000000000000000000000000;
return bytes16(result);
}
}
/**
* Convert quadruple precision number into octuple precision number.
*
* @param x quadruple precision number
* @return octuple precision number
*/
function toOctuple(bytes16 x) internal pure returns (bytes32) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF)
exponent = 0x7FFFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = mostSignificantBit(result);
result =
(result << (236 - msb)) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 245649 + msb;
}
} else {
result <<= 124;
exponent += 245760;
}
result |= exponent << 236;
if (uint128(x) >= 0x80000000000000000000000000000000)
result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
return bytes32(result);
}
}
/**
* Convert double precision number into quadruple precision number.
*
* @param x double precision number
* @return quadruple precision number
*/
function fromDouble(bytes8 x) internal pure returns (bytes16) {
unchecked {
uint256 exponent = (uint64(x) >> 52) & 0x7FF;
uint256 result = uint64(x) & 0xFFFFFFFFFFFFF;
if (exponent == 0x7FF)
exponent = 0x7FFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = mostSignificantBit(result);
result =
(result << (112 - msb)) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 15309 + msb;
}
} else {
result <<= 60;
exponent += 15360;
}
result |= exponent << 112;
if (x & 0x8000000000000000 > 0)
result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into double precision number.
*
* @param x quadruple precision number
* @return double precision number
*/
function toDouble(bytes16 x) internal pure returns (bytes8) {
unchecked {
bool negative = uint128(x) >= 0x80000000000000000000000000000000;
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 significand = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) {
if (significand > 0) return 0x7FF8000000000000;
// NaN
else
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000); // Infinity
}
if (exponent > 17406)
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000);
// Infinity
else if (exponent < 15309)
return
negative
? bytes8(0x8000000000000000) // -0
: bytes8(0x0000000000000000);
// 0
else if (exponent < 15361) {
significand =
(significand | 0x10000000000000000000000000000) >>
(15421 - exponent);
exponent = 0;
} else {
significand >>= 60;
exponent -= 15360;
}
uint64 result = uint64(significand | (exponent << 52));
if (negative) result |= 0x8000000000000000;
return bytes8(result);
}
}
/**
* Test whether given quadruple precision number is NaN.
*
* @param x quadruple precision number
* @return true if x is NaN, false otherwise
*/
function isNaN(bytes16 x) internal pure returns (bool) {
unchecked {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF >
0x7FFF0000000000000000000000000000;
}
}
/**
* Test whether given quadruple precision number is positive or negative
* infinity.
*
* @param x quadruple precision number
* @return true if x is positive or negative infinity, false otherwise
*/
function isInfinity(bytes16 x) internal pure returns (bool) {
unchecked {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ==
0x7FFF0000000000000000000000000000;
}
}
/**
* Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x
* is positive. Note that sign (-0) is zero. Revert if x is NaN.
*
* @param x quadruple precision number
* @return sign of x
*/
function sign(bytes16 x) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128(x) >= 0x80000000000000000000000000000000)
return -1;
else return 1;
}
}
/**
* Calculate sign (x - y). Revert if either argument is NaN, or both
* arguments are infinities of the same sign.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return sign (x - y)
*/
function cmp(bytes16 x, bytes16 y) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN
// Not infinities of the same sign
require(x != y || absoluteX < 0x7FFF0000000000000000000000000000);
if (x == y) return 0;
else {
bool negativeX =
uint128(x) >= 0x80000000000000000000000000000000;
bool negativeY =
uint128(y) >= 0x80000000000000000000000000000000;
if (negativeX) {
if (negativeY) return absoluteX > absoluteY ? -1 : int8(1);
else return -1;
} else {
if (negativeY) return 1;
else return absoluteX > absoluteY ? int8(1) : -1;
}
}
}
}
/**
* Test whether x equals y. NaN, infinity, and -infinity are not equal to
* anything.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return true if x equals to y, false otherwise
*/
function eq(bytes16 x, bytes16 y) internal pure returns (bool) {
unchecked {
if (x == y) {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF <
0x7FFF0000000000000000000000000000;
} else return false;
}
}
/**
* Calculate x + y. Special values behave in the following way:
*
* NaN + x = NaN for any x.
* Infinity + x = Infinity for any finite x.
* -Infinity + x = -Infinity for any finite x.
* Infinity + Infinity = Infinity.
* -Infinity + -Infinity = -Infinity.
* Infinity + -Infinity = -Infinity + Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function add(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x;
else return NaN;
} else return x;
} else if (yExponent == 0x7FFF) return y;
else {
bool xSign = uint128(x) >= 0x80000000000000000000000000000000;
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
bool ySign = uint128(y) >= 0x80000000000000000000000000000000;
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0)
return y == _NEGATIVE_ZERO ? _POSITIVE_ZERO : y;
else if (ySignifier == 0)
return x == _NEGATIVE_ZERO ? _POSITIVE_ZERO : x;
else {
int256 delta = int256(xExponent) - int256(yExponent);
if (xSign == ySign) {
if (delta > 112) return x;
else if (delta > 0) ySignifier >>= uint256(delta);
else if (delta < -112) return y;
else if (delta < 0) {
xSignifier >>= uint256(-delta);
xExponent = yExponent;
}
xSignifier += ySignifier;
if (xSignifier >= 0x20000000000000000000000000000) {
xSignifier >>= 1;
xExponent += 1;
}
if (xExponent == 0x7FFF)
return
xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else {
if (xSignifier < 0x10000000000000000000000000000)
xExponent = 0;
else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
return
bytes16(
uint128(
(
xSign
? 0x80000000000000000000000000000000
: 0
) |
(xExponent << 112) |
xSignifier
)
);
}
} else {
if (delta > 0) {
xSignifier <<= 1;
xExponent -= 1;
} else if (delta < 0) {
ySignifier <<= 1;
xExponent = yExponent - 1;
}
if (delta > 112) ySignifier = 1;
else if (delta > 1)
ySignifier =
((ySignifier - 1) >> uint256(delta - 1)) +
1;
else if (delta < -112) xSignifier = 1;
else if (delta < -1)
xSignifier =
((xSignifier - 1) >> uint256(-delta - 1)) +
1;
if (xSignifier >= ySignifier) xSignifier -= ySignifier;
else {
xSignifier = ySignifier - xSignifier;
xSign = ySign;
}
if (xSignifier == 0) return _POSITIVE_ZERO;
uint256 msb = mostSignificantBit(xSignifier);
if (msb == 113) {
xSignifier =
(xSignifier >> 1) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent += 1;
} else if (msb < 112) {
uint256 shift = 112 - msb;
if (xExponent > shift) {
xSignifier =
(xSignifier << shift) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent -= shift;
} else {
xSignifier <<= xExponent - 1;
xExponent = 0;
}
} else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF)
return
xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else
return
bytes16(
uint128(
(
xSign
? 0x80000000000000000000000000000000
: 0
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
}
}
/**
* Calculate x - y. Special values behave in the following way:
*
* NaN - x = NaN for any x.
* Infinity - x = Infinity for any finite x.
* -Infinity - x = -Infinity for any finite x.
* Infinity - -Infinity = Infinity.
* -Infinity - Infinity = -Infinity.
* Infinity - Infinity = -Infinity - -Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {return add(x, y ^ 0x80000000000000000000000000000000);}
}
/**
* Calculate x * y. Special values behave in the following way:
*
* NaN * x = NaN for any x.
* Infinity * x = Infinity for any finite positive x.
* Infinity * x = -Infinity for any finite negative x.
* -Infinity * x = -Infinity for any finite positive x.
* -Infinity * x = Infinity for any finite negative x.
* Infinity * 0 = NaN.
* -Infinity * 0 = NaN.
* Infinity * Infinity = Infinity.
* Infinity * -Infinity = -Infinity.
* -Infinity * Infinity = -Infinity.
* -Infinity * -Infinity = Infinity.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y)
return x ^ (y & 0x80000000000000000000000000000000);
else if (x ^ y == 0x80000000000000000000000000000000)
return x | y;
else return NaN;
} else {
if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
}
} else if (yExponent == 0x7FFF) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return y ^ (x & 0x80000000000000000000000000000000);
} else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
xSignifier *= ySignifier;
if (xSignifier == 0)
return
(x ^ y) & 0x80000000000000000000000000000000 > 0
? _NEGATIVE_ZERO
: _POSITIVE_ZERO;
xExponent += yExponent;
uint256 msb =
xSignifier >=
0x200000000000000000000000000000000000000000000000000000000
? 225
: xSignifier >=
0x100000000000000000000000000000000000000000000000000000000
? 224
: mostSignificantBit(xSignifier);
if (xExponent + msb < 16496) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb < 16608) {
// Subnormal
if (xExponent < 16496) xSignifier >>= 16496 - xExponent;
else if (xExponent > 16496)
xSignifier <<= xExponent - 16496;
xExponent = 0;
} else if (xExponent + msb > 49373) {
xExponent = 0x7FFF;
xSignifier = 0;
} else {
if (msb > 112) xSignifier >>= msb - 112;
else if (msb < 112) xSignifier <<= 112 - msb;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb - 16607;
}
return
bytes16(
uint128(
uint128(
(x ^ y) & 0x80000000000000000000000000000000
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
/**
* Calculate x / y. Special values behave in the following way:
*
* NaN / x = NaN for any x.
* x / NaN = NaN for any x.
* Infinity / x = Infinity for any finite non-negative x.
* Infinity / x = -Infinity for any finite negative x including -0.
* -Infinity / x = -Infinity for any finite non-negative x.
* -Infinity / x = Infinity for any finite negative x including -0.
* x / Infinity = 0 for any finite non-negative x.
* x / -Infinity = -0 for any finite non-negative x.
* x / Infinity = -0 for any finite non-negative x including -0.
* x / -Infinity = 0 for any finite non-negative x including -0.
*
* Infinity / Infinity = NaN.
* Infinity / -Infinity = -NaN.
* -Infinity / Infinity = -NaN.
* -Infinity / -Infinity = NaN.
*
* Division by zero behaves in the following way:
*
* x / 0 = Infinity for any finite positive x.
* x / -0 = -Infinity for any finite positive x.
* x / 0 = -Infinity for any finite negative x.
* x / -0 = Infinity for any finite negative x.
* 0 / 0 = NaN.
* 0 / -0 = NaN.
* -0 / 0 = NaN.
* -0 / -0 = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function div(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
} else if (yExponent == 0x7FFF) {
if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN;
else
return
_POSITIVE_ZERO |
((x ^ y) & 0x80000000000000000000000000000000);
} else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else
return
_POSITIVE_INFINITY |
((x ^ y) & 0x80000000000000000000000000000000);
} else {
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) {
if (xSignifier != 0) {
uint256 shift = 226 - mostSignificantBit(xSignifier);
xSignifier <<= shift;
xExponent = 1;
yExponent += shift - 114;
}
} else {
xSignifier =
(xSignifier | 0x10000000000000000000000000000) <<
114;
}
xSignifier = xSignifier / ySignifier;
if (xSignifier == 0)
return
(x ^ y) & 0x80000000000000000000000000000000 > 0
? _NEGATIVE_ZERO
: _POSITIVE_ZERO;
assert(xSignifier >= 0x1000000000000000000000000000);
uint256 msb =
xSignifier >= 0x80000000000000000000000000000
? mostSignificantBit(xSignifier)
: xSignifier >= 0x40000000000000000000000000000
? 114
: xSignifier >= 0x20000000000000000000000000000
? 113
: 112;
if (xExponent + msb > yExponent + 16497) {
// Overflow
xExponent = 0x7FFF;
xSignifier = 0;
} else if (xExponent + msb + 16380 < yExponent) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb + 16268 < yExponent) {
// Subnormal
if (xExponent + 16380 > yExponent)
xSignifier <<= xExponent + 16380 - yExponent;
else if (xExponent + 16380 < yExponent)
xSignifier >>= yExponent - xExponent - 16380;
xExponent = 0;
} else {
// Normal
if (msb > 112) xSignifier >>= msb - 112;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb + 16269 - yExponent;
}
return
bytes16(
uint128(
uint128(
(x ^ y) & 0x80000000000000000000000000000000
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
/**
* Calculate -x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function neg(bytes16 x) internal pure returns (bytes16) {
unchecked {return x ^ 0x80000000000000000000000000000000;}
}
/**
* Calculate |x|.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function abs(bytes16 x) internal pure returns (bytes16) {
unchecked {return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;}
}
/**
* Calculate square root of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function sqrt(bytes16 x) internal pure returns (bytes16) {
unchecked {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return _POSITIVE_ZERO;
bool oddExponent = xExponent & 0x1 == 0;
xExponent = (xExponent + 16383) >> 1;
if (oddExponent) {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 113;
else {
uint256 msb = mostSignificantBit(xSignifier);
uint256 shift = (226 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
} else {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 112;
else {
uint256 msb = mostSignificantBit(xSignifier);
uint256 shift = (225 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
}
uint256 r = 0x10000000000000000000000000000;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1; // Seven iterations should be enough
uint256 r1 = xSignifier / r;
if (r1 < r) r = r1;
return
bytes16(
uint128(
(xExponent << 112) |
(r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
}
/**
* Calculate binary logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function log_2(bytes16 x) internal pure returns (bytes16) {
unchecked {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else if (x == 0x3FFF0000000000000000000000000000)
return _POSITIVE_ZERO;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return _NEGATIVE_INFINITY;
bool resultNegative;
uint256 resultExponent = 16495;
uint256 resultSignifier;
if (xExponent >= 0x3FFF) {
resultNegative = false;
resultSignifier = xExponent - 0x3FFF;
xSignifier <<= 15;
} else {
resultNegative = true;
if (xSignifier >= 0x10000000000000000000000000000) {
resultSignifier = 0x3FFE - xExponent;
xSignifier <<= 15;
} else {
uint256 msb = mostSignificantBit(xSignifier);
resultSignifier = 16493 - msb;
xSignifier <<= 127 - msb;
}
}
if (xSignifier == 0x80000000000000000000000000000000) {
if (resultNegative) resultSignifier += 1;
uint256 shift =
112 - mostSignificantBit(resultSignifier);
resultSignifier <<= shift;
resultExponent -= shift;
} else {
uint256 bb = resultNegative ? 1 : 0;
while (
resultSignifier < 0x10000000000000000000000000000
) {
resultSignifier <<= 1;
resultExponent -= 1;
xSignifier *= xSignifier;
uint256 b = xSignifier >> 255;
resultSignifier += b ^ bb;
xSignifier >>= 127 + b;
}
}
return
bytes16(
uint128(
(
resultNegative
? 0x80000000000000000000000000000000
: 0
) |
(resultExponent << 112) |
(resultSignifier &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
}
/**
* Calculate natural logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function ln(bytes16 x) internal pure returns (bytes16) {
unchecked {return mul(log_2(x), 0x3FFE62E42FEFA39EF35793C7673007E5);}
}
/**
* Calculate 2^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function pow_2(bytes16 x) internal pure returns (bytes16) {
unchecked {
bool xNegative = uint128(x) > 0x80000000000000000000000000000000;
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF && xSignifier != 0) return NaN;
else if (xExponent > 16397)
return xNegative ? _POSITIVE_ZERO : _POSITIVE_INFINITY;
else if (xExponent < 16255)
return 0x3FFF0000000000000000000000000000;
else {
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xExponent > 16367) xSignifier <<= xExponent - 16367;
else if (xExponent < 16367) xSignifier >>= 16367 - xExponent;
if (
xNegative &&
xSignifier > 0x406E00000000000000000000000000000000
) return _POSITIVE_ZERO;
if (
!xNegative &&
xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
) return _POSITIVE_INFINITY;
uint256 resultExponent = xSignifier >> 128;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xNegative && xSignifier != 0) {
xSignifier = ~xSignifier;
resultExponent += 1;
}
uint256 resultSignifier = 0x80000000000000000000000000000000;
if (xSignifier & 0x80000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x16A09E667F3BCC908B2FB1366EA957D3E) >>
128;
if (xSignifier & 0x40000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1306FE0A31B7152DE8D5A46305C85EDEC) >>
128;
if (xSignifier & 0x20000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1172B83C7D517ADCDF7C8C50EB14A791F) >>
128;
if (xSignifier & 0x10000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10B5586CF9890F6298B92B71842A98363) >>
128;
if (xSignifier & 0x8000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1059B0D31585743AE7C548EB68CA417FD) >>
128;
if (xSignifier & 0x4000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x102C9A3E778060EE6F7CACA4F7A29BDE8) >>
128;
if (xSignifier & 0x2000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10163DA9FB33356D84A66AE336DCDFA3F) >>
128;
if (xSignifier & 0x1000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100B1AFA5ABCBED6129AB13EC11DC9543) >>
128;
if (xSignifier & 0x800000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10058C86DA1C09EA1FF19D294CF2F679B) >>
128;
if (xSignifier & 0x400000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1002C605E2E8CEC506D21BFC89A23A00F) >>
128;
if (xSignifier & 0x200000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100162F3904051FA128BCA9C55C31E5DF) >>
128;
if (xSignifier & 0x100000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000B175EFFDC76BA38E31671CA939725) >>
128;
if (xSignifier & 0x80000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100058BA01FB9F96D6CACD4B180917C3D) >>
128;
if (xSignifier & 0x40000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10002C5CC37DA9491D0985C348C68E7B3) >>
128;
if (xSignifier & 0x20000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000162E525EE054754457D5995292026) >>
128;
if (xSignifier & 0x10000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000B17255775C040618BF4A4ADE83FC) >>
128;
if (xSignifier & 0x8000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >>
128;
if (xSignifier & 0x4000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >>
128;
if (xSignifier & 0x2000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000162E43F4F831060E02D839A9D16D) >>
128;
if (xSignifier & 0x1000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000B1721BCFC99D9F890EA06911763) >>
128;
if (xSignifier & 0x800000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000058B90CF1E6D97F9CA14DBCC1628) >>
128;
if (xSignifier & 0x400000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000002C5C863B73F016468F6BAC5CA2B) >>
128;
if (xSignifier & 0x200000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000162E430E5A18F6119E3C02282A5) >>
128;
if (xSignifier & 0x100000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000B1721835514B86E6D96EFD1BFE) >>
128;
if (xSignifier & 0x80000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000058B90C0B48C6BE5DF846C5B2EF) >>
128;
if (xSignifier & 0x40000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000002C5C8601CC6B9E94213C72737A) >>
128;
if (xSignifier & 0x20000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000162E42FFF037DF38AA2B219F06) >>
128;
if (xSignifier & 0x10000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000B17217FBA9C739AA5819F44F9) >>
128;
if (xSignifier & 0x8000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000058B90BFCDEE5ACD3C1CEDC823) >>
128;
if (xSignifier & 0x4000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000002C5C85FE31F35A6A30DA1BE50) >>
128;
if (xSignifier & 0x2000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000162E42FF0999CE3541B9FFFCF) >>
128;
if (xSignifier & 0x1000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000B17217F80F4EF5AADDA45554) >>
128;
if (xSignifier & 0x800000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000058B90BFBF8479BD5A81B51AD) >>
128;
if (xSignifier & 0x400000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000002C5C85FDF84BD62AE30A74CC) >>
128;
if (xSignifier & 0x200000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000162E42FEFB2FED257559BDAA) >>
128;
if (xSignifier & 0x100000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000B17217F7D5A7716BBA4A9AE) >>
128;
if (xSignifier & 0x80000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000058B90BFBE9DDBAC5E109CCE) >>
128;
if (xSignifier & 0x40000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000002C5C85FDF4B15DE6F17EB0D) >>
128;
if (xSignifier & 0x20000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000162E42FEFA494F1478FDE05) >>
128;
if (xSignifier & 0x10000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000B17217F7D20CF927C8E94C) >>
128;
if (xSignifier & 0x8000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000058B90BFBE8F71CB4E4B33D) >>
128;
if (xSignifier & 0x4000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000002C5C85FDF477B662B26945) >>
128;
if (xSignifier & 0x2000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000162E42FEFA3AE53369388C) >>
128;
if (xSignifier & 0x1000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000B17217F7D1D351A389D40) >>
128;
if (xSignifier & 0x800000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000058B90BFBE8E8B2D3D4EDE) >>
128;
if (xSignifier & 0x400000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000002C5C85FDF4741BEA6E77E) >>
128;
if (xSignifier & 0x200000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000162E42FEFA39FE95583C2) >>
128;
if (xSignifier & 0x100000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000B17217F7D1CFB72B45E1) >>
128;
if (xSignifier & 0x80000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000058B90BFBE8E7CC35C3F0) >>
128;
if (xSignifier & 0x40000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000002C5C85FDF473E242EA38) >>
128;
if (xSignifier & 0x20000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000162E42FEFA39F02B772C) >>
128;
if (xSignifier & 0x10000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000B17217F7D1CF7D83C1A) >>
128;
if (xSignifier & 0x8000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000058B90BFBE8E7BDCBE2E) >>
128;
if (xSignifier & 0x4000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000002C5C85FDF473DEA871F) >>
128;
if (xSignifier & 0x2000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000162E42FEFA39EF44D91) >>
128;
if (xSignifier & 0x1000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000B17217F7D1CF79E949) >>
128;
if (xSignifier & 0x800000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000058B90BFBE8E7BCE544) >>
128;
if (xSignifier & 0x400000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000002C5C85FDF473DE6ECA) >>
128;
if (xSignifier & 0x200000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000162E42FEFA39EF366F) >>
128;
if (xSignifier & 0x100000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000B17217F7D1CF79AFA) >>
128;
if (xSignifier & 0x80000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000058B90BFBE8E7BCD6D) >>
128;
if (xSignifier & 0x40000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000002C5C85FDF473DE6B2) >>
128;
if (xSignifier & 0x20000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000162E42FEFA39EF358) >>
128;
if (xSignifier & 0x10000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000B17217F7D1CF79AB) >>
128;
if (xSignifier & 0x8000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000058B90BFBE8E7BCD5) >>
128;
if (xSignifier & 0x4000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000002C5C85FDF473DE6A) >>
128;
if (xSignifier & 0x2000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000162E42FEFA39EF34) >>
128;
if (xSignifier & 0x1000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000B17217F7D1CF799) >>
128;
if (xSignifier & 0x800000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000058B90BFBE8E7BCC) >>
128;
if (xSignifier & 0x400000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000002C5C85FDF473DE5) >>
128;
if (xSignifier & 0x200000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000162E42FEFA39EF2) >>
128;
if (xSignifier & 0x100000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000B17217F7D1CF78) >>
128;
if (xSignifier & 0x80000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000058B90BFBE8E7BB) >>
128;
if (xSignifier & 0x40000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000002C5C85FDF473DD) >>
128;
if (xSignifier & 0x20000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000162E42FEFA39EE) >>
128;
if (xSignifier & 0x10000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000B17217F7D1CF6) >>
128;
if (xSignifier & 0x8000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000058B90BFBE8E7A) >>
128;
if (xSignifier & 0x4000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000002C5C85FDF473C) >>
128;
if (xSignifier & 0x2000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000162E42FEFA39D) >>
128;
if (xSignifier & 0x1000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000B17217F7D1CE) >>
128;
if (xSignifier & 0x800000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000058B90BFBE8E6) >>
128;
if (xSignifier & 0x400000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000002C5C85FDF472) >>
128;
if (xSignifier & 0x200000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000162E42FEFA38) >>
128;
if (xSignifier & 0x100000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000B17217F7D1B) >>
128;
if (xSignifier & 0x80000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000058B90BFBE8D) >>
128;
if (xSignifier & 0x40000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000002C5C85FDF46) >>
128;
if (xSignifier & 0x20000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000162E42FEFA2) >>
128;
if (xSignifier & 0x10000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000B17217F7D0) >>
128;
if (xSignifier & 0x8000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000058B90BFBE7) >>
128;
if (xSignifier & 0x4000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000002C5C85FDF3) >>
128;
if (xSignifier & 0x2000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000162E42FEF9) >>
128;
if (xSignifier & 0x1000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000B17217F7C) >>
128;
if (xSignifier & 0x800000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000058B90BFBD) >>
128;
if (xSignifier & 0x400000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000002C5C85FDE) >>
128;
if (xSignifier & 0x200000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000162E42FEE) >>
128;
if (xSignifier & 0x100000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000B17217F6) >>
128;
if (xSignifier & 0x80000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000058B90BFA) >>
128;
if (xSignifier & 0x40000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000002C5C85FC) >>
128;
if (xSignifier & 0x20000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000162E42FD) >>
128;
if (xSignifier & 0x10000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000B17217E) >>
128;
if (xSignifier & 0x8000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000058B90BE) >>
128;
if (xSignifier & 0x4000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000002C5C85E) >>
128;
if (xSignifier & 0x2000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000162E42E) >>
128;
if (xSignifier & 0x1000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000B17216) >>
128;
if (xSignifier & 0x800000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000058B90A) >>
128;
if (xSignifier & 0x400000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000002C5C84) >>
128;
if (xSignifier & 0x200000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000162E41) >>
128;
if (xSignifier & 0x100000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000B1720) >>
128;
if (xSignifier & 0x80000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000058B8F) >>
128;
if (xSignifier & 0x40000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000002C5C7) >>
128;
if (xSignifier & 0x20000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000162E3) >>
128;
if (xSignifier & 0x10000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000B171) >>
128;
if (xSignifier & 0x8000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000058B8) >>
128;
if (xSignifier & 0x4000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000002C5B) >>
128;
if (xSignifier & 0x2000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000162D) >>
128;
if (xSignifier & 0x1000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000B16) >>
128;
if (xSignifier & 0x800 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000058A) >>
128;
if (xSignifier & 0x400 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000002C4) >>
128;
if (xSignifier & 0x200 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000161) >>
128;
if (xSignifier & 0x100 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000000B0) >>
128;
if (xSignifier & 0x80 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000057) >>
128;
if (xSignifier & 0x40 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000002B) >>
128;
if (xSignifier & 0x20 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000015) >>
128;
if (xSignifier & 0x10 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000000A) >>
128;
if (xSignifier & 0x8 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000004) >>
128;
if (xSignifier & 0x4 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000001) >>
128;
if (!xNegative) {
resultSignifier =
(resultSignifier >> 15) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent += 0x3FFF;
} else if (resultExponent <= 0x3FFE) {
resultSignifier =
(resultSignifier >> 15) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent = 0x3FFF - resultExponent;
} else {
resultSignifier =
resultSignifier >>
(resultExponent - 16367);
resultExponent = 0;
}
return
bytes16(uint128((resultExponent << 112) | resultSignifier));
}
}
}
/**
* Calculate e^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function exp(bytes16 x) internal pure returns (bytes16) {
unchecked {return pow_2(mul(x, 0x3FFF71547652B82FE1777D0FFDA0D23A));}
}
/**
* Get index of the most significant non-zero bit in binary representation of
* x. Reverts if x is zero.
*
* @return index of the most significant non-zero bit in binary representation
* of x
*/
function mostSignificantBit(uint256 x) private pure returns (uint256) {
unchecked {
require(x > 0);
uint256 result = 0;
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
result += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
result += 64;
}
if (x >= 0x100000000) {
x >>= 32;
result += 32;
}
if (x >= 0x10000) {
x >>= 16;
result += 16;
}
if (x >= 0x100) {
x >>= 8;
result += 8;
}
if (x >= 0x10) {
x >>= 4;
result += 4;
}
if (x >= 0x4) {
x >>= 2;
result += 2;
}
if (x >= 0x2) result += 1; // No need to shift x anymore
return result;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "./IERC20Ubiquity.sol";
/// @title UAD stablecoin interface
/// @author Ubiquity Algorithmic Dollar
interface IUbiquityAlgorithmicDollar is IERC20Ubiquity {
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
function setIncentiveContract(address account, address incentive) external;
function incentiveContract(address account) external view returns (address);
}
// SPDX-License-Identifier: MIT
// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !!
pragma solidity ^0.8.3;
interface ICurveFactory {
event BasePoolAdded(address base_pool, address implementat);
event MetaPoolDeployed(
address coin,
address base_pool,
uint256 A,
uint256 fee,
address deployer
);
function find_pool_for_coins(address _from, address _to)
external
view
returns (address);
function find_pool_for_coins(
address _from,
address _to,
uint256 i
) external view returns (address);
function get_n_coins(address _pool)
external
view
returns (uint256, uint256);
function get_coins(address _pool) external view returns (address[2] memory);
function get_underlying_coins(address _pool)
external
view
returns (address[8] memory);
function get_decimals(address _pool)
external
view
returns (uint256[2] memory);
function get_underlying_decimals(address _pool)
external
view
returns (uint256[8] memory);
function get_rates(address _pool) external view returns (uint256[2] memory);
function get_balances(address _pool)
external
view
returns (uint256[2] memory);
function get_underlying_balances(address _pool)
external
view
returns (uint256[8] memory);
function get_A(address _pool) external view returns (uint256);
function get_fees(address _pool) external view returns (uint256, uint256);
function get_admin_balances(address _pool)
external
view
returns (uint256[2] memory);
function get_coin_indices(
address _pool,
address _from,
address _to
)
external
view
returns (
int128,
int128,
bool
);
function add_base_pool(
address _base_pool,
address _metapool_implementation,
address _fee_receiver
) external;
function deploy_metapool(
address _base_pool,
string memory _name,
string memory _symbol,
address _coin,
uint256 _A,
uint256 _fee
) external returns (address);
function commit_transfer_ownership(address addr) external;
function accept_transfer_ownership() external;
function set_fee_receiver(address _base_pool, address _fee_receiver)
external;
function convert_fees() external returns (bool);
function admin() external view returns (address);
function future_admin() external view returns (address);
function pool_list(uint256 arg0) external view returns (address);
function pool_count() external view returns (uint256);
function base_pool_list(uint256 arg0) external view returns (address);
function base_pool_count() external view returns (uint256);
function fee_receiver(address arg0) external view returns (address);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "./interfaces/IMetaPool.sol";
contract TWAPOracle {
address public immutable pool;
address public immutable token0;
address public immutable token1;
uint256 public price0Average;
uint256 public price1Average;
uint256 public pricesBlockTimestampLast;
uint256[2] public priceCumulativeLast;
constructor(
address _pool,
address _uADtoken0,
address _curve3CRVtoken1
) {
pool = _pool;
// coin at index 0 is uAD and index 1 is 3CRV
require(
IMetaPool(_pool).coins(0) == _uADtoken0 &&
IMetaPool(_pool).coins(1) == _curve3CRVtoken1,
"TWAPOracle: COIN_ORDER_MISMATCH"
);
token0 = _uADtoken0;
token1 = _curve3CRVtoken1;
uint256 _reserve0 = uint112(IMetaPool(_pool).balances(0));
uint256 _reserve1 = uint112(IMetaPool(_pool).balances(1));
// ensure that there's liquidity in the pair
require(_reserve0 != 0 && _reserve1 != 0, "TWAPOracle: NO_RESERVES");
// ensure that pair balance is perfect
require(_reserve0 == _reserve1, "TWAPOracle: PAIR_UNBALANCED");
priceCumulativeLast = IMetaPool(_pool).get_price_cumulative_last();
pricesBlockTimestampLast = IMetaPool(_pool).block_timestamp_last();
price0Average = 1 ether;
price1Average = 1 ether;
}
// calculate average price
function update() external {
(uint256[2] memory priceCumulative, uint256 blockTimestamp) =
_currentCumulativePrices();
if (blockTimestamp - pricesBlockTimestampLast > 0) {
// get the balances between now and the last price cumulative snapshot
uint256[2] memory twapBalances =
IMetaPool(pool).get_twap_balances(
priceCumulativeLast,
priceCumulative,
blockTimestamp - pricesBlockTimestampLast
);
// price to exchange amounIn uAD to 3CRV based on TWAP
price0Average = IMetaPool(pool).get_dy(0, 1, 1 ether, twapBalances);
// price to exchange amounIn 3CRV to uAD based on TWAP
price1Average = IMetaPool(pool).get_dy(1, 0, 1 ether, twapBalances);
// we update the priceCumulative
priceCumulativeLast = priceCumulative;
pricesBlockTimestampLast = blockTimestamp;
}
}
// note this will always return 0 before update has been called successfully
// for the first time.
function consult(address token) external view returns (uint256 amountOut) {
if (token == token0) {
// price to exchange 1 uAD to 3CRV based on TWAP
amountOut = price0Average;
} else {
require(token == token1, "TWAPOracle: INVALID_TOKEN");
// price to exchange 1 3CRV to uAD based on TWAP
amountOut = price1Average;
}
}
function _currentCumulativePrices()
internal
view
returns (uint256[2] memory priceCumulative, uint256 blockTimestamp)
{
priceCumulative = IMetaPool(pool).get_price_cumulative_last();
blockTimestamp = IMetaPool(pool).block_timestamp_last();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
| swap half amount to uGOV | function _swapDollarsForGovernance(bytes16 amountIn)
internal
returns (uint256)
{
address[] memory path = new address[](2);
path[0] = manager.dollarTokenAddress();
path[1] = manager.governanceTokenAddress();
uint256[] memory amounts =
_router.swapExactTokensForTokens(
amountIn.toUInt(),
0,
path,
address(this),
block.timestamp + 100
);
return amounts[1];
}
| 11,722,335 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "ds-test/test.sol";
import {MockProvider} from "@cleanunicorn/mockprovider/src/MockProvider.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ChainlinkFactory} from "./ChainlinkFactory.sol";
import {Relayer} from "../relayer/Relayer.sol";
import {IRelayer} from "../relayer/IRelayer.sol";
import {ChainlinkValueProvider} from "../oracle_implementations/spot_price/Chainlink/ChainlinkValueProvider.sol";
import {IChainlinkAggregatorV3Interface} from "../oracle_implementations/spot_price/Chainlink/ChainlinkAggregatorV3Interface.sol";
contract ChainlinkFactoryTest is DSTest {
address private _collybusAddress = address(0xC011b005);
uint256 private _oracleUpdateWindow = 1 * 3600;
address private _tokenAddress = address(0x105311);
uint256 private _minimumPercentageDeltaValue = 25;
ChainlinkFactory private _factory;
function setUp() public {
_factory = new ChainlinkFactory();
}
function test_deploy() public {
assertTrue(address(_factory) != address(0));
}
function test_create_relayerIsDeployed() public {
// Create a chainlink mock aggregator
MockProvider chainlinkMock = new MockProvider();
chainlinkMock.givenQueryReturnResponse(
abi.encodeWithSelector(
IChainlinkAggregatorV3Interface.decimals.selector
),
MockProvider.ReturnData({success: true, data: abi.encode(8)}),
false
);
// Create the chainlink Relayer
address chainlinkRelayerAddress = _factory.create(
_collybusAddress,
_tokenAddress,
_minimumPercentageDeltaValue,
_oracleUpdateWindow,
address(chainlinkMock)
);
assertTrue(
chainlinkRelayerAddress != address(0),
"Factory Chainlink Relayer create failed"
);
}
function test_create_oracleIsDeployed() public {
// Create a chainlink mock aggregator
MockProvider chainlinkMock = new MockProvider();
chainlinkMock.givenQueryReturnResponse(
abi.encodeWithSelector(
IChainlinkAggregatorV3Interface.decimals.selector
),
MockProvider.ReturnData({success: true, data: abi.encode(8)}),
false
);
// Create the chainlink Relayer
address chainlinkRelayerAddress = _factory.create(
_collybusAddress,
_tokenAddress,
_minimumPercentageDeltaValue,
_oracleUpdateWindow,
address(chainlinkMock)
);
assertTrue(
Relayer(chainlinkRelayerAddress).oracle() != address(0),
"Invalid oracle address"
);
}
function test_create_validateRelayerProperties() public {
// Create a chainlink mock aggregator
MockProvider chainlinkMock = new MockProvider();
chainlinkMock.givenQueryReturnResponse(
abi.encodeWithSelector(
IChainlinkAggregatorV3Interface.decimals.selector
),
MockProvider.ReturnData({success: true, data: abi.encode(8)}),
false
);
// Create the chainlink Relayer
Relayer chainlinkRelayer = Relayer(
_factory.create(
_collybusAddress,
_tokenAddress,
_minimumPercentageDeltaValue,
_oracleUpdateWindow,
address(chainlinkMock)
)
);
assertEq(
Relayer(chainlinkRelayer).collybus(),
_collybusAddress,
"Chainlink Relayer incorrect Collybus address"
);
assertTrue(
Relayer(chainlinkRelayer).relayerType() ==
IRelayer.RelayerType.SpotPrice,
"Chainlink Relayer incorrect RelayerType"
);
assertEq(
Relayer(chainlinkRelayer).encodedTokenId(),
bytes32(uint256(uint160(_tokenAddress))),
"Chainlink Relayer incorrect tokenId"
);
assertEq(
Relayer(chainlinkRelayer).minimumPercentageDeltaValue(),
_minimumPercentageDeltaValue,
"Chainlink Relayer incorrect minimumPercentageDeltaValue"
);
}
function test_create_validateOracleProperties() public {
// Create a chainlink mock aggregator
MockProvider chainlinkMock = new MockProvider();
chainlinkMock.givenQueryReturnResponse(
abi.encodeWithSelector(
IChainlinkAggregatorV3Interface.decimals.selector
),
MockProvider.ReturnData({success: true, data: abi.encode(8)}),
false
);
// Create the chainlink Relayer
address chainlinkRelayerAddress = _factory.create(
_collybusAddress,
_tokenAddress,
_minimumPercentageDeltaValue,
_oracleUpdateWindow,
address(chainlinkMock)
);
address chainlinkOracleAddress = Relayer(chainlinkRelayerAddress)
.oracle();
// Test that properties are correctly set
assertEq(
ChainlinkValueProvider(chainlinkOracleAddress).timeUpdateWindow(),
_oracleUpdateWindow,
"Chainlink Value Provider incorrect oracleUpdateWindow"
);
assertEq(
ChainlinkValueProvider(chainlinkOracleAddress)
.chainlinkAggregatorAddress(),
address(chainlinkMock),
"Chainlink Value Provider incorrect chainlinkAggregatorAddress"
);
}
function test_create_factoryPassesOraclePermissions() public {
// Create a chainlink mock aggregator
MockProvider chainlinkMock = new MockProvider();
chainlinkMock.givenQueryReturnResponse(
abi.encodeWithSelector(
IChainlinkAggregatorV3Interface.decimals.selector
),
MockProvider.ReturnData({success: true, data: abi.encode(8)}),
false
);
// Create chainlink Relayer
address chainlinkRelayerAddress = _factory.create(
_collybusAddress,
_tokenAddress,
_minimumPercentageDeltaValue,
_oracleUpdateWindow,
address(chainlinkMock)
);
ChainlinkValueProvider chainlinkValueProvider = ChainlinkValueProvider(
Relayer(chainlinkRelayerAddress).oracle()
);
bool factoryIsAuthorized = chainlinkValueProvider.canCall(
chainlinkValueProvider.ANY_SIG(),
address(_factory)
);
assertTrue(
factoryIsAuthorized == false,
"The Factory should not have rights over the created contract"
);
bool callerIsAuthorized = chainlinkValueProvider.canCall(
chainlinkValueProvider.ANY_SIG(),
address(this)
);
assertTrue(
callerIsAuthorized,
"Caller should have rights over the created contract"
);
}
function test_create_factoryPassesRelayerPermissions() public {
// Create a chainlink mock aggregator
MockProvider chainlinkMock = new MockProvider();
chainlinkMock.givenQueryReturnResponse(
abi.encodeWithSelector(
IChainlinkAggregatorV3Interface.decimals.selector
),
MockProvider.ReturnData({success: true, data: abi.encode(8)}),
false
);
// Create chainlink Relayer
Relayer chainlinkRelayer = Relayer(
_factory.create(
_collybusAddress,
_tokenAddress,
_minimumPercentageDeltaValue,
_oracleUpdateWindow,
address(chainlinkMock)
)
);
bool factoryIsAuthorized = chainlinkRelayer.canCall(
chainlinkRelayer.ANY_SIG(),
address(_factory)
);
assertTrue(
factoryIsAuthorized == false,
"The Factory should not have rights over the created contract"
);
bool callerIsAuthorized = chainlinkRelayer.canCall(
chainlinkRelayer.ANY_SIG(),
address(this)
);
assertTrue(
callerIsAuthorized,
"Caller should have rights over the created contract"
);
}
}
| Create a chainlink mock aggregator Create the chainlink Relayer | function test_create_validateRelayerProperties() public {
MockProvider chainlinkMock = new MockProvider();
chainlinkMock.givenQueryReturnResponse(
abi.encodeWithSelector(
IChainlinkAggregatorV3Interface.decimals.selector
),
false
);
Relayer chainlinkRelayer = Relayer(
_factory.create(
_collybusAddress,
_tokenAddress,
_minimumPercentageDeltaValue,
_oracleUpdateWindow,
address(chainlinkMock)
)
);
assertEq(
Relayer(chainlinkRelayer).collybus(),
_collybusAddress,
"Chainlink Relayer incorrect Collybus address"
);
assertTrue(
Relayer(chainlinkRelayer).relayerType() ==
IRelayer.RelayerType.SpotPrice,
"Chainlink Relayer incorrect RelayerType"
);
assertEq(
Relayer(chainlinkRelayer).encodedTokenId(),
bytes32(uint256(uint160(_tokenAddress))),
"Chainlink Relayer incorrect tokenId"
);
assertEq(
Relayer(chainlinkRelayer).minimumPercentageDeltaValue(),
_minimumPercentageDeltaValue,
"Chainlink Relayer incorrect minimumPercentageDeltaValue"
);
}
| 12,971,350 |
//SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.4;
import "forge-std/Test.sol";
import "forge-std/Vm.sol";
import "forge-std/console2.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import {Logbook} from "../../Logbook/Logbook.sol";
import {ILogbook} from "../../Logbook/ILogbook.sol";
contract LogbookTest is Test {
Logbook private logbook;
address constant DEPLOYER = address(176);
address constant TRAVELOGGERS_OWNER = address(177);
address constant PUBLIC_SALE_MINTER = address(178);
address constant ATTACKER = address(179);
address constant APPROVED = address(180);
address constant FRONTEND_OPERATOR = address(181);
uint256 constant _ROYALTY_BPS_LOGBOOK_OWNER = 8000;
uint256 private constant _ROYALTY_BPS_COMMISSION_MAX = 10000 - _ROYALTY_BPS_LOGBOOK_OWNER;
uint256 constant _PUBLIC_SALE_ON = 1;
uint256 constant _PUBLIC_SALE_OFF = 2;
uint256 constant CLAIM_TOKEN_START_ID = 1;
uint256 constant CLAIM_TOKEN_END_ID = 1500;
event SetTitle(uint256 indexed tokenId, string title);
event SetDescription(uint256 indexed tokenId, string description);
event SetForkPrice(uint256 indexed tokenId, uint256 amount);
event Content(address indexed author, bytes32 indexed contentHash, string content);
event Publish(uint256 indexed tokenId, bytes32 indexed contentHash);
event Fork(uint256 indexed tokenId, uint256 indexed newTokenId, address indexed owner, uint32 end, uint256 amount);
event Donate(uint256 indexed tokenId, address indexed donor, uint256 amount);
enum RoyaltyPurpose {
Fork,
Donate
}
event Pay(
uint256 indexed tokenId,
address indexed sender,
address indexed recipient,
RoyaltyPurpose purpose,
uint256 amount
);
event Withdraw(address indexed account, uint256 amount);
function setUp() public {
// Deploy contract with DEPLOYER
vm.prank(DEPLOYER);
logbook = new Logbook("Logbook", "LOGRS");
// label addresses
vm.label(DEPLOYER, "DEPLOYER");
vm.label(TRAVELOGGERS_OWNER, "TRAVELOGGERS_OWNER");
vm.label(PUBLIC_SALE_MINTER, "PUBLIC_SALE_MINTER");
vm.label(ATTACKER, "ATTACKER");
vm.label(APPROVED, "APPROVED");
vm.label(FRONTEND_OPERATOR, "FRONTEND_OPERATOR");
}
/**
* Claim
*/
function _claimToTraveloggersOwner() private {
uint160 blockTime = 1647335928;
vm.prank(DEPLOYER);
vm.warp(blockTime);
logbook.claim(TRAVELOGGERS_OWNER, CLAIM_TOKEN_START_ID);
assertEq(logbook.ownerOf(CLAIM_TOKEN_START_ID), TRAVELOGGERS_OWNER);
assertEq(logbook.balanceOf(TRAVELOGGERS_OWNER), 1);
ILogbook.Book memory book = logbook.getLogbook(CLAIM_TOKEN_START_ID);
assertEq(uint160(block.timestamp), blockTime);
assertEq(block.timestamp, book.createdAt);
}
function testClaim() public {
// only owner
vm.prank(PUBLIC_SALE_MINTER);
vm.expectRevert("Ownable: caller is not the owner");
logbook.claim(TRAVELOGGERS_OWNER, CLAIM_TOKEN_END_ID);
// token has not been claimed yet
vm.expectRevert("ERC721: owner query for nonexistent token");
logbook.ownerOf(CLAIM_TOKEN_START_ID);
assertEq(logbook.balanceOf(TRAVELOGGERS_OWNER), 0);
// claim
_claimToTraveloggersOwner();
// token can't be claimed twice
vm.prank(DEPLOYER);
vm.expectRevert("ERC721: token already minted");
logbook.claim(TRAVELOGGERS_OWNER, CLAIM_TOKEN_START_ID);
// invalid token id
vm.prank(DEPLOYER);
vm.expectRevert(abi.encodeWithSignature("InvalidTokenId(uint256,uint256)", 1, 1500));
logbook.claim(TRAVELOGGERS_OWNER, CLAIM_TOKEN_START_ID - 1);
vm.prank(DEPLOYER);
vm.expectRevert(abi.encodeWithSignature("InvalidTokenId(uint256,uint256)", 1, 1500));
logbook.claim(TRAVELOGGERS_OWNER, CLAIM_TOKEN_END_ID + 1);
}
/**
* Public Sale
*/
function testPublicSale() public {
uint256 price = 1 ether;
// not started
vm.expectRevert(abi.encodePacked(bytes4(keccak256("PublicSaleNotStarted()"))));
logbook.publicSaleMint();
// turn on
vm.prank(DEPLOYER);
logbook.turnOnPublicSale();
vm.prank(DEPLOYER);
logbook.setPublicSalePrice(price);
assertEq(logbook.publicSalePrice(), price);
// mint
uint256 deployerWalletBalance = DEPLOYER.balance;
vm.deal(PUBLIC_SALE_MINTER, price + 1 ether);
vm.prank(PUBLIC_SALE_MINTER);
uint256 tokenId = logbook.publicSaleMint{value: price}();
assertEq(tokenId, CLAIM_TOKEN_END_ID + 1);
assertEq(logbook.ownerOf(tokenId), PUBLIC_SALE_MINTER);
// deployer receives ether
assertEq(DEPLOYER.balance, deployerWalletBalance + price);
// not engough ether to mint
vm.expectRevert(abi.encodeWithSignature("InsufficientAmount(uint256,uint256)", price - 0.01 ether, price));
vm.deal(PUBLIC_SALE_MINTER, price + 1 ether);
vm.prank(PUBLIC_SALE_MINTER);
logbook.publicSaleMint{value: price - 0.01 ether}();
// free to mint
vm.prank(DEPLOYER);
logbook.setPublicSalePrice(0);
assertEq(logbook.publicSalePrice(), 0);
vm.prank(PUBLIC_SALE_MINTER);
uint256 freeTokenId = logbook.publicSaleMint{value: 0}();
assertEq(freeTokenId, CLAIM_TOKEN_END_ID + 2);
assertEq(logbook.ownerOf(freeTokenId), PUBLIC_SALE_MINTER);
}
/**
* Title, Description, Fork Price, Publish...
*/
function _setForkPrice(uint256 forkPrice) private {
vm.expectEmit(true, true, false, false);
emit SetForkPrice(CLAIM_TOKEN_START_ID, forkPrice);
vm.prank(TRAVELOGGERS_OWNER);
logbook.setForkPrice(CLAIM_TOKEN_START_ID, forkPrice);
ILogbook.Book memory book = logbook.getLogbook(CLAIM_TOKEN_START_ID);
assertEq(book.forkPrice, forkPrice);
}
function _publish(string memory content, bool emitContent) private returns (bytes32 contentHash) {
contentHash = keccak256(abi.encodePacked(content));
// emit Content
if (emitContent) {
vm.expectEmit(true, true, true, false);
emit Content(TRAVELOGGERS_OWNER, contentHash, content);
}
// emit Publish
vm.expectEmit(true, true, false, false);
emit Publish(CLAIM_TOKEN_START_ID, contentHash);
vm.prank(TRAVELOGGERS_OWNER);
logbook.publish(CLAIM_TOKEN_START_ID, content);
}
function testSetTitle() public {
_claimToTraveloggersOwner();
string memory title = "Sit deserunt nulla aliqua ex nisi";
// set title
vm.prank(TRAVELOGGERS_OWNER);
vm.expectEmit(true, true, false, false);
emit SetTitle(CLAIM_TOKEN_START_ID, title);
logbook.setTitle(CLAIM_TOKEN_START_ID, title);
// only logbook owner
vm.prank(ATTACKER);
vm.expectRevert(abi.encodePacked(bytes4(keccak256("Unauthorized()"))));
logbook.setTitle(CLAIM_TOKEN_START_ID, title);
// approve other address
vm.startPrank(TRAVELOGGERS_OWNER);
logbook.approve(APPROVED, CLAIM_TOKEN_START_ID);
logbook.getApproved(CLAIM_TOKEN_START_ID);
vm.stopPrank();
vm.prank(APPROVED);
logbook.setTitle(CLAIM_TOKEN_START_ID, title);
}
function testSetDescription() public {
_claimToTraveloggersOwner();
string
memory description = "Quis commodo sunt ea est aliquip enim aliquip ullamco eu. Excepteur aliquip enim irure dolore deserunt fugiat consectetur esse in deserunt commodo in eiusmod esse. Cillum cupidatat dolor voluptate in id consequat nulla aliquip. Deserunt sunt aute eu aliqua consequat nulla aliquip excepteur exercitation. Lorem ex magna deserunt duis dolor dolore mollit.";
// set description
vm.prank(TRAVELOGGERS_OWNER);
vm.expectEmit(true, true, false, false);
emit SetDescription(CLAIM_TOKEN_START_ID, description);
logbook.setDescription(CLAIM_TOKEN_START_ID, description);
// only logbook owner
vm.prank(ATTACKER);
vm.expectRevert(abi.encodePacked(bytes4(keccak256("Unauthorized()"))));
logbook.setTitle(CLAIM_TOKEN_START_ID, description);
}
function testSetForkPrice() public {
_claimToTraveloggersOwner();
// set fork price
uint256 forkPrice = 0.1 ether;
_setForkPrice(forkPrice);
// only logbook owner
vm.prank(ATTACKER);
vm.expectRevert(abi.encodePacked(bytes4(keccak256("Unauthorized()"))));
logbook.setForkPrice(CLAIM_TOKEN_START_ID, forkPrice);
}
function testPublish(string calldata content) public {
_claimToTraveloggersOwner();
bytes32 contentHash = keccak256(abi.encodePacked(content));
// publish
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
ILogbook.Book memory book = logbook.getLogbook(CLAIM_TOKEN_START_ID);
assertEq(book.logCount, 1);
// publish same content
bytes32 return2ContentHash = _publish(content, false);
assertEq(contentHash, return2ContentHash);
ILogbook.Book memory book2 = logbook.getLogbook(CLAIM_TOKEN_START_ID);
assertEq(book2.logCount, 2);
// only logbook owner
vm.prank(ATTACKER);
vm.expectRevert(abi.encodePacked(bytes4(keccak256("Unauthorized()"))));
logbook.publish(CLAIM_TOKEN_START_ID, content);
}
function testPublishZh20() public {
_claimToTraveloggersOwner();
string memory content = unicode"愛倫坡驚悚小說全集,坎坷的奇才,大家好。";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishZh50() public {
_claimToTraveloggersOwner();
string
memory content = unicode"愛倫坡驚悚小說全集,坎坷的奇才,大家好,我係今集已讀不回主持人Serrini。熱辣辣嘅暑假最適合咩?";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishZh100() public {
_claimToTraveloggersOwner();
string
memory content = unicode"愛倫坡驚悚小說全集,坎坷的奇才,大家好,我係今集已讀不回主持人Serrini。熱辣辣嘅暑假最適合咩?愛倫坡驚悚小說全集,坎坷的奇才,大家好,我係今集已讀不回主持人Serrini。熱辣辣嘅暑假最適合咩?";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishZh200() public {
_claimToTraveloggersOwner();
string
memory content = unicode"愛倫坡驚悚小說全集,坎坷的奇才,大家好,我係今集已讀不回主持人Serrini。熱辣辣嘅暑假最適合咩?愛倫坡驚悚小說全集,坎坷的奇才,大家好,我係今集已讀不回主持人Serrini。熱辣辣嘅暑假最適合咩?愛倫坡驚悚小說全集,坎坷的奇才,大家好,我係今集已讀不回主持人Serrini。熱辣辣嘅暑假最適合咩?愛倫坡驚悚小說全集,坎坷的奇才,大家好,我係今集已讀不回主持人Serrini。熱辣辣嘅暑假最適合咩?";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishZh500() public {
_claimToTraveloggersOwner();
string
memory content = unicode"我覺得大家會好喜歡今天介紹嘅書。\n學者James Cooper Lawrence係1917年有篇有趣嘅文章 “A Theory of the Short Story” 「短篇小說的理論」就提到愛倫坡話過自己比較prefer短篇,就係因為短篇嘅小說可以最可以做到簡潔、完整。情況就好似讀者可以將故事世界置於掌心、唔洗時刻記住20個角色同埋接受大量情境setting資料就可以走入故事。可能坡哥對人嘅耐心無咩信心,佢覺得比讀者控制到個故事篇幅先可以令人全程投入。佢創作短篇小說嘅重點就在於傳達一個single effect,唔係就變就你地d 分手千字文架啦。\n愛倫坡係短篇小說、詩歌、評論文章都set到個bar好高,堪稱冠絕同代美國作家。以下我地講下愛倫坡嘅小說寫作風格,等大家可以調整一下期望。愛倫坡嘅作品比較容易比讀者get到嘅風格就係一種揉合帶有古典味、歌德色嘅浪漫主義嘅「坡體」(個term只存在這個book channel)。他寫作風格靠近浪漫主義,因為其文字偏重騰飛嘅思想同自言自語講情感,有拜倫、雪萊之風,簡單地說就係「腦海想旅行」、唔係幾現實,甚至係避世,都同上面提到「為藝術而藝術」幾配合。";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishZh2000() public {
_claimToTraveloggersOwner();
string
memory content = unicode"常言道,食餐好可以令心情好,心情唔好更加要食餐好,飲食係美好生活的重要一環,而香港都算係國際美食之都,好多香港人都算係為食架。但係食得太多太好又會影響健康,會有三高糖尿病等富貴病,或者肥左少少都會令心情緊張,所以做一個為食的人,都係充滿掙扎的一件事。今次想同大家介紹的書是一本飲食文化史,《饞——貪吃的歷史》,從文化角度了解下我地為食一族的各種面貌和歷史意義。\n我本人是否為食呢?在這裡跟大家分享一個小故事。話說我中學時得過一個徵文比賽的獎項,個頒獎禮有幾十人得獎,豬肉味有啲濃。個幾十人的茶會有個重點環節,就係大作家,金庸會來跟我們合照,合照完之後還可以請金庸簽名。金庸人人仰幕,大家當然帶好書。合照完左,茶會開始,但所有人都去排隊請金庸先生簽名,我眼前是,一邊係幾十人排隊等待的金庸,一邊係無人問津的茶點(水平普通),而我,當時選擇了——茶點。全場只得我一個中學生,先去食茶點,等條隊無乜人排時,才施施然去請金庸簽名。這個選擇背後的勇氣來自什麼,我都好難講清楚,是反叛還是什麼,我在今日這個場合承認,是因為,單純的為食。究竟為食呢樣嘢,係令你生活更加美好還是阻止你生活變得更加美好呢?不妨來讀這本書思考一下。\n《饞——貪吃的歷史》的作者弗羅杭.柯立葉是一位專門研究飲食的歷史學家及作家,本書是得過書獎的。書中由宗教典籍、嚴肅文學、民間文學、藝術繪畫、報章漫畫、民俗資料,展示了「饞」這個概念及相關概念,展示了它的各種形態與流變,是一本飽覽貪吃眾生相的飲食文化史。在書中可以看到許多藝術繪畫,又可以順便認識好多文學作品,可謂營養豐富,賞心悅目,秀色可餐。\n在早期,「饞」是一件大事,大家都知,聖經的七宗罪裡就有一條「饕餮」,即是極度為食,這個中文翻譯亦都很雅,饕餮本來是古代中國神話中的怪物,《史記》裡面有佢個名,青銅器上會有佢個樣,《山海經》有佢比較詳細的形象。簡單來講,饕餮很貪吃,會食人,所以代表了貪婪的罪惡。傳統上中國也將貪吃的人稱為老饕。我猜你平時見到饕餮兩個字都不識讀的了,學多兩個字是否很開心?這樣談飲食是否更有文化?這本書一\n開始就有一章是梳理書名「饞」gourmandise有關的詞,好有文化,我硬食了幾十個法文西班牙文意大利文拉丁文生詞……原來「饞」gourmandise的詞義在歷史上一直變化,簡單來講有三個面向:glouton(暴食,即是饕餮), gourmet(講究美食), gourmand(貪嘴),我今日的法文課可否到此為止……所以饞的意思可指帶罪惡意味的暴食、講究美食(比較有知識和文化味)、及比較日常的貪嘴為食,而這三個解釋大致符合歷史的流向,以及本書的結構。\n在中世紀的教會眼中,貪饞為食與教會苦修節制的美德相反,雖然貪饞只是輕罪,但也列入七大宗罪,因為貪饞會引起其它的罪惡。大家不要忘了,人類之所以會從失樂園墮落,都係因為夏娃同亞當吃了蘋果,中世紀很多神學家都認為人類的原罪包括貪饞。貪饞容易引起口舌之禍,飲飽食醉之後會做滑稽放蕩的行為,會亂講話,傻笑之類,又容易驕傲、嫉妒等其它罪惡。而進食用口部,口部是語言和食物交會的十字路口,教會眼中是很容易受到撒旦侵襲的。所以修道院規定進食時必須保持沉默,並以大聲朗誦聖經篇章代替席間交談,其實是想提醒食客靈魂的糧食比身體糧食更重要,而聽覺比味覺更高尚。落到胃部就更麻煩了,因為腹部和腹部以下的性器相連,「飲食男女,人之大欲存焉」,「食色性也」,飲食和性欲被認為是非常接近的東西,又好容易曳曳了。所謂「飽暖思淫慾」,原來古代的中西方都是這樣想。甚至,在法文中,有些話女性貪食的字眼,其實也意近她性方面不檢點。噢,原來話女人「大食」作為性意味的侮辱,廣東人和法國人竟然在這方面相通,利害利害。\n教會一度大力鞭撻暴飲暴食之罪,在聖經手抄本、壁畫、教堂雕飾、版畫等地方大肆醜化暴食者,將之畫成狼、豬、癩蛤蟆等等,也將暴飲暴食描述為有財有勢者的專屬犯罪。不過也造成了貪饞在藝術史上的源遠流長,file幾呎厚。另一方面大力提倡齋戒、節制等美德,又一度主張禁食,但問題來了,植物、動物、美食,其實都是上帝的造物,如果一味禁食、厭惡美食,那麼如何欣賞上帝的創造呢?這豈非和上帝距離愈來愈遠嗎?而且,饑餓感、食慾都是上帝創造的嘛,不用覺得它們是邪惡的,所以有些神學家都主張大家平常心一點去看待,不必讉責吃喝的慾望,也不用鞭撻飲食享樂,只是要追求適度、節制、平衡,也要有禮儀以滿足社交要求,同時滿足個人生理需要和賓客的精神需要。大概由十三世紀,適度飲食的理想已代替了禁食的理想。\n教會很努力向世俗世界傳遞節制的美德,但事實上,由十三世紀左右開始,民間有一些相反的體裁重新興起,就是關於極樂世界的故事、詩歌、鬧劇、圖畫、版畫、漫畫地圖等。這種極樂世界不是宗教裡的天堂,而是民間的想像,它們都經常描述一個食物供應源源不絕、種類超級豐富的人間仙境間仙境。";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishZh5000() public {
_claimToTraveloggersOwner();
string
memory content = unicode"《饞——貪吃的歷史》\n常言道,食餐好可以令心情好,心情唔好更加要食餐好,飲食係美好生活的重要一環,而香港都算係國際美食之都,好多香港人都算係為食架。但係食得太多太好又會影響健康,會有三高糖尿病等富貴病,或者肥左少少都會令心情緊張,所以做一個為食的人,都係充滿掙扎的一件事。今次想同大家介紹的書是一本飲食文化史,《饞——貪吃的歷史》,從文化角度了解下我地為食一族的各種面貌和歷史意義。\n我本人是否為食呢?在這裡跟大家分享一個小故事。話說我中學時得過一個徵文比賽的獎項,個頒獎禮有幾十人得獎,豬肉味有啲濃。個幾十人的茶會有個重點環節,就係大作家,金庸會來跟我們合照,合照完之後還可以請金庸簽名。金庸人人仰幕,大家當然帶好書。合照完左,茶會開始,但所有人都去排隊請金庸先生簽名,我眼前是,一邊係幾十人排隊等待的金庸,一邊係無人問津的茶點(水平普通),而我,當時選擇了——茶點。全場只得我一個中學生,先去食茶點,等條隊無乜人排時,才施施然去請金庸簽名。這個選擇背後的勇氣來自什麼,我都好難講清楚,是反叛還是什麼,我在今日這個場合承認,是因為,單純的為食。究竟為食呢樣嘢,係令你生活更加美好還是阻止你生活變得更加美好呢?不妨來讀這本書思考一下。\n《饞——貪吃的歷史》的作者弗羅杭.柯立葉是一位專門研究飲食的歷史學家及作家,本書是得過書獎的。書中由宗教典籍、嚴肅文學、民間文學、藝術繪畫、報章漫畫、民俗資料,展示了「饞」這個概念及相關概念,展示了它的各種形態與流變,是一本飽覽貪吃眾生相的飲食文化史。在書中可以看到許多藝術繪畫,又可以順便認識好多文學作品,可謂營養豐富,賞心悅目,秀色可餐。\n一、為食好大罪\n在早期,「饞」是一件大事,大家都知,聖經的七宗罪裡就有一條「饕餮」,即是極度為食,這個中文翻譯亦都很雅,饕餮本來是古代中國神話中的怪物,《史記》裡面有佢個名,青銅器上會有佢個樣,《山海經》有佢比較詳細的形象。簡單來講,饕餮很貪吃,會食人,所以代表了貪婪的罪惡。傳統上中國也將貪吃的人稱為老饕。我猜你平時見到饕餮兩個字都不識讀的了,學多兩個字是否很開心?這樣談飲食是否更有文化?這本書一開始就有一章是梳理書名「饞」gourmandise有關的詞,好有文化,我硬食了幾十個法文西班牙文意大利文拉丁文生詞……原來「饞」gourmandise的詞義在歷史上一直變化,簡單來講有三個面向:glouton(暴食,即是饕餮), gourmet(講究美食), gourmand(貪嘴),我今日的法文課可否到此為止……所以饞的意思可指帶罪惡意味的暴食、講究美食(比較有知識和文化味)、及比較日常的貪嘴為食,而這三個解釋大致符合歷史的流向,以及本書的結構。\n在中世紀的教會眼中,貪饞為食與教會苦修節制的美德相反,雖然貪饞只是輕罪,但也列入七大宗罪,因為貪饞會引起其它的罪惡。大家不要忘了,人類之所以會從失樂園墮落,都係因為夏娃同亞當吃了蘋果,中世紀很多神學家都認為人類的原罪包括貪饞。貪饞容易引起口舌之禍,飲飽食醉之後會做滑稽放蕩的行為,會亂講話,傻笑之類,又容易驕傲、嫉妒等其它罪惡。而進食用口部,口部是語言和食物交會的十字路口,教會眼中是很容易受到撒旦侵襲的。所以修道院規定進食時必須保持沉默,並以大聲朗誦聖經篇章代替席間交談,其實是想提醒食客靈魂的糧食比身體糧食更重要,而聽覺比味覺更高尚。落到胃部就更麻煩了,因為腹部和腹部以下的性器相連,「飲食男女,人之大欲存焉」,「食色性也」,飲食和性欲被認為是非常接近的東西,又好容易曳曳了。所謂「飽暖思淫慾」,原來古代的中西方都是這樣想。甚至,在法文中,有些話女性貪食的字眼,其實也意近她性方面不檢點。噢,原來話女人「大食」作為性意味的侮辱,廣東人和法國人竟然在這方面相通,利害利害。\n教會一度大力鞭撻暴飲暴食之罪,在聖經手抄本、壁畫、教堂雕飾、版畫等地方大肆醜化暴食者,將之畫成狼、豬、癩蛤蟆等等,也將暴飲暴食描述為有財有勢者的專屬犯罪。不過也造成了貪饞在藝術史上的源遠流長,file幾呎厚。另一方面大力提倡齋戒、節制等美德,又一度主張禁食,但問題來了,植物、動物、美食,其實都是上帝的造物,如果一味禁食、厭惡美食,那麼如何欣賞上帝的創造呢?這豈非和上帝距離愈來愈遠嗎?而且,饑餓感、食慾都是上帝創造的嘛,不用覺得它們是邪惡的,所以有些神學家都主張大家平常心一點去看待,不必讉責吃喝的慾望,也不用鞭撻飲食享樂,只是要追求適度、節制、平衡,也要有禮儀以滿足社交要求,同時滿足個人生理需要和賓客的精神需要。大概由十三世紀,適度飲食的理想已代替了禁食的理想。\n二、放縱與節制\n教會很努力向世俗世界傳遞節制的美德,但事實上,由十三世紀左右開始,民間有一些相反的體裁重新興起,就是關於極樂世界的故事、詩歌、鬧劇、圖畫、版畫、漫畫地圖等。這種極樂世界不是宗教裡的天堂,而是民間的想像,它們都經常描述一個食物供應源源不絕、種類超級豐富的人間仙境,人在其中不用工作,就是隨時隨意地大吃大喝,歌舞作樂,根本不知饑餓感為何物。更早期公元前五世紀的古希臘喜劇也類似,烤雲雀會直接由天上掉入人的口中,河流是浮著肉的濃湯,魚群自動送上門,自行油炸送入食客口中,樹上直接掉下杏仁饀餅和烤羊腸。中世紀的烏托邦裡永遠是春天和夏天,人類完全沉浸在感官享樂的世俗幸福中,無限放題,又唔駛做,又唔會老。\n(讀P.48極樂世界)\n各個不同國家的極樂世界飲食詩結構大致一樣,但會出現不同地區的獨特美食。例如法國的極樂世界,河川是紅酒和白酒(都是名貴產地),荷蘭版本就多了一條啤酒河;意大利的極樂世界牆紙是圓型的沙樂美腸,又會有一座由乳酪絲組成的高山,會噴出通心粉,接著跌入醬汁河裡。而在這個世界裡「肥」是一個正面的詞語,代表了豐饒富足、無憂無慮。極樂世界完全係民間世俗的想像,後來逐漸又演變成邊緣人物流放的桃花源,好似愈講愈正咁。\n值得注意的是,這種狂歡節般的想像,其實是因為現實中連年的大饑荒,民間食品供應極度不足又面對嚴厲的宗教規管,所以才在想像的世界中尋求慰藉,也是緬懷逝去的昔日。這是一種民間自行尋找安定人心的方式,是一種宣洩的管道、短暫的補償。其實在聖經中,都是在大洪水之後,神才開始允許挪亞及其後代吃肉和喝酒,見到人類生活每況愈下神都會讓步。如果在很困難的時候還不讓人發洩和想像,真是太殘忍了。\n極樂世界烏托邦想像早期曾有反抗天主教教條的意味,但真正擊敗天主教教條的不是極樂世界,而是天主教本身的腐敗。十三世紀以降天主教對美食的規訓放鬆,教廷又有錢,結果就出現了「美食齋戒」這樣荒謬的觀念,於是就出現許多描述宗教人員和修道院放奢華飲食、酒池肉林的諷刺文學,例如說他們是「大腹神學家」,將之前在宗教繪畫裡貪食者的形象用來描繪貪食修士等等。這一點甚至是十六世紀宗教改革時,基督新教對羅馬天主教的主要抨擊目標之一。基督教對於美食的態度可用英國飲食文化來代表:英國只是考慮食材和食物的養份、維他命及機能。而天主教則已經累積了許多種植、飲食的技藝和知識,已比較似法國人和意大利人那樣考慮烹飪藝術的觀點。天主教面對指責,進行了對美食的除罪化,也同時提倡適度而不豪奢的飲食,這有助催生一種為食的美學:只要能遵守規範,食好嘢的樂趣就可以被肯定,而所有規範中最重要的就是餐桌禮儀和分享之樂。\n三、美食的知識和教養\n由十六、十七世紀左右,由天主教和西方社會推動的「美食文化菁英化」運動,首先就是唾棄貪食者、暴食者,但推崇端正得體,知識豐富的「饕客」和美食家。到十八世紀,法國上流菁英已經視享樂為飲食的目的,而「貪饞」gourmandise這個詞也開始被收入百科全書,意即「對美食細膩而無節制的喜好」,雖然褒貶參半,但「細緻的喜好」已經出現了,不再只是「不知節制」。\n端正得體的饕客著重餐桌禮儀,重要參考物就是人稱「人文主義王子」伊拉斯謨的《兒童禮儀》,這本書是參考古典文學(如亞里士多德、西塞羅)、中世紀的教育論著、諺語、寓言故事,制定一套社會接納的行為準則。如何盛菜、切菜、放入口、咀嚼,都有規定。這套優雅的準則被沿用了五世紀之久,可說是演化緩慢。而餐桌禮儀的敵人當然就是粗魯的「饕餮之徒」啦,由文藝復興到啟蒙運動期間,都有好多文學作品描述他們的醜態。\n//可讀p.111//\n儀態之後就是品味,1803年美食享樂主義者格里蒙.德.拉雷涅《饕客年鑑》,應該算係米芝蓮前身,就是飲食品味的重要指標。而飲食的高雅品味離不開高級的語言能力,一個美食家需要用優美的語言去形容食物,並指出它的來源地和烹飪方法。食物本身也開始象徵身份地位,例如鷹嘴豆、蘿蔔、扁豆、黑血腸就是窮人的食物,時鮮的蘆荀、朝鮮薊、甜瓜、無花果及西洋梨就是上流社會的喜好,果醬、蜜餞、杏仁小餅之類的甜食都是高貴嘢。上流的饕客端正得體,儀容整潔、容光煥發,而下等的饕餮之後就猥瑣、貪婪、肥而走樣,因為必須能掌控自己的身體,才是上流人。\n飲食有知識,有教養,有節制,有合理的熱情,現在我愈講愈健康,愈完美了,但作者一邊梳理飲食文化如何成為法國文化最有代表性的一環,也有指出所謂上流、規範的虛榮、浮華與自相矛盾。他也沒有忽略到,在這些看來普世而體面的規範當中,有一些東西是被邊緣化的,例如,女性。女性經常被認為只愛吃甜食,這是一種像小孩子般幼稚的表現,所以女性不會懂得真正欣賞美食,真正要去品嚐美食就不要帶女性了,只會令你分心。而許多關於女性與食物的刻板想法也是荒謬可笑的,例如覺得女人的胃口與性欲是呈正比的,戀愛中的女人就應該食欲好好,所以如果你和女人吃飯她沒有胃口,你就不用想下一步了——這真是毫無道理,完全錯晒。同時,女性又常被食物隱喻來寫,所謂「秀色可餐」。\n//p180-182//\n不過這本書並沒有跌入超級政治正確的問題,沒有太過讉責這些有性別意味的措辭,他摘錄了大量資料,只偶然地幽默調侃一下,其餘就讓讀者自己判斷,這種應該是一個歷史學家的眼光,保留著歷史的多元性,並讓歷史來回應當下。至於到底「饞」gourmandise有多正面多負面,我們對飲食的欲望應該節制到什麼程度、放縱到什麼程度,作者本身的態度是怎樣呢?我隱隱覺得他是稍稍傾向放縱那一邊的,因為他應該比較反對節制,他欣賞的是比「適度」多一點點。但客觀來看,作者所呈現的貪饞文化史,總是在兩種張力之間游走的,因為正如巴塔耶說,哪裡有禁忌,哪裡有踰越,為食都是在放縱中充滿掙扎的生存狀態,因為在控制的邊界反而可以看到更多元的存在。究竟為食呢樣嘢,係令你生活更加美好還是阻止你生活變得更加美好呢?看完本書後,至少可以說,為食有令人類文化史更加豐富美好。\n儀態之後就是品味,1803年美食享樂主義者格里蒙.德.拉雷涅《饕客年鑑》,應該算係米芝蓮前身,就是飲食品味的重要指標。而飲食的高雅品味離不開高級的語言能力,一個美食家需要用優美的語言去形容食物,並指出它的來源地和烹飪方法。食物本身也開始象徵身份地位,例如鷹嘴豆、蘿蔔、扁豆、黑血腸就是窮人的食物,時鮮的蘆荀、朝鮮薊、甜瓜、無花果及西洋梨就是上流社會的喜好,果醬、蜜餞、杏仁小餅之類的甜食都是高貴嘢。上流的饕客端正得體,儀容整潔、容光煥發,而下等的饕餮之後就猥瑣、貪婪、肥而走樣,因為必須能掌控自己的身體,才是上流人。\n飲食有知識,有教養,有節制,有合理的熱情,現在我愈講愈健康,愈完美了,但作者一邊梳理飲食文化如何成為法國文化最有代表性的一環,也有指出所謂上流、規範的虛榮、浮華與自相矛盾。他也沒有忽略到,在這些看來普世而體面的規範當中,有一些東西是被邊緣化的,例如,女性。女性經常被認為只愛吃甜食,這是一種像小孩子般幼稚的表現,所以女性不會懂得真正欣賞美食,真正要去品嚐美食就不要帶女性了,只會令你分心。而許多關於女性與食物的刻板想法也是荒謬可笑的,例如覺得女人的胃口與性欲是呈正比的,戀愛中的女人就應該食欲好好,所以如果你和女人吃飯她沒有胃口,你就不用想下一步了——這真是毫無道理,完全錯晒。同時,女性又常被食物隱喻來寫,所謂「秀色可餐」。\n由十六、十七世紀左右,由天主教和西方社會推動的「美食文化菁英化」運動,首先就是唾棄貪食者、暴食者,但推崇端正得體,知識豐富的「饕客」和美食家。到十八世紀,法國上流菁英已經視享樂為飲食的目的,而「貪饞」gourmandise這個詞也開始被收入百科全書。";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishEn50() public {
_claimToTraveloggersOwner();
string memory content = "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishEn140() public {
_claimToTraveloggersOwner();
string
memory content = "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishEn200() public {
_claimToTraveloggersOwner();
string
memory content = "Even if they fail to deter him, they are still valuable to isolate Russia from the world and as a punishment, according to Steven Pifer, a former US ambassador to Ukraine, appearing Thursday on CNNNN.";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishEn300() public {
_claimToTraveloggersOwner();
string
memory content = "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishEn500() public {
_claimToTraveloggersOwner();
string
memory content = "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishEn1000() public {
_claimToTraveloggersOwner();
string
memory content = "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishEn2000() public {
_claimToTraveloggersOwner();
string
memory content = "US markets rebounded, while Russia's haven't yet. Egan noted that the stock market dropped in the morning after news of the attacks on Ukraine, but then rebounded after Biden announced sanctions.\nRussia's stock market, on the other hand, lost a third of its value. The value of the ruble also tumbled.\n\"There are some real concerns from investors about Russia becoming a pariah state at this point,\" he said.\nConsider the unlikely nightmare scenario. I talked to Tom Collina, policy director at the Ploughshares Fund -- which pushes to eliminate the dangers posed by nuclear weapons -- about what it means for the US and Russia, the world's two top nuclear countries, to be in a standoff.\nHe said Putin's new demeanor means the world needs to view him differently. The worst possible scenario, which is very unlikely, is the US and Russia in an armed conflict and a miscalculation triggering nuclear war.\n\"I think all bets are off as to knowing what he's going to do next,\" Collina said.\nNobody wants to trigger such a scenario, but with nuclear powers in conflict, there is major concern.\n\"Even if they don't want to get into a nuclear conflict, they could by accident or miscalculation,\" Collina said. \"In the fog of war, things can happen that no one ever wanted to happen.\"\nThere is already nuclear talk. Ukraine used to house many of the Soviet Union's nuclear weapons but gave them up in 1994 in exchange for a security guarantee, known as the Budapest Memorandum, from the US, the United Kingdom and Russia. That promise was clearly violated this week.\nPutin made up a conspiracy theory that the US and Ukraine were plotting to place nuclear weapons back in Ukraine as a pretext for his invasion.\nFrench Foreign Minister Jean-Yves Le Drian said Thursday on French television, according to Reuters, that his country viewed some of Putin's recent comments as a threat to use nuclear weapons in the Ukraine conflict.\n\"Yes, I think that Vladimir Putin must also understand that the Atlantic alliance is a nuclear alliance.\n";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
function testPublishEn5000() public {
_claimToTraveloggersOwner();
string
memory content = "US markets rebounded, while Russia's haven't yet. Egan noted that the stock market dropped in the morning after news of the attacks on Ukraine, but then rebounded after Biden announced sanctions.\nRussia's stock market, on the other hand, lost a third of its value. The value of the ruble also tumbled.\"There are some real concerns from investors about Russia becoming a pariah state at this point,\" he said.Consider the unlikely nightmare scenario. I talked to Tom Collina, policy director at the Ploughshares Fund -- which pushes to eliminate the dangers posed by nuclear weapons -- about what it means for the US and Russia, the world's two top nuclear countries, to be in a standoff.\nHe said Putin's new demeanor means the world needs to view him differently. The worst possible scenario, which is very unlikely, is the US and Russia in an armed conflict and a miscalculation triggering nuclear war.\"I think all bets are off as to knowing what he's going to do next,\" Collina said.\nNobody wants to trigger such a scenario, but with nuclear powers in conflict, there is major concern.\"Even if they don't want to get into a nuclear conflict, they could by accident or miscalculation,\" Collina said. \"In the fog of war, things can happen that no one ever wanted to happen.\"\nThere is already nuclear talk. Ukraine used to house many of the Soviet Union's nuclear weapons but gave them up in 1994 in exchange for a security guarantee, known as the Budapest Memorandum, from the US, the United Kingdom and Russia. That promise was clearly violated this week.\nPutin made up a conspiracy theory that the US and Ukraine were plotting to place nuclear weapons back in Ukraine as a pretext for his invasion.\nFrench Foreign Minister Jean-Yves Le Drian said Thursday on French television, according to Reuters, that his country viewed some of Putin's recent comments as a threat to use nuclear weapons in the Ukraine conflict.\"Yes, I think that Vladimir Putin must also understand that the Atlantic alliance is a nuclear alliance.\nA version of this story appeared in CNN's What Matters newsletter. To get it in your inbox, sign up for free here.\n(CNN)Europe woke up to a major war on Thursday after Russian President Vladimir Putin launched a violent, multipronged invasion of Ukraine, the democracy that sits between NATO countries and Russia.\nNow that it is clear Putin will sacrifice lives and Russian wealth to reconstitute parts of the old Soviet Union, European and US troops are scrambling to fortify the wall of NATO countries that borders Ukraine -- and the fear that he could move farther, past Ukraine, is now very real.\nOn a continent that spent decades as the front line of the Cold War in a standoff over ideology between nuclear powers, this new war seems like a return to the sort of conventional warfare that marked Europe before the world wars, when countries did battle and tested their alliances.\nNo one in recent weeks has claimed to know what's in Putin's head. But few guessed he would so boldly try to take over Ukraine.\nUS markets rebounded, while Russia's haven't yet. Egan noted that the stock market dropped in the morning after news of the attacks on Ukraine, but then rebounded after Biden announced sanctions.\nRussia's stock market, on the other hand, lost a third of its value. The value of the ruble also tumbled.\"There are some real concerns from investors about Russia becoming a pariah state at this point,\" he said.Consider the unlikely nightmare scenario. I talked to Tom Collina, policy director at the Ploughshares Fund -- which pushes to eliminate the dangers posed by nuclear weapons -- about what it means for the US and Russia, the world's two top nuclear countries, to be in a standoff.\nHe said Putin's new demeanor means the world needs to view him differently. The worst possible scenario, which is very unlikely, is the US and Russia in an armed conflict and a miscalculation triggering nuclear war.\"I think all bets are off as to knowing what he's going to do next,\" Collina said.\nNobody wants to trigger such a scenario, but with nuclear powers in conflict, there is major concern.\"Even if they don't want to get into a nuclear conflict, they could by accident or miscalculation,\" Collina said. \"In the fog of war, things can happen that no one ever wanted to happen.\"\nThere is already nuclear talk. Ukraine used to house many of the Soviet Union's nuclear weapons but gave them up in 1994 in exchange for a security guarantee, known as the Budapest Memorandum, from the US, the United Kingdom and Russia. That promise was clearly violated this week.\nPutin made up a conspiracy theory that the US and Ukraine were plotting to place nuclear weapons back in Ukraine as a pretext for his invasion.\nFrench Foreign Minister Jean-Yves Le Drian said Thursday on French television, according to Reuters, that his country viewed some of Putin's recent comments as a threat to use nuclear weapons in the Ukraine conflict.\"Yes, I think that Vladimir Putin must also understand that the Atlantic alliance is a nuclear alliance.";
bytes32 contentHash = keccak256(abi.encodePacked(content));
bytes32 returnContentHash = _publish(content, true);
assertEq(contentHash, returnContentHash);
}
/**
* Set title, description, fork price and publish new content
* in one transaction
*/
function testMulticall() public {
_claimToTraveloggersOwner();
bytes[] memory data = new bytes[](4);
// title
string memory title = "Sit deserunt nulla aliqua ex nisi";
data[0] = abi.encodeWithSignature("setTitle(uint256,string)", CLAIM_TOKEN_START_ID, title);
// description
string
memory description = "Deserunt proident dolor id Lorem pariatur irure adipisicing labore labore aute sunt aliquip culpa consectetur laboris.";
data[1] = abi.encodeWithSignature("setDescription(uint256,string)", CLAIM_TOKEN_START_ID, description);
// fork price
uint256 forkPrice = 0.122 ether;
data[2] = abi.encodeWithSignature("setForkPrice(uint256,uint256)", CLAIM_TOKEN_START_ID, forkPrice);
// publish
string
memory content = "Fugiat proident irure et mollit quis occaecat labore cupidatat ut aute tempor esse exercitation eiusmod. Do commodo incididunt quis exercitation laboris adipisicing nisi. Magna aliquip aute mollit id aliquip incididunt sint ea laborum mollit eiusmod do aliquip aute. Enim ea eiusmod pariatur mollit pariatur irure consectetur anim. Proident elit nisi ea laboris ad reprehenderit. Consectetur consequat excepteur duis tempor nulla id in commodo occaecat. Excepteur quis nostrud velit exercitation ut ullamco tempor nulla non. Occaecat laboris anim labore ut adipisicing nisi. Sit enim dolor eiusmod ipsum nulla quis aliqua reprehenderit ea. Lorem sit tempor consequat magna Lorem deserunt duis.";
data[3] = abi.encodeWithSignature("publish(uint256,string)", CLAIM_TOKEN_START_ID, content);
// call
bytes32 contentHash = keccak256(abi.encodePacked(content));
vm.prank(TRAVELOGGERS_OWNER);
vm.expectEmit(true, true, false, false);
emit SetTitle(CLAIM_TOKEN_START_ID, title);
vm.expectEmit(true, true, false, false);
emit SetDescription(CLAIM_TOKEN_START_ID, description);
vm.expectEmit(true, true, false, false);
emit SetForkPrice(CLAIM_TOKEN_START_ID, forkPrice);
vm.expectEmit(true, true, true, false);
emit Content(TRAVELOGGERS_OWNER, contentHash, content);
vm.expectEmit(true, true, false, false);
emit Publish(CLAIM_TOKEN_START_ID, contentHash);
logbook.multicall(data);
}
/**
* Donate, Fork
*/
function testDonate(uint96 amount) public {
_claimToTraveloggersOwner();
// donate
vm.deal(PUBLIC_SALE_MINTER, amount);
vm.prank(PUBLIC_SALE_MINTER);
if (amount > 0) {
// uint256 contractBalance = address(this).balance;
vm.expectEmit(true, true, true, false);
emit Donate(CLAIM_TOKEN_START_ID, PUBLIC_SALE_MINTER, amount);
logbook.donate{value: amount}(CLAIM_TOKEN_START_ID);
// assertEq(address(this).balance, contractBalance + amount);
} else {
vm.expectRevert(abi.encodePacked(bytes4(keccak256("ZeroAmount()"))));
logbook.donate{value: amount}(CLAIM_TOKEN_START_ID);
}
// no logbook
vm.deal(PUBLIC_SALE_MINTER, 1 ether);
vm.prank(PUBLIC_SALE_MINTER);
vm.expectRevert(abi.encodePacked(bytes4(keccak256("TokenNotExists()"))));
logbook.donate{value: 1 ether}(CLAIM_TOKEN_START_ID + 1);
}
function testDonateWithCommission(uint96 amount, uint96 bps) public {
_claimToTraveloggersOwner();
bool isInvalidBPS = bps > _ROYALTY_BPS_COMMISSION_MAX;
// donate
vm.deal(PUBLIC_SALE_MINTER, amount);
vm.prank(PUBLIC_SALE_MINTER);
if (amount > 0) {
if (isInvalidBPS) {
vm.expectRevert(abi.encodeWithSignature("InvalidBPS(uint256,uint256)", 0, 2000));
} else {
vm.expectEmit(true, true, true, false);
emit Donate(CLAIM_TOKEN_START_ID, PUBLIC_SALE_MINTER, amount);
}
logbook.donateWithCommission{value: amount}(CLAIM_TOKEN_START_ID, FRONTEND_OPERATOR, bps);
} else {
vm.expectRevert(abi.encodePacked(bytes4(keccak256("ZeroAmount()"))));
logbook.donateWithCommission{value: amount}(CLAIM_TOKEN_START_ID, FRONTEND_OPERATOR, bps);
}
// no logbook
vm.deal(PUBLIC_SALE_MINTER, 1 ether);
vm.prank(PUBLIC_SALE_MINTER);
vm.expectRevert(abi.encodePacked(bytes4(keccak256("TokenNotExists()"))));
logbook.donateWithCommission{value: 1 ether}(CLAIM_TOKEN_START_ID + 1, FRONTEND_OPERATOR, bps);
}
function testFork(uint96 amount, string calldata content) public {
_claimToTraveloggersOwner();
// no logbook
vm.deal(PUBLIC_SALE_MINTER, amount);
vm.prank(PUBLIC_SALE_MINTER);
vm.expectRevert(abi.encodePacked(bytes4(keccak256("TokenNotExists()"))));
logbook.fork{value: amount}(CLAIM_TOKEN_START_ID + 1, 1);
// no content
vm.deal(PUBLIC_SALE_MINTER, amount);
vm.prank(PUBLIC_SALE_MINTER);
vm.expectRevert(abi.encodeWithSignature("InsufficientLogs(uint32)", 0));
logbook.fork{value: amount}(CLAIM_TOKEN_START_ID, 1);
_publish(content, true);
// value too small
if (amount > 1) {
_setForkPrice(amount);
vm.deal(PUBLIC_SALE_MINTER, amount);
vm.prank(PUBLIC_SALE_MINTER);
vm.expectRevert(abi.encodeWithSignature("InsufficientAmount(uint256,uint256)", amount / 2, amount));
logbook.fork{value: amount / 2}(CLAIM_TOKEN_START_ID, 1);
}
// fork
_setForkPrice(amount);
// uint256 contractBalance = address(this).balance;
vm.deal(PUBLIC_SALE_MINTER, amount);
vm.prank(PUBLIC_SALE_MINTER);
vm.expectEmit(true, true, true, true);
emit Fork(CLAIM_TOKEN_START_ID, CLAIM_TOKEN_END_ID + 1, PUBLIC_SALE_MINTER, 1, amount);
logbook.fork{value: amount}(CLAIM_TOKEN_START_ID, 1);
// assertEq(address(this).balance, contractBalance + amount);
}
function testForkRecursively(uint8 forkCount, uint96 forkPrice) public {
vm.assume(forkCount <= 64);
_claimToTraveloggersOwner();
_publish("1234", true);
_setForkPrice(forkPrice);
// forks
address logbookOwner = TRAVELOGGERS_OWNER;
uint256 nextTokenId = CLAIM_TOKEN_START_ID;
for (uint32 i = 0; i < forkCount; i++) {
address prevLogbookOwner = logbookOwner;
logbookOwner = address(uint160(i + 10000));
// fork
vm.deal(logbookOwner, forkPrice);
vm.prank(logbookOwner);
nextTokenId = logbook.fork{value: forkPrice}(nextTokenId, 1);
// append log
string memory content = Strings.toString(i);
vm.prank(logbookOwner);
logbook.publish(nextTokenId, content);
uint256 feesLogbookOwner = (forkPrice * _ROYALTY_BPS_LOGBOOK_OWNER) / 10000;
uint256 feesPerLogAuthor = (forkPrice - feesLogbookOwner) / (i + 1);
// check owner balance
assertEq(logbook.getBalance(prevLogbookOwner), feesLogbookOwner + feesPerLogAuthor);
}
assertEq(logbookOwner, logbook.ownerOf(nextTokenId));
// check logs
(bytes32[] memory contentHashes, address[] memory authors) = logbook.getLogs(nextTokenId);
ILogbook.Book memory book = logbook.getLogbook(nextTokenId);
assertEq(book.logCount, forkCount + 1);
assertEq(forkCount + 1, contentHashes.length);
assertEq(forkCount + 1, authors.length);
}
function testForkWithCommission(
uint96 amount,
string calldata content,
uint256 bps
) public {
bool isInvalidBPS = bps > _ROYALTY_BPS_COMMISSION_MAX;
_claimToTraveloggersOwner();
_publish(content, true);
_setForkPrice(amount);
vm.deal(PUBLIC_SALE_MINTER, amount);
vm.prank(PUBLIC_SALE_MINTER);
if (isInvalidBPS) {
vm.expectRevert(abi.encodeWithSignature("InvalidBPS(uint256,uint256)", 0, 2000));
} else {
vm.expectEmit(true, true, true, true);
emit Fork(CLAIM_TOKEN_START_ID, CLAIM_TOKEN_END_ID + 1, PUBLIC_SALE_MINTER, 1, amount);
}
uint256 newTokenId = logbook.forkWithCommission{value: amount}(CLAIM_TOKEN_START_ID, 1, FRONTEND_OPERATOR, bps);
if (!isInvalidBPS) {
// get tokenURI
logbook.tokenURI(newTokenId);
}
}
/**
* Split Royalty, Withdraw
*/
function testSplitRoyalty(
uint8 logCount,
uint8 endAt,
uint96 forkPrice
) public {
vm.assume(logCount <= 64);
_claimToTraveloggersOwner();
_setForkPrice(forkPrice);
// append logs
address logbookOwner = TRAVELOGGERS_OWNER;
address firstAuthor;
for (uint32 i = 0; i < logCount; i++) {
// transfer to new owner
address currentOwner = logbook.ownerOf(CLAIM_TOKEN_START_ID);
logbookOwner = address(uint160(i + 10000));
assertTrue(currentOwner != logbookOwner);
if (i == 0) {
firstAuthor = logbookOwner;
}
vm.deal(currentOwner, forkPrice);
vm.prank(currentOwner);
logbook.transferFrom(currentOwner, logbookOwner, CLAIM_TOKEN_START_ID);
// append log
string memory content = Strings.toString(i);
vm.deal(logbookOwner, forkPrice);
vm.prank(logbookOwner);
logbook.publish(CLAIM_TOKEN_START_ID, content);
}
assertEq(logbookOwner, logbook.ownerOf(CLAIM_TOKEN_START_ID));
// check logs
(bytes32[] memory contentHashes, address[] memory authors) = logbook.getLogs(CLAIM_TOKEN_START_ID);
ILogbook.Book memory book = logbook.getLogbook(CLAIM_TOKEN_START_ID);
assertEq(book.logCount, logCount);
assertEq(logCount, contentHashes.length);
assertEq(logCount, authors.length);
uint32 maxEndAt = uint32(book.contentHashes.length);
vm.deal(PUBLIC_SALE_MINTER, forkPrice);
vm.prank(PUBLIC_SALE_MINTER);
// fork
if (logCount <= 0 || endAt <= 0 || maxEndAt < endAt) {
vm.expectRevert(abi.encodeWithSignature("InsufficientLogs(uint32)", logCount));
logbook.fork{value: forkPrice}(CLAIM_TOKEN_START_ID, endAt);
return;
} else {
vm.expectEmit(true, true, true, true);
emit Fork(CLAIM_TOKEN_START_ID, CLAIM_TOKEN_END_ID + 1, PUBLIC_SALE_MINTER, endAt, forkPrice);
}
uint256 newTokenId = logbook.fork{value: forkPrice}(CLAIM_TOKEN_START_ID, endAt);
// get tokenURI
logbook.tokenURI(newTokenId);
// check log count
ILogbook.Book memory newBook = logbook.getLogbook(newTokenId);
assertEq(book.logCount - maxEndAt + endAt, newBook.logCount);
// check content hashes
(bytes32[] memory newContentHashes, ) = logbook.getLogs(newTokenId);
assertEq(keccak256(abi.encodePacked(Strings.toString(uint32(0)))), newContentHashes[0]);
assertEq(keccak256(abi.encodePacked(Strings.toString(uint32(endAt - 1)))), newContentHashes[endAt - 1]);
// check balances
uint256 feesLogbookOwner = (forkPrice * _ROYALTY_BPS_LOGBOOK_OWNER) / 10000;
uint256 feesPerLogAuthor = (forkPrice - feesLogbookOwner) / endAt;
if (logCount == endAt) {
// logbook owner
assertEq(logbook.getBalance(logbookOwner), feesLogbookOwner + feesPerLogAuthor);
} else {
// logbook owner
assertEq(logbook.getBalance(logbookOwner), feesLogbookOwner);
// first author
if (endAt > 2) {
uint256 firstAuthorBalance = logbook.getBalance(firstAuthor);
assertEq(firstAuthorBalance, feesPerLogAuthor);
}
}
}
function testWithdraw() public {
uint256 donationValue = 3.13 ether;
uint32 logCount = 64;
_claimToTraveloggersOwner();
// append logs
for (uint32 i = 0; i < logCount; i++) {
// transfer to new owner
address currentOwner = logbook.ownerOf(CLAIM_TOKEN_START_ID);
address newOwner = address(uint160(i + 10000));
assertTrue(currentOwner != newOwner);
vm.prank(currentOwner);
logbook.transferFrom(currentOwner, newOwner, CLAIM_TOKEN_START_ID);
// append log
string memory content = string(abi.encodePacked(i));
vm.deal(newOwner, donationValue);
vm.prank(newOwner);
logbook.publish(CLAIM_TOKEN_START_ID, content);
}
// uint256 contractBalance = address(this).balance;
// donate
vm.deal(PUBLIC_SALE_MINTER, donationValue);
vm.prank(PUBLIC_SALE_MINTER);
vm.expectEmit(true, true, true, false);
emit Donate(CLAIM_TOKEN_START_ID, PUBLIC_SALE_MINTER, donationValue);
logbook.donate{value: donationValue}(CLAIM_TOKEN_START_ID);
// logbook owner withdrawl
address owner = address(uint160(logCount - 1 + 10000));
uint256 feesLogbookOwner = (donationValue * _ROYALTY_BPS_LOGBOOK_OWNER) / 10000;
uint256 feesPerLogAuthor = (donationValue - feesLogbookOwner) / logCount;
uint256 ownerBalance = logbook.getBalance(owner);
assertEq(ownerBalance, feesLogbookOwner + feesPerLogAuthor);
uint256 ownerWalletBalance = owner.balance;
vm.prank(owner);
vm.expectEmit(true, true, false, false);
emit Withdraw(owner, ownerBalance);
logbook.withdraw();
assertEq(owner.balance, ownerWalletBalance + ownerBalance);
assertEq(logbook.getBalance(owner), 0);
// uint256 contractBalanceAfterOwnerWithdraw = address(this).balance;
// assertEq(contractBalanceAfterOwnerWithdraw, contractBalance - ownerWalletBalance - ownerBalance);
// previous author withdrawl
address secondLastOwner = address(uint160(logCount - 2 + 10000));
uint256 secondLastOwnerBalance = logbook.getBalance(secondLastOwner);
assertEq(secondLastOwnerBalance, feesPerLogAuthor);
uint256 secondLastOwnerWalletBalance = secondLastOwner.balance;
vm.prank(secondLastOwner);
vm.expectEmit(true, true, false, false);
emit Withdraw(secondLastOwner, secondLastOwnerBalance);
logbook.withdraw();
assertEq(secondLastOwner.balance, secondLastOwnerWalletBalance + secondLastOwnerBalance);
assertEq(logbook.getBalance(secondLastOwner), 0);
// assertEq(address(this).balance, secondLastOwnerWalletBalance - feesPerLogAuthor);
}
}
| Donate, Fork/ donate uint256 contractBalance = address(this).balance; assertEq(address(this).balance, contractBalance + amount); | function testDonate(uint96 amount) public {
_claimToTraveloggersOwner();
vm.deal(PUBLIC_SALE_MINTER, amount);
vm.prank(PUBLIC_SALE_MINTER);
if (amount > 0) {
vm.expectEmit(true, true, true, false);
emit Donate(CLAIM_TOKEN_START_ID, PUBLIC_SALE_MINTER, amount);
vm.expectRevert(abi.encodePacked(bytes4(keccak256("ZeroAmount()"))));
}
vm.prank(PUBLIC_SALE_MINTER);
vm.expectRevert(abi.encodePacked(bytes4(keccak256("TokenNotExists()"))));
}
| 6,459,397 |
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 Varia LLC
/// Wet Code by Erich Dylus & Sarah Brennan
/// Dry Code by LexDAO LLC
pragma solidity ^0.8.6;
/// @notice This contract manages function access control, adapted from @boringcrypto (https://github.com/boringcrypto/BoringSolidity).
contract Ownable {
address public owner;
address public pendingOwner;
event TransferOwnership(address indexed from, address indexed to);
event TransferOwnershipClaim(address indexed from, address indexed to);
/// @notice Initialize contract.
constructor() {
owner = msg.sender;
emit TransferOwnership(address(0), msg.sender);
}
/// @notice Access control modifier that requires modified function to be called by `owner` account.
modifier onlyOwner {
require(msg.sender == owner, 'Ownable:!owner');
_;
}
/// @notice The `pendingOwner` can claim `owner` account.
function claimOwner() external {
require(msg.sender == pendingOwner, 'Ownable:!pendingOwner');
emit TransferOwnership(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
/// @notice Transfer `owner` account.
/// @param to Account granted `owner` access control.
/// @param direct If 'true', ownership is directly transferred.
function transferOwnership(address to, bool direct) external onlyOwner {
if (direct) {
owner = to;
emit TransferOwnership(msg.sender, to);
} else {
pendingOwner = to;
emit TransferOwnershipClaim(msg.sender, to);
}
}
}
/// @notice This contract allows potential delegates of DAO voting power to ethSign a ricardian template for delegation disclosures.
contract VoteDelegateDisclosure is Ownable {
uint8 public version; // counter for ricardian template versions
string public template; // string stored for ricardian template signature - amendable by `owner`
mapping(address => bool) public registrations; // maps signatories to registration status (true/false)
event Amend(string template);
event Sign(string details);
event Revoke(string details);
constructor(string memory _template) {
template = _template; // initialize ricardian template
}
function amend(string calldata _template) external onlyOwner {
version++; // increment ricardian template version
template = _template; // update ricardian template string stored in this contract
emit Amend(_template); // emit amendment details in event for apps
}
function sign(string calldata details) external {
registrations[msg.sender] = true; // register caller signatory
emit Sign(details); // emit signature details in event for apps
}
function revoke(string calldata details) external {
registrations[msg.sender] = false; // nullify caller registration
emit Revoke(details); // emit revocation details in event for apps
}
} | The `pendingOwner` can claim `owner` account. | function claimOwner() external {
require(msg.sender == pendingOwner, 'Ownable:!pendingOwner');
emit TransferOwnership(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
}
| 1,605,279 |
./full_match/3/0xd486C084629440cd737D69cC9ecEf3c35273F053/sources/scripts/Assets.sol | Permet de quantifier et numériser les chiffres | function give() public view returns (uint256){
return number;
}
| 8,144,807 |
pragma solidity 0.4.21;
import "./GroupAdmin.sol";
import "../zeppelin/lifecycle/Destructible.sol";
contract Conference is Destructible, GroupAdmin {
// string public name;
uint256 public deposit;
uint public limitOfParticipants;
uint public registered;
uint public attended;
bool public ended;
bool public cancelled;
uint public endedAt;
uint public coolingPeriod;
uint256 public payoutAmount;
// string public description;
// uint public date;
// bytes8 public geohash;
mapping (address => Participant) public participants;
mapping (uint => address) public participantsIndex;
struct Participant {
address addr;
bool attended;
bool paid;
}
event RegisterEvent(address addr, uint registered, uint limitOfParticipants, bool isFull);
event AttendEvent(address addr);
event PaybackEvent(uint256 _payout);
event WithdrawEvent(address addr, uint256 _payout);
event CancelEvent();
event ClearEvent(address addr, uint256 leftOver);
event ChangeNameEvent(string name);
/* Modifiers */
modifier onlyActive {
require(!ended);
_;
}
modifier noOneRegistered {
require(registered == 0);
_;
}
modifier onlyEnded {
require(ended);
_;
}
/* Public functions */
/**
* @dev Construcotr.
* @param _owner Address of the owner of the event, group admin
* @param _deposit The amount each participant deposits. The default is set to 0.02 Ether. The amount cannot be changed once deployed.
* @param _limitOfParticipants The number of participant. The default is set to 20. The number can be changed by the owner of the event.
* @param _coolingPeriod The period participants should withdraw their deposit after the event ends. After the cooling period, the event owner can claim the remining deposits.
*/
function Conference (
address _owner,
// string _name,
uint256 _deposit,
uint _limitOfParticipants,
uint _coolingPeriod
// string _description,
// uint _date,
// bytes8 _geohash
) public {
require(_owner != 0x0);
owner = _owner;
// if (bytes(_name).length != 0){
// name = _name;
// } else {
// name = "Test";
// }
if(_deposit != 0){
deposit = _deposit;
}else{
deposit = 0.02 ether;
}
if (_limitOfParticipants != 0){
limitOfParticipants = _limitOfParticipants;
}else{
limitOfParticipants = 20;
}
if (_coolingPeriod != 0) {
coolingPeriod = _coolingPeriod;
} else {
coolingPeriod = 1 weeks;
}
// if (bytes(_description).length != 0) {
// description = _description;
// } else {
// description = "Test";
// }
// if (_date != 0) {
// date = _date;
// } else {
// date = block.timestamp;
// }
// if (_geohash.length != 0) {
// geohash = _geohash;
// } else {
// geohash = 0x0;
// }
}
/**
* @dev Registers message sender.
*/
function register() external payable onlyActive{
registerInternal();
bool full = isFull();
emit RegisterEvent(msg.sender, registered, limitOfParticipants, full);
}
/**
* @dev The internal function to register participant
*/
function registerInternal() internal {
require(msg.value == deposit);
require(registered < limitOfParticipants);
require(!isRegistered(msg.sender));
registered++;
participantsIndex[registered] = msg.sender;
participants[msg.sender] = Participant(msg.sender, false, false);
}
/**
* @dev Withdraws deposit after the event is over.
*/
function withdraw() external onlyEnded{
require(payoutAmount > 0);
Participant storage participant = participants[msg.sender];
require(participant.addr == msg.sender);
require(cancelled || participant.attended);
require(participant.paid == false);
participant.paid = true;
participant.addr.transfer(payoutAmount);
emit WithdrawEvent(msg.sender, payoutAmount);
}
/* Constants */
/**
* @dev Returns total balance of the contract. This function can be deprecated when refactroing front end code.
* @return The total balance of the contract.
*/
function totalBalance() view public returns (uint256){
return address(this).balance;
}
/**
* @dev Returns true if the given user is registered.
* @param _addr The address of a participant.
* @return True if the address exists in the pariticipant list.
*/
function isRegistered(address _addr) view public returns (bool){
return participants[_addr].addr != address(0);
}
/**
* @dev Returns true if the given user is attended.
* @param _addr The address of a participant.
* @return True if the user is marked as attended by admin.
*/
function isAttended(address _addr) view public returns (bool){
return isRegistered(_addr) && participants[_addr].attended;
}
/**
* @dev Returns true if the given user has withdrawn his/her deposit.
* @param _addr The address of a participant.
* @return True if the attendee has withdrawn his/her deposit.
*/
function isPaid(address _addr) view public returns (bool){
return isRegistered(_addr) && participants[_addr].paid;
}
/**
* @dev Show the payout amount each participant can withdraw.
* @return The amount each participant can withdraw.
*/
function payout() view public returns(uint256){
if (attended == 0) return 0;
return uint(totalBalance()) / uint(attended);
}
/* Admin only functions */
/**
* @dev Ends the event by owner
*/
function payback() external onlyOwner onlyActive{
payoutAmount = payout();
ended = true;
endedAt = now;
emit PaybackEvent(payoutAmount);
}
/**
* @dev Cancels the event by owner. When the event is canceled each participant can withdraw their deposit back.
*/
function cancel() external onlyOwner onlyActive{
payoutAmount = deposit;
cancelled = true;
ended = true;
endedAt = now;
emit CancelEvent();
}
/**
* @dev The event owner transfer the outstanding deposits if there are any unclaimed deposits after cooling period
*/
function clear() external onlyOwner onlyEnded{
require(now > endedAt + coolingPeriod);
uint leftOver = totalBalance();
owner.transfer(leftOver);
emit ClearEvent(owner, leftOver);
}
/**
* @dev Change the capacity of the event. The owner can change it until event is over.
* @param _limitOfParticipants the number of the capacity of the event.
*/
function setLimitOfParticipants(uint _limitOfParticipants) external onlyOwner onlyActive{
limitOfParticipants = _limitOfParticipants;
}
/**
* @dev Change the name of the event. The owner can change it as long as no one has registered yet.
* @param _name the name of the event.
*/
function changeName(string _name) external onlyOwner noOneRegistered{
// name = _name;
require(bytes(_name).length > 0);
emit ChangeNameEvent(_name);
}
/**
* @dev Mark participants as attended. The attendance cannot be undone.
* @param _addresses The list of participant's address.
*/
function attend(address[] _addresses) external onlyAdmin onlyActive{
for( uint i = 0; i < _addresses.length; i++){
address _addr = _addresses[i];
require(isRegistered(_addr));
require(!isAttended(_addr));
emit AttendEvent(_addr);
participants[_addr].attended = true;
attended++;
}
}
function isFull() public view returns(bool) {
if (registered < limitOfParticipants) {
return false;
} else {
return true;
}
}
}
| Change the name of the event. The owner can change it as long as no one has registered yet. _name the name of the event./ name = _name; | function changeName(string _name) external onlyOwner noOneRegistered{
require(bytes(_name).length > 0);
emit ChangeNameEvent(_name);
}
| 15,829,966 |
/**
*Submitted for verification at Etherscan.io on 2021-05-23
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
contract Owned {
address public owner;
address public proposedOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() virtual {
require(msg.sender == owner);
_;
}
/**
* @dev propeses a new owner
* Can only be called by the current owner.
*/
function proposeOwner(address payable _newOwner) external onlyOwner {
proposedOwner = _newOwner;
}
/**
* @dev claims ownership of the contract
* Can only be called by the new proposed owner.
*/
function claimOwnership() external {
require(msg.sender == proposedOwner);
emit OwnershipTransferred(owner, proposedOwner);
owner = proposedOwner;
}
}
interface IPika {
function minSupply() external returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function burn(uint256 value) external;
}
contract PikaStaking is Owned {
address public communityWallet;
uint256 public totalAmountStaked = 0;
mapping(address => uint256) public balances;
mapping(address => uint256) public claimPeriods;
IPika public pika;
uint256 public periodNonce = 0;
uint256 public periodFinish;
uint256 public minPeriodDuration = 14 days;
uint256 public rewardPerToken = 0;
uint256 public maxInitializationReward;
event Staked(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
event RewardClaimed(address indexed user, uint256 amount);
event StakingPeriodStarted(uint256 totalRewardPool, uint256 periodFinish);
event MinPeriodDurationUpdated(uint256 oldDuration, uint256 newDuration);
event MaxInitializationRewardUpdated(uint256 oldValue, uint256 newValue);
constructor(address _token, address _communityWallet) {
pika = IPika(_token);
communityWallet = _communityWallet;
maxInitializationReward = 1000000000 ether;
periodFinish = block.timestamp + 3 days;
}
/**
* @notice allows a user to stake tokens
* @dev requires to claim pending rewards before being able to stake more tokens
* @param _amount of tokens to stake
*/
function stake(uint256 _amount) public {
uint256 balance = balances[msg.sender];
if (balance > 0) {
require(
claimPeriods[msg.sender] == periodNonce,
"Claim your reward before staking more tokens"
);
}
pika.transferFrom(msg.sender, address(this), _amount);
uint256 burnedAmount = (_amount * 12) / 100;
if (pika.totalSupply() - burnedAmount >= pika.minSupply()) {
pika.burn(burnedAmount);
} else {
burnedAmount = 0;
}
uint256 communityWalletAmount = (_amount * 3) / 100;
pika.transfer(communityWallet, communityWalletAmount);
uint256 userBalance = _amount - burnedAmount - communityWalletAmount;
balances[msg.sender] += userBalance;
claimPeriods[msg.sender] = periodNonce;
totalAmountStaked += userBalance;
emit Staked(msg.sender, userBalance);
}
/**
* @notice allows a user to withdraw staked tokens
* @dev unclaimed tokens cannot be claimed after withdrawal
* @dev unstakes all tokens
*/
function withdraw() public {
uint256 balance = balances[msg.sender];
balances[msg.sender] = 0;
totalAmountStaked -= balance;
pika.transfer(msg.sender, balance);
emit Withdraw(msg.sender, balance);
}
/**
* @notice claims a reward for the staked tokens
* @dev can only claim once per staking period
*/
function claimReward() public {
uint256 balance = balances[msg.sender];
require(balance > 0, "No tokens staked");
require(
claimPeriods[msg.sender] < periodNonce,
"Wait for this period to finish before claiming your reward"
);
claimPeriods[msg.sender] = periodNonce;
uint256 reward = (balance * rewardPerToken) / 1 ether;
pika.transfer(msg.sender, reward);
emit RewardClaimed(msg.sender, reward);
}
/**
* @notice returns claimable reward for a user
* @param _user to check
*/
function claimableReward(address _user) public view returns (uint256) {
if (claimPeriods[_user] == periodNonce) {
return 0;
}
return (balances[_user] * rewardPerToken) / 1 ether;
}
/**
* @notice initializes new staking claim period
* @dev requires previous staking period to be over
* @dev only callable by anyone, msg.sender receives a portion of the staking pool as a reward
*/
function initNewRewardPeriod() external {
require(
block.timestamp >= periodFinish,
"Wait for claim period to finish"
);
require(totalAmountStaked > 0, "No tokens staked in contract");
uint256 rewardPool = pika.balanceOf(address(this)) - totalAmountStaked;
uint256 initializationReward = rewardPool / 1000;
if (initializationReward > maxInitializationReward) {
initializationReward = maxInitializationReward;
}
rewardPool -= initializationReward;
pika.transfer(msg.sender, initializationReward);
rewardPerToken = (rewardPool * 1 ether) / totalAmountStaked;
periodNonce++;
periodFinish = block.timestamp + minPeriodDuration;
emit StakingPeriodStarted(rewardPool, periodFinish);
}
/**
* @notice sets a new minimum duration for each staking claim period
* @dev only callable by owner
* @param _days amount of days the new staking claim period should at least last
*/
function setMinDuration(uint256 _days) external onlyOwner {
emit MinPeriodDurationUpdated(minPeriodDuration / 1 days, _days);
minPeriodDuration = _days * 1 days;
}
/**
* @notice sets maximum initialization reward
* @dev only callable by owner
* @param _newMaxReward new maximum reward paid out by initNewRewardPeriod function
*/
function setMaxInitializationReward(uint256 _newMaxReward)
external
onlyOwner
{
emit MaxInitializationRewardUpdated(
maxInitializationReward,
_newMaxReward
);
maxInitializationReward = _newMaxReward;
}
} | sets maximum initialization reward only callable by owner _newMaxReward new maximum reward paid out by initNewRewardPeriod function/ | function setMaxInitializationReward(uint256 _newMaxReward)
external
onlyOwner
{
emit MaxInitializationRewardUpdated(
maxInitializationReward,
_newMaxReward
);
maxInitializationReward = _newMaxReward;
}
| 15,430,190 |
./full_match/1/0x250ef5b1ec5ab0566BB5715daa61a49aB19e45E3/sources/contracts/TheDopePandas.sol | Verify whitelist requirements | function whitelistMint(uint256 _mintAmount, bytes32[] calldata _merkleProof) public payable mintCompliance(_mintAmount) mintPriceCompliance(_mintAmount) nonReentrant {
require(whitelistMintEnabled, 'The whitelist sale is not enabled!');
require(!whitelistClaimed[_msgSender()], 'Address already claimed!');
bytes32 leaf = keccak256(abi.encodePacked(_msgSender()));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), 'Invalid proof!');
whitelistClaimed[_msgSender()] = true;
_safeMint(_msgSender(), _mintAmount);
}
| 9,757,263 |
/**
* @title Certificate Library
* ░V░e░r░i░f░i░e░d░ ░O░n░ ░C░h░a░i░n░
* Visit https://verifiedonchain.com/
*/
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library CertificateLibrary {
struct Document {
bytes ipfsHash;
bytes32 transcriptHash;
bytes32 contentHash;
}
/**
* @notice Add Certification to a student
* @param _contentHash - Hash of the document
* @param _ipfsHash - IPFS Hash of the document
* @param _transcriptHash - Transcript Hash of the document
**/
function addCertification(Document storage self, bytes32 _contentHash, bytes _ipfsHash, bytes32 _transcriptHash) public {
self.ipfsHash = _ipfsHash;
self.contentHash= _contentHash;
self.transcriptHash = _transcriptHash;
}
/**
* @notice Validate Certification to a student
* @param _ipfsHash - IPFS Hash of the document
* @param _contentHash - Content Hash of the document
* @param _transcriptHash - Transcript Hash of the document
* @return Returns true if validation is successful
**/
function validate(Document storage self, bytes _ipfsHash, bytes32 _contentHash, bytes32 _transcriptHash) public view returns(bool) {
bytes storage ipfsHash = self.ipfsHash;
bytes32 contentHash = self.contentHash;
bytes32 transcriptHash = self.transcriptHash;
return contentHash == _contentHash && keccak256(ipfsHash) == keccak256(_ipfsHash) && transcriptHash == _transcriptHash;
}
/**
* @notice Validate IPFS Hash alone of a student
* @param _ipfsHash - IPFS Hash of the document
* @return Returns true if validation is successful
**/
function validateIpfsDoc(Document storage self, bytes _ipfsHash) public view returns(bool) {
bytes storage ipfsHash = self.ipfsHash;
return keccak256(ipfsHash) == keccak256(_ipfsHash);
}
/**
* @notice Validate Content Hash alone of a student
* @param _contentHash - Content Hash of the document
* @return Returns true if validation is successful
**/
function validateContentHash(Document storage self, bytes32 _contentHash) public view returns(bool) {
bytes32 contentHash = self.contentHash;
return contentHash == _contentHash;
}
/**
* @notice Validate Content Hash alone of a student
* @param _transcriptHash - Transcript Hash of the document
* @return Returns true if validation is successful
**/
function validateTranscriptHash(Document storage self, bytes32 _transcriptHash) public view returns(bool) {
bytes32 transcriptHash = self.transcriptHash;
return transcriptHash == _transcriptHash;
}
}
contract Certificate is Ownable {
using CertificateLibrary for CertificateLibrary.Document;
struct Certification {
mapping (uint => CertificateLibrary.Document) documents;
uint16 indx;
}
mapping (address => Certification) studentCertifications;
event CertificationAdded(address userAddress, uint docIndx);
/**
* @notice Add Certification to a student
* @param _student - Address of student
* @param _contentHash - Hash of the document
* @param _ipfsHash - IPFS Hash of the document
* @param _transcriptHash - Transcript Hash of the document
**/
function addCertification(address _student, bytes32 _contentHash, bytes _ipfsHash, bytes32 _transcriptHash) public onlyOwner {
uint currIndx = studentCertifications[_student].indx;
(studentCertifications[_student].documents[currIndx]).addCertification(_contentHash, _ipfsHash, _transcriptHash);
studentCertifications[_student].indx++;
emit CertificationAdded(_student, currIndx);
}
/**
* @notice Validate Certification to a student
* @param _student - Address of student
* @param _docIndx - Index of the document to be validated
* @param _contentHash - Content Hash of the document
* @param _ipfsHash - IPFS Hash of the document
* @param _transcriptHash - Transcript Hash of the GradeSheet
* @return Returns true if validation is successful
**/
function validate(address _student, uint _docIndx, bytes32 _contentHash, bytes _ipfsHash, bytes32 _transcriptHash) public view returns(bool) {
Certification storage certification = studentCertifications[_student];
return (certification.documents[_docIndx]).validate(_ipfsHash, _contentHash, _transcriptHash);
}
/**
* @notice Validate IPFS Hash alone of a student
* @param _student - Address of student
* @param _docIndx - Index of the document to be validated
* @param _ipfsHash - IPFS Hash of the document
* @return Returns true if validation is successful
**/
function validateIpfsDoc(address _student, uint _docIndx, bytes _ipfsHash) public view returns(bool) {
Certification storage certification = studentCertifications[_student];
return (certification.documents[_docIndx]).validateIpfsDoc(_ipfsHash);
}
/**
* @notice Validate Content Hash alone of a student
* @param _student - Address of student
* @param _docIndx - Index of the document to be validated
* @param _contentHash - Content Hash of the document
* @return Returns true if validation is successful
**/
function validateContentHash(address _student, uint _docIndx, bytes32 _contentHash) public view returns(bool) {
Certification storage certification = studentCertifications[_student];
return (certification.documents[_docIndx]).validateContentHash(_contentHash);
}
/**
* @notice Validate Transcript Hash alone of a student
* @param _student - Address of student
* @param _transcriptHash - Transcript Hash of the GradeSheet
* @return Returns true if validation is successful
**/
function validateTranscriptHash(address _student, uint _docIndx, bytes32 _transcriptHash) public view returns(bool) {
Certification storage certification = studentCertifications[_student];
return (certification.documents[_docIndx]).validateTranscriptHash(_transcriptHash);
}
/**
* @notice Get Certification Document Count
* @param _student - Address of student
* @return Returns the total number of certifications for a student
**/
function getCertifiedDocCount(address _student) public view returns(uint256) {
return studentCertifications[_student].indx;
}
/**
* @notice Get Certification Document from DocType
* @param _student - Address of student
* @param _docIndx - Index of the document to be validated
* @return Returns IPFSHash, ContentHash, TranscriptHash of the document
**/
function getCertificationDocument(address _student, uint _docIndx) public view onlyOwner returns (bytes, bytes32, bytes32) {
return ((studentCertifications[_student].documents[_docIndx]).ipfsHash, (studentCertifications[_student].documents[_docIndx]).contentHash, (studentCertifications[_student].documents[_docIndx]).transcriptHash);
}
/**
* @param _studentAddrOld - Address of student old
* @param _studentAddrNew - Address of student new
* May fail due to gas exceptions
* ADVICE:
* Check gas and then send
**/
function transferAll(address _studentAddrOld, address _studentAddrNew) public onlyOwner {
studentCertifications[_studentAddrNew] = studentCertifications[_studentAddrOld];
delete studentCertifications[_studentAddrOld];
}
/**
* @param _studentAddrOld - Address of student old
* @param _studentAddrNew - Address of student new
**/
function transferDoc(uint docIndx, address _studentAddrOld, address _studentAddrNew) public onlyOwner {
studentCertifications[_studentAddrNew].documents[docIndx] = studentCertifications[_studentAddrOld].documents[docIndx];
delete studentCertifications[_studentAddrOld].documents[docIndx];
}
} | Add Certification to a student _contentHash - Hash of the document _ipfsHash - IPFS Hash of the document _transcriptHash - Transcript Hash of the document/ | function addCertification(Document storage self, bytes32 _contentHash, bytes _ipfsHash, bytes32 _transcriptHash) public {
self.ipfsHash = _ipfsHash;
self.contentHash= _contentHash;
self.transcriptHash = _transcriptHash;
}
| 10,774,595 |
pragma solidity 0.4.24;
/**
* @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 Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface TokenInterface {
function totalSupply() external constant returns (uint);
function balanceOf(address tokenOwner) external constant returns (uint balance);
function allowance(address tokenOwner, address spender) external constant returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
function burn(uint256 _value) external;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Burn(address indexed burner, uint256 value);
}
contract URUNCrowdsale is Ownable{
using SafeMath for uint256;
// The token being sold
TokenInterface public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// how many token units a buyer gets per wei
uint256 public ratePerWei = 800;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public TOKENS_SOLD;
uint256 public TOKENS_BOUGHT;
uint256 public minimumContributionPhase1;
uint256 public minimumContributionPhase2;
uint256 public minimumContributionPhase3;
uint256 public minimumContributionPhase4;
uint256 public minimumContributionPhase5;
uint256 public minimumContributionPhase6;
uint256 public maxTokensToSaleInClosedPreSale;
uint256 public bonusInPhase1;
uint256 public bonusInPhase2;
uint256 public bonusInPhase3;
uint256 public bonusInPhase4;
uint256 public bonusInPhase5;
uint256 public bonusInPhase6;
bool public isCrowdsalePaused = false;
uint256 public totalDurationInDays = 123 days;
struct userInformation {
address userAddress;
uint tokensToBeSent;
uint ethersToBeSent;
bool isKYCApproved;
bool recurringBuyer;
}
event usersAwaitingTokens(address[] users);
mapping(address=>userInformation) usersBuyingInformation;
address[] allUsers;
address[] u;
userInformation info;
/**
* 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);
constructor(uint256 _startTime, address _wallet, address _tokenAddress) public
{
require(_wallet != 0x0);
require(_startTime >=now);
startTime = _startTime;
endTime = startTime + totalDurationInDays;
require(endTime >= startTime);
owner = _wallet;
bonusInPhase1 = 30;
bonusInPhase2 = 20;
bonusInPhase3 = 15;
bonusInPhase4 = 10;
bonusInPhase5 = 75;
bonusInPhase6 = 5;
minimumContributionPhase1 = uint(3).mul(10 ** 17); //0.3 eth is the minimum contribution in presale phase 1
minimumContributionPhase2 = uint(5).mul(10 ** 16); //0.05 eth is the minimum contribution in presale phase 2
minimumContributionPhase3 = uint(5).mul(10 ** 16); //0.05 eth is the minimum contribution in presale phase 3
minimumContributionPhase4 = uint(5).mul(10 ** 16); //0.05 eth is the minimum contribution in presale phase 4
minimumContributionPhase5 = uint(5).mul(10 ** 16); //0.05 eth is the minimum contribution in presale phase 5
minimumContributionPhase6 = uint(5).mul(10 ** 16); //0.05 eth is the minimum contribution in presale phase 6
token = TokenInterface(_tokenAddress);
}
// fallback function can be used to buy tokens
function () public payable {
buyTokens(msg.sender);
}
function determineBonus(uint tokens, uint ethersSent) internal view returns (uint256 bonus)
{
uint256 timeElapsed = now - startTime;
uint256 timeElapsedInDays = timeElapsed.div(1 days);
//phase 1 (16 days)
if (timeElapsedInDays <16)
{
require(ethersSent>=minimumContributionPhase1);
bonus = tokens.mul(bonusInPhase1);
bonus = bonus.div(100);
}
//phase 2 (31 days)
else if (timeElapsedInDays >=16 && timeElapsedInDays <47)
{
require(ethersSent>=minimumContributionPhase2);
bonus = tokens.mul(bonusInPhase2);
bonus = bonus.div(100);
}
//phase 3 (15 days)
else if (timeElapsedInDays >=47 && timeElapsedInDays <62)
{
require(ethersSent>=minimumContributionPhase3);
bonus = tokens.mul(bonusInPhase3);
bonus = bonus.div(100);
}
//(16 days) -- break
else if (timeElapsedInDays >=62 && timeElapsedInDays <78)
{
revert();
}
//phase 5 (15 days)
else if (timeElapsedInDays >=78 && timeElapsedInDays <93)
{
require(ethersSent>=minimumContributionPhase4);
bonus = tokens.mul(bonusInPhase4);
bonus = bonus.div(100);
}
//phase 6 (15 days)
else if (timeElapsedInDays >=93 && timeElapsedInDays <108)
{
require(ethersSent>=minimumContributionPhase5);
bonus = tokens.mul(bonusInPhase5);
bonus = bonus.div(10); //to cater for the 7.5 figure
bonus = bonus.div(100);
}
//phase 7 (15 days)
else if (timeElapsedInDays >=108 && timeElapsedInDays <123)
{
require(ethersSent>=minimumContributionPhase6);
bonus = tokens.mul(bonusInPhase6);
bonus = bonus.div(100);
}
else
{
bonus = 0;
}
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(isCrowdsalePaused == false);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(ratePerWei);
uint256 bonus = determineBonus(tokens,weiAmount);
tokens = tokens.add(bonus);
//if the user is first time buyer, add his entries
if (usersBuyingInformation[beneficiary].recurringBuyer == false)
{
info = userInformation ({ userAddress: beneficiary, tokensToBeSent:tokens, ethersToBeSent:weiAmount, isKYCApproved:false,
recurringBuyer:true});
usersBuyingInformation[beneficiary] = info;
allUsers.push(beneficiary);
}
//if the user is has bought with the same address before too, update his entries
else
{
info = usersBuyingInformation[beneficiary];
info.tokensToBeSent = info.tokensToBeSent.add(tokens);
info.ethersToBeSent = info.ethersToBeSent.add(weiAmount);
usersBuyingInformation[beneficiary] = info;
}
TOKENS_BOUGHT = TOKENS_BOUGHT.add(tokens);
emit TokenPurchase(owner, beneficiary, weiAmount, tokens);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant 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 constant returns (bool) {
return now > endTime;
}
/**
* function to change the end time and start time of the ICO
* can only be called by owner wallet
**/
function changeStartAndEndDate (uint256 startTimeUnixTimestamp, uint256 endTimeUnixTimestamp) public onlyOwner
{
require (startTimeUnixTimestamp!=0 && endTimeUnixTimestamp!=0);
require(endTimeUnixTimestamp>startTimeUnixTimestamp);
require(endTimeUnixTimestamp.sub(startTimeUnixTimestamp) >=totalDurationInDays);
startTime = startTimeUnixTimestamp;
endTime = endTimeUnixTimestamp;
}
/**
* function to change the rate of tokens
* can only be called by owner wallet
**/
function setPriceRate(uint256 newPrice) public onlyOwner {
ratePerWei = newPrice;
}
/**
* function to pause the crowdsale
* can only be called from owner wallet
**/
function pauseCrowdsale() public onlyOwner {
isCrowdsalePaused = true;
}
/**
* function to resume the crowdsale if it is paused
* can only be called from owner wallet
**/
function resumeCrowdsale() public onlyOwner {
isCrowdsalePaused = false;
}
/**
* function through which owner can take back the tokens from the contract
**/
function takeTokensBack() public onlyOwner
{
uint remainingTokensInTheContract = token.balanceOf(address(this));
token.transfer(owner,remainingTokensInTheContract);
}
/**
* function through which owner can transfer the tokens to any address
* use this which to properly display the tokens that have been sold via ether or other payments
**/
function manualTokenTransfer(address receiver, uint value) public onlyOwner
{
token.transfer(receiver,value);
TOKENS_SOLD = TOKENS_SOLD.add(value);
TOKENS_BOUGHT = TOKENS_BOUGHT.add(value);
}
/**
* function to approve a single user which means the user has passed all KYC checks
* can only be called by the owner
**/
function approveSingleUser(address user) public onlyOwner {
usersBuyingInformation[user].isKYCApproved = true;
}
/**
* function to disapprove a single user which means the user has failed the KYC checks
* can only be called by the owner
**/
function disapproveSingleUser(address user) public onlyOwner {
usersBuyingInformation[user].isKYCApproved = false;
}
/**
* function to approve multiple users at once
* can only be called by the owner
**/
function approveMultipleUsers(address[] users) public onlyOwner {
for (uint i=0;i<users.length;i++)
{
usersBuyingInformation[users[i]].isKYCApproved = true;
}
}
/**
* function to distribute the tokens to approved users
* can only be called by the owner
**/
function distributeTokensToApprovedUsers() public onlyOwner {
for(uint i=0;i<allUsers.length;i++)
{
if (usersBuyingInformation[allUsers[i]].isKYCApproved == true && usersBuyingInformation[allUsers[i]].tokensToBeSent>0)
{
address to = allUsers[i];
uint tokens = usersBuyingInformation[to].tokensToBeSent;
token.transfer(to,tokens);
if (usersBuyingInformation[allUsers[i]].ethersToBeSent>0)
owner.transfer(usersBuyingInformation[allUsers[i]].ethersToBeSent);
TOKENS_SOLD = TOKENS_SOLD.add(usersBuyingInformation[allUsers[i]].tokensToBeSent);
weiRaised = weiRaised.add(usersBuyingInformation[allUsers[i]].ethersToBeSent);
usersBuyingInformation[allUsers[i]].tokensToBeSent = 0;
usersBuyingInformation[allUsers[i]].ethersToBeSent = 0;
}
}
}
/**
* function to distribute the tokens to all users whether approved or unapproved
* can only be called by the owner
**/
function distributeTokensToAllUsers() public onlyOwner {
for(uint i=0;i<allUsers.length;i++)
{
if (usersBuyingInformation[allUsers[i]].tokensToBeSent>0)
{
address to = allUsers[i];
uint tokens = usersBuyingInformation[to].tokensToBeSent;
token.transfer(to,tokens);
if (usersBuyingInformation[allUsers[i]].ethersToBeSent>0)
owner.transfer(usersBuyingInformation[allUsers[i]].ethersToBeSent);
TOKENS_SOLD = TOKENS_SOLD.add(usersBuyingInformation[allUsers[i]].tokensToBeSent);
weiRaised = weiRaised.add(usersBuyingInformation[allUsers[i]].ethersToBeSent);
usersBuyingInformation[allUsers[i]].tokensToBeSent = 0;
usersBuyingInformation[allUsers[i]].ethersToBeSent = 0;
}
}
}
/**
* function to refund a single user in case he hasnt passed the KYC checks
* can only be called by the owner
**/
function refundSingleUser(address user) public onlyOwner {
require(usersBuyingInformation[user].ethersToBeSent > 0 );
user.transfer(usersBuyingInformation[user].ethersToBeSent);
usersBuyingInformation[user].tokensToBeSent = 0;
usersBuyingInformation[user].ethersToBeSent = 0;
}
/**
* function to refund to multiple users in case they havent passed the KYC checks
* can only be called by the owner
**/
function refundMultipleUsers(address[] users) public onlyOwner {
for (uint i=0;i<users.length;i++)
{
require(usersBuyingInformation[users[i]].ethersToBeSent >0);
users[i].transfer(usersBuyingInformation[users[i]].ethersToBeSent);
usersBuyingInformation[users[i]].tokensToBeSent = 0;
usersBuyingInformation[users[i]].ethersToBeSent = 0;
}
}
/**
* function to transfer out all ethers present in the contract
* after calling this function all refunds would need to be done manually
* would use this function as a last resort
* can only be called by owner wallet
**/
function transferOutAllEthers() public onlyOwner {
owner.transfer(address(this).balance);
}
/**
* function to get the top 150 users who are awaiting the transfer of tokens
* can only be called by the owner
* this function would work in read mode
**/
function getUsersAwaitingForTokensTop150(bool fetch) public constant returns (address[150]) {
address[150] memory awaiting;
uint k = 0;
for (uint i=0;i<allUsers.length;i++)
{
if (usersBuyingInformation[allUsers[i]].isKYCApproved == true && usersBuyingInformation[allUsers[i]].tokensToBeSent>0)
{
awaiting[k] = allUsers[i];
k = k.add(1);
if (k==150)
return awaiting;
}
}
return awaiting;
}
/**
* function to get the users who are awaiting the transfer of tokens
* can only be called by the owner
* this function would work in write mode
**/
function getUsersAwaitingForTokens() public onlyOwner returns (address[]) {
delete u;
for (uint i=0;i<allUsers.length;i++)
{
if (usersBuyingInformation[allUsers[i]].isKYCApproved == true && usersBuyingInformation[allUsers[i]].tokensToBeSent>0)
{
u.push(allUsers[i]);
}
}
emit usersAwaitingTokens(u);
return u;
}
/**
* function to return the information of a single user
**/
function getUserInfo(address userAddress) public constant returns(uint _ethers, uint _tokens, bool _isApproved)
{
_ethers = usersBuyingInformation[userAddress].ethersToBeSent;
_tokens = usersBuyingInformation[userAddress].tokensToBeSent;
_isApproved = usersBuyingInformation[userAddress].isKYCApproved;
return(_ethers,_tokens,_isApproved);
}
/**
* function to clear all payables/receivables of a user
* can only be called by owner
**/
function closeUser(address userAddress) public onlyOwner
{
//instead of deleting the user from the system we are just clearing the payables/receivables
//if this user buys again, his entry would be updated
uint ethersByTheUser = usersBuyingInformation[userAddress].ethersToBeSent;
usersBuyingInformation[userAddress].isKYCApproved = false;
usersBuyingInformation[userAddress].ethersToBeSent = 0;
usersBuyingInformation[userAddress].tokensToBeSent = 0;
usersBuyingInformation[userAddress].recurringBuyer = true;
owner.transfer(ethersByTheUser);
}
/**
* function to get a list of top 150 users that are unapproved
* can only be called by owner
* this function would work in read mode
**/
function getUnapprovedUsersTop150(bool fetch) public constant returns (address[150])
{
address[150] memory unapprove;
uint k = 0;
for (uint i=0;i<allUsers.length;i++)
{
if (usersBuyingInformation[allUsers[i]].isKYCApproved == false)
{
unapprove[k] = allUsers[i];
k = k.add(1);
if (k==150)
return unapprove;
}
}
return unapprove;
}
/**
* function to get a list of all users that are unapproved
* can only be called by owner
* this function would work in write mode
**/
function getUnapprovedUsers() public onlyOwner returns (address[])
{
delete u;
for (uint i=0;i<allUsers.length;i++)
{
if (usersBuyingInformation[allUsers[i]].isKYCApproved == false)
{
u.push(allUsers[i]);
}
}
emit usersAwaitingTokens(u);
return u;
}
/**
* function to return all the users
**/
function getAllUsers(bool fetch) public constant returns (address[])
{
return allUsers;
}
/**
* function to change the address of a user
* this function would be used in situations where user made the transaction from one wallet
* but wants to receive tokens in another wallet
* so owner should be able to update the address
**/
function changeUserEthAddress(address oldEthAddress, address newEthAddress) public onlyOwner
{
usersBuyingInformation[newEthAddress] = usersBuyingInformation[oldEthAddress];
for (uint i=0;i<allUsers.length;i++)
{
if (allUsers[i] == oldEthAddress)
allUsers[i] = newEthAddress;
}
delete usersBuyingInformation[oldEthAddress];
}
/**
* Add a user that has paid with BTC or other payment methods
**/
function addUser(address userAddr, uint tokens) public onlyOwner
{
// if first time buyer, add his details in the mapping
if (usersBuyingInformation[userAddr].recurringBuyer == false)
{
info = userInformation ({ userAddress: userAddr, tokensToBeSent:tokens, ethersToBeSent:0, isKYCApproved:false,
recurringBuyer:true});
usersBuyingInformation[userAddr] = info;
allUsers.push(userAddr);
}
//if recurring buyer, update his mappings
else
{
info = usersBuyingInformation[userAddr];
info.tokensToBeSent = info.tokensToBeSent.add(tokens);
usersBuyingInformation[userAddr] = info;
}
TOKENS_BOUGHT = TOKENS_BOUGHT.add(tokens);
}
/**
* Set the tokens bought
**/
function setTokensBought(uint tokensBought) public onlyOwner
{
TOKENS_BOUGHT = tokensBought;
}
/**
* Returns the number of tokens who have been sold
**/
function getTokensBought() public constant returns(uint)
{
return TOKENS_BOUGHT;
}
} | function to change the end time and start time of the ICO can only be called by owner wallet/ | function changeStartAndEndDate (uint256 startTimeUnixTimestamp, uint256 endTimeUnixTimestamp) public onlyOwner
{
require (startTimeUnixTimestamp!=0 && endTimeUnixTimestamp!=0);
require(endTimeUnixTimestamp>startTimeUnixTimestamp);
require(endTimeUnixTimestamp.sub(startTimeUnixTimestamp) >=totalDurationInDays);
startTime = startTimeUnixTimestamp;
endTime = endTimeUnixTimestamp;
}
| 11,642,821 |
//Address: 0xcdf89e7f44fcc837630fb4a10387ca81eba6932a
//Contract name: MultiSigTokenWallet
//Balance: 0 Ether
//Verification Date: 8/27/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity 0.4.16;
/// @title Multi signature token wallet - Allows multiple parties to approve tokens transfer
/// @author popofe (Avalon Platform) - <[email protected]>
contract MultiSigTokenWallet {
/// @dev No fallback function to prevent ether deposit
address constant public TOKEN = 0xeD247980396B10169BB1d36f6e278eD16700a60f;
event Confirmation(address source, uint actionId);
event Revocation(address source, uint actionId);
event NewAction(uint actionId);
event Execution(uint actionId);
event ExecutionFailure(uint actionId);
event OwnerAddition(address owner);
event OwnerWithdraw(address owner);
event QuorumChange(uint quorum);
enum ActionChoices { AddOwner, ChangeQuorum, DeleteAction, TransferToken, WithdrawOwner}
mapping (uint => Action) public actions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public quorum;
uint public actionCount;
struct Action {
address addressField;
uint value;
ActionChoices actionType;
bool executed;
bool deleted;
}
modifier ownerDeclared(address owner) {
require (isOwner[owner]);
_;
}
modifier actionSubmitted(uint actionId) {
require ( actions[actionId].addressField != 0
|| actions[actionId].value != 0);
_;
}
modifier confirmed(uint actionId, address owner) {
require (confirmations[actionId][owner]);
_;
}
modifier notConfirmed(uint actionId, address owner) {
require (!confirmations[actionId][owner]);
_;
}
modifier notExecuted(uint actionId) {
require (!actions[actionId].executed);
_;
}
modifier notDeleted(uint actionId) {
require (!actions[actionId].deleted);
_;
}
modifier validQuorum(uint ownerCount, uint _quorum) {
require (_quorum <= ownerCount && _quorum > 0);
_;
}
modifier validAction(address addressField, uint value, ActionChoices actionType) {
require ((actionType == ActionChoices.AddOwner && addressField != 0 && value == 0)
|| (actionType == ActionChoices.ChangeQuorum && addressField == 0 && value > 0)
|| (actionType == ActionChoices.DeleteAction && addressField == 0 && value > 0)
|| (actionType == ActionChoices.TransferToken && addressField != 0 && value > 0)
|| (actionType == ActionChoices.WithdrawOwner && addressField != 0 && value == 0));
_;
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _quorum Number of required confirmations.
function MultiSigTokenWallet(address[] _owners, uint _quorum)
public
validQuorum(_owners.length, _quorum)
{
for (uint i=0; i<_owners.length; i++) {
require (!isOwner[_owners[i]] && _owners[i] != 0);
isOwner[_owners[i]] = true;
}
owners = _owners;
quorum = _quorum;
}
/// @dev Allows to add a new owner.
/// @param owner Address of new owner.
function addOwner(address owner)
private
{
require(!isOwner[owner]);
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to withdraw an owner.
/// @param owner Address of owner.
function withdrawOwner(address owner)
private
{
require (isOwner[owner]);
require (owners.length - 1 >= quorum);
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
OwnerWithdraw(owner);
}
/// @dev Allows to change the number of required confirmations.
/// @param _quorum Number of required confirmations.
function changeQuorum(uint _quorum)
private
{
require (_quorum > 0 && _quorum <= owners.length);
quorum = _quorum;
QuorumChange(_quorum);
}
/// @dev Allows to delete a previous action not executed
/// @param _actionId Number of required confirmations.
function deleteAction(uint _actionId)
private
notExecuted(_actionId)
{
actions[_actionId].deleted = true;
}
/// @dev Allows to delete a previous action not executed
/// @param _destination address that receive tokens.
/// @param _value Number of tokens.
function transferToken(address _destination, uint _value)
private
returns (bool)
{
ERC20Basic ERC20Contract = ERC20Basic(TOKEN);
return ERC20Contract.transfer(_destination, _value);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param addressField Action target address.
/// @param value Number of token / new quorum to reach.
/// @return Returns transaction ID.
function submitAction(address addressField, uint value, ActionChoices actionType)
public
ownerDeclared(msg.sender)
validAction(addressField, value, actionType)
returns (uint actionId)
{
actionId = addAction(addressField, value, actionType);
confirmAction(actionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param actionId Action ID.
function confirmAction(uint actionId)
public
ownerDeclared(msg.sender)
actionSubmitted(actionId)
notConfirmed(actionId, msg.sender)
{
confirmations[actionId][msg.sender] = true;
Confirmation(msg.sender, actionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param actionId Action ID.
function revokeConfirmation(uint actionId)
public
ownerDeclared(msg.sender)
confirmed(actionId, msg.sender)
notExecuted(actionId)
{
confirmations[actionId][msg.sender] = false;
Revocation(msg.sender, actionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param actionId Action ID.
function executeAction(uint actionId)
public
ownerDeclared(msg.sender)
actionSubmitted(actionId)
notExecuted(actionId)
notDeleted(actionId)
{
if (isConfirmed(actionId)) {
Action memory action = actions[actionId];
action.executed = true;
if (action.actionType == ActionChoices.AddOwner)
addOwner(action.addressField);
else if (action.actionType == ActionChoices.ChangeQuorum)
changeQuorum(action.value);
else if (action.actionType == ActionChoices.DeleteAction)
deleteAction(action.value);
else if (action.actionType == ActionChoices.TransferToken)
if (transferToken(action.addressField, action.value))
Execution(actionId);
else {
ExecutionFailure(actionId);
action.executed = false;
}
else if (action.actionType == ActionChoices.WithdrawOwner)
withdrawOwner(action.addressField);
else
revert();
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param actionId Action ID.
/// @return Confirmation status.
function isConfirmed(uint actionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[actionId][owners[i]])
count += 1;
if (count == quorum)
return true;
}
return false;
}
/// @dev Adds a new action to the transaction list, if action does not exist yet.
/// @param addressField address to send token or too add or withadraw as owner.
/// @param value number of tokens (useful only for token transfer).
/// @return Returns transaction ID.
function addAction(address addressField, uint value, ActionChoices actionType)
private
returns (uint)
{
actionCount += 1;
uint actionId = actionCount;
actions[actionId] = Action({
addressField: addressField,
value: value,
actionType: actionType,
executed: false,
deleted: false
});
NewAction(actionId);
return actionId;
}
/// @dev Returns number of confirmations of an action.
/// @param actionId Action ID.
/// @return Number of confirmations.
function getConfirmationCount(uint actionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[actionId][owners[i]])
count += 1;
}
/// @dev Returns total number of actions after filers are applied.
/// @param pending Include pending actions.
/// @param executed Include executed actions.
/// @return Total number of actions after filters are applied.
function getActionCount(bool pending, bool executed, bool exceptDeleted)
public
constant
returns (uint count)
{
for (uint i=0; i<actionCount; i++)
if ( ((pending && !actions[i].executed)
|| (executed && actions[i].executed))
&& (!exceptDeleted || !actions[i].deleted))
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param actionId Action ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint actionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[actionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of action IDs in defined range.
/// @param pending Include pending actions.
/// @param executed Include executed actions.
/// @param exceptDeleted Exclude deleted actions.
/// @return Returns array of transaction IDs.
function getActionIds(bool pending, bool executed, bool exceptDeleted)
public
constant
returns (uint[] memory)
{
uint[] memory actionIds;
uint count = 0;
uint i;
for (i=0; i<actionCount; i++)
if (((pending && !actions[i].executed)
|| (executed && actions[i].executed))
&& (!exceptDeleted || !actions[i].deleted))
{
actionIds[count] = i;
count += 1;
}
}
}
/**
* @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) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
| Allows an owner to confirm a transaction. actionId Action ID. | function confirmAction(uint actionId)
public
ownerDeclared(msg.sender)
actionSubmitted(actionId)
notConfirmed(actionId, msg.sender)
{
confirmations[actionId][msg.sender] = true;
Confirmation(msg.sender, actionId);
}
| 1,831,521 |
/**
*Submitted for verification at Etherscan.io on 2021-08-08
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
////////////////////////////////
///////////// ERC //////////////
////////////////////////////////
/*
* @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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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 Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
////////////////////////////////
////////// Dividend ////////////
////////////////////////////////
/*
@title Dividend-Paying Token Interface
@author Roger Wu (https://github.com/roger-wu)
@dev An interface for a dividend-paying token contract.
*/
interface IDividendPayingToken {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/*
@title Dividend-Paying Token Optional Interface
@author Roger Wu (https://github.com/roger-wu)
@dev OPTIONAL functions for a dividend-paying token contract.
*/
interface IDividendPayingTokenOptional {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
/*
@title Dividend-Paying Token
@author Roger Wu (https://github.com/roger-wu)
@dev A mintable ERC20 token that allows anyone to pay and distribute ether
to token holders as dividends and allows token holders to withdraw their dividends.
Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
*/
contract DividendPayingToken is ERC20, IDividendPayingToken, IDividendPayingTokenOptional {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
uint256 internal lastAmount;
address public dividendToken = 0x3301Ee63Fb29F863f2333Bd4466acb46CD8323E6;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
uint256 public gasForTransfer;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
gasForTransfer = 3000;
}
receive() external payable {
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
function distributeDividends(uint256 amount) public {
require(totalSupply() > 0);
if (amount > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(amount).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, amount);
totalDividendsDistributed = totalDividendsDistributed.add(amount);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(payable(msg.sender));
}
function setDividendTokenAddress(address newToken) public {
dividendToken = newToken;
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
bool success = IERC20(dividendToken).transfer(user, _withdrawableDividend);
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
////////////////////////////////
///////// Interfaces ///////////
////////////////////////////////
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
////////////////////////////////
////////// Libraries ///////////
////////////////////////////////
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
/**
* @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;
}
}
/**
* @title SafeMathInt
* @dev Math operations with safety checks that revert on error
* @dev SafeMath adapted for int256
* Based on code of https://github.com/RequestNetwork/requestNetwork/blob/master/packages/requestNetworkSmartContracts/contracts/base/math/SafeMathInt.sol
*/
library SafeMathInt {
function mul(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when multiplying INT256_MIN with -1
// https://github.com/RequestNetwork/requestNetwork/issues/43
require(!(a == - 2**255 && b == -1) && !(b == - 2**255 && a == -1));
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing INT256_MIN by -1
// https://github.com/RequestNetwork/requestNetwork/issues/43
require(!(a == - 2**255 && b == -1) && (b > 0));
return a / b;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
////////////////////////////////
/////////// Tokens /////////////
////////////////////////////////
contract KitsuneInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
bool private liquidating;
KitsuneInuDividendTracker public dividendTracker;
address public liquidityWallet;
uint256 public constant MAX_SELL_TRANSACTION_AMOUNT = 2500000000 * (10**18);
uint256 public constant ETH_REWARDS_FEE = 11;
uint256 public constant LIQUIDITY_FEE = 3;
uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE;
bool _swapEnabled = false;
bool openForPresale = false;
mapping (address => bool) private _isBlackListedBot;
address[] private _blackListedBots;
address private _dividendToken = 0x3301Ee63Fb29F863f2333Bd4466acb46CD8323E6;
address public marketingAddress = 0x61B3e99AfA0925EaF18bDeb8810b01b4ed1C895B;
bool _maxBuyEnabled = true;
// use by default 150,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 150000;
// liquidate tokens for ETH when the contract reaches 25000k tokens by default
uint256 public liquidateTokensAtAmount = 25000000 * (10**18);
// whether the token can already be traded
bool public tradingEnabled;
function activate() public onlyOwner {
require(!tradingEnabled, "KitsuneInu: Trading is already enabled");
_swapEnabled = true;
tradingEnabled = true;
}
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// addresses that can make transfers before presale is over
mapping (address => bool) public canTransferBeforeTradingIsEnabled;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Liquified(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapAndSendToDev(
uint256 tokensSwapped,
uint256 ethReceived
);
event SentDividends(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor() ERC20("Kitsune Inu", "KITSU") {
dividendTracker = new KitsuneInuDividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
// exclude from paying fees or having max transaction amount
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
// enable owner wallet to send tokens before presales are over.
canTransferBeforeTradingIsEnabled[owner()] = true;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 250000000000 * (10**18));
}
receive() external payable {
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "KitsuneInu: The Uniswap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "KitsuneInu: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function excludeFromFees(address account) public onlyOwner {
require(!_isExcludedFromFees[account], "KitsuneInu: Account is already excluded from fees");
_isExcludedFromFees[account] = true;
}
function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner {
dividendTracker.updateGasForTransfer(gasForTransfer);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
require(newValue != gasForProcessing, "KitsuneInu: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getGasForTransfer() external view returns(uint256) {
return dividendTracker.gasForTransfer();
}
function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){
require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee");
_swapEnabled = _devFeeEnabled;
return(_swapEnabled);
}
function setOpenForPresale(bool open )external onlyOwner {
openForPresale = open;
}
function setMaxBuyEnabled(bool enabled ) external onlyOwner {
_maxBuyEnabled = enabled;
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account) public view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function addBotToBlackList(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.');
require(!_isBlackListedBot[account], "Account is already blacklisted");
_isBlackListedBot[account] = true;
_blackListedBots.push(account);
}
function removeBotFromBlackList(address account) external onlyOwner() {
require(_isBlackListedBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _blackListedBots.length; i++) {
if (_blackListedBots[i] == account) {
_blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1];
_isBlackListedBot[account] = false;
_blackListedBots.pop();
break;
}
}
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isBlackListedBot[to], "You have no power here!");
require(!_isBlackListedBot[msg.sender], "You have no power here!");
require(!_isBlackListedBot[from], "You have no power here!");
//to prevent bots both buys and sells will have a max on launch after only sells will
if(from != owner() && to != owner() && _maxBuyEnabled)
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount.");
bool tradingIsEnabled = tradingEnabled;
// only whitelisted addresses can make transfers before the public presale is over.
if (!tradingIsEnabled) {
//turn transfer on to allow for whitelist form/mutlisend presale
if(!openForPresale){
require(canTransferBeforeTradingIsEnabled[from], "KitsuneInu: This account cannot send tokens until trading is enabled");
}
}
if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) {
//require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop");
// require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop");
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (!liquidating &&
tradingIsEnabled &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] //no max for those excluded from fees
) {
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= liquidateTokensAtAmount;
if (tradingIsEnabled &&
canSwap &&
_swapEnabled &&
!liquidating &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
liquidating = true;
uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES);
swapAndSendToDev(swapTokens);
uint256 sellTokens = balanceOf(address(this));
swapAndSendDividends(sellTokens);
liquidating = false;
}
bool takeFee = tradingIsEnabled && !liquidating;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = amount.mul(TOTAL_FEES).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {
}
if (!liquidating) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
} catch {
}
}
}
function swapAndSendToDev(uint256 tokens) private {
uint256 tokenBalance = tokens;
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
address payable _devAndMarketingAddress = payable(marketingAddress);
_devAndMarketingAddress.transfer(newBalance);
emit SwapAndSendToDev(tokens, newBalance);
}
function swapTokensForDividendToken(uint256 tokenAmount, address recipient) private {
// generate the uniswap pair path of weth -> busd
address[] memory path = new address[](3);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
path[2] = _dividendToken;
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of dividend token
path,
recipient,
block.timestamp
);
}
function swapAndSendDividends(uint256 tokens) private {
swapTokensForDividendToken(tokens, address(this));
uint256 dividends = IERC20(_dividendToken).balanceOf(address(this));
bool success = IERC20(_dividendToken).transfer(address(dividendTracker), dividends);
if (success) {
dividendTracker.distributeDividends(dividends);
emit SentDividends(tokens, dividends);
}
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
}
contract KitsuneInuDividendTracker is DividendPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public immutable minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() DividendPayingToken("KitsuneInu_Dividend_Tracker", "KitsuneInu_Dividend_Tracker") {
claimWait = 3600;
minimumTokenBalanceForDividends = 2500000 * (10**18); //must hold 2500000+ tokens
}
function _transfer(address, address, uint256) pure internal override {
require(false, "KitsuneInu_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() pure public override {
require(false, "KitsuneInu_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main KitsuneInu contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromDividends(account);
}
function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner {
require(newGasForTransfer != gasForTransfer, "KitsuneInu_Dividend_Tracker: Cannot update gasForTransfer to same value");
emit GasForTransferUpdated(newGasForTransfer, gasForTransfer);
gasForTransfer = newGasForTransfer;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 1800 && newClaimWait <= 86400, "KitsuneInu_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "KitsuneInu_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
}
else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if(numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while(gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if(_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if(canAutoClaim(lastClaimTimes[account])) {
if(processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if(gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
} | capture the contract's current ETH balance. this is so that we can capture exactly the amount of ETH that the swap creates, and not make the liquidity event include any ETH that has been manually sent to the contract swap tokens for ETH how much ETH did we just swap into? | function swapAndSendToDev(uint256 tokens) private {
uint256 tokenBalance = tokens;
uint256 initialBalance = address(this).balance;
uint256 newBalance = address(this).balance.sub(initialBalance);
address payable _devAndMarketingAddress = payable(marketingAddress);
_devAndMarketingAddress.transfer(newBalance);
emit SwapAndSendToDev(tokens, newBalance);
}
| 2,449,110 |
// SPDX-License-Identifier: MIT
//
// Copyright (c) 2021 Kentaro Hara
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
pragma solidity ^0.8.11;
import "./JohnLawCoin_v4.sol";
//------------------------------------------------------------------------------
// [Oracle contract]
//
// The oracle is a decentralized mechanism to determine one "truth" level
// from 0, 1, 2, ..., LEVEL_MAX - 1. The oracle uses the commit-reveal-reclaim
// voting scheme.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract Oracle_v5 is OwnableUpgradeable {
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public LEVEL_MAX;
uint public RECLAIM_THRESHOLD;
uint public PROPORTIONAL_REWARD_RATE;
// The valid phase transition is: COMMIT => REVEAL => RECLAIM.
enum Phase {
COMMIT, REVEAL, RECLAIM
}
// Commit is a struct to manage one commit entry in the commit-reveal-reclaim
// scheme.
struct Commit {
// The committed hash (filled in the commit phase).
bytes32 hash;
// The amount of deposited coins (filled in the commit phase).
uint deposit;
// The oracle level (filled in the reveal phase).
uint oracle_level;
// The phase of this commit entry.
Phase phase;
// The epoch ID when this commit entry is created.
uint epoch_id;
}
// Vote is a struct to aggregate voting statistics for each oracle level.
// The data is aggregated during the reveal phase and finalized at the end
// of the reveal phase.
struct Vote {
// The total amount of the coins deposited by the voters who voted for this
// oracle level.
uint deposit;
// The number of the voters.
uint count;
// Set to true when the voters for this oracle level are eligible to
// reclaim the coins they deposited.
bool should_reclaim;
// Set to true when the voters for this oracle level are eligible to
// receive a reward.
bool should_reward;
}
// Epoch is a struct to keep track of the states in the commit-reveal-reclaim
// scheme. The oracle creates three Epoch objects and uses them in a
// round-robin manner. For example, when the first Epoch object is in use for
// the commit phase, the second Epoch object is in use for the reveal phase,
// and the third Epoch object is in use for the reclaim phase.
struct Epoch {
// The commit entries.
mapping (address => Commit) commits;
// The voting statistics for all the oracle levels. This uses a mapping
// (instead of an array) to make the Vote struct upgradeable.
mapping (uint => Vote) votes;
// An account to store coins deposited by the voters.
address deposit_account;
// An account to store the reward.
address reward_account;
// The total amount of the reward.
uint reward_total;
// The current phase of this Epoch.
Phase phase;
}
// Attributes. See the comment in initialize().
// This uses a mapping (instead of an array) to make the Epoch struct
// upgradeable.
mapping (uint => Epoch) public epochs_;
uint public epoch_id_;
// Events.
event CommitEvent(address indexed sender, uint indexed epoch_id,
bytes32 hash, uint deposited);
event RevealEvent(address indexed sender, uint indexed epoch_id,
uint oracle_level, uint salt);
event ReclaimEvent(address indexed sender, uint indexed epoch_id,
uint reclaimed, uint rewarded);
event AdvancePhaseEvent(uint indexed epoch_id, uint tax, uint burned);
// Initializer.
function initialize(uint epoch_id)
public initializer {
__Ownable_init();
// Constants.
// The number of the oracle levels.
LEVEL_MAX = 9;
// If the "truth" level is 4 and RECLAIM_THRESHOLD is 1, the voters who
// voted for 3, 4 and 5 can reclaim their deposited coins. Other voters
// lose their deposited coins.
RECLAIM_THRESHOLD = 1;
// The lost coins and the collected tax are distributed to the voters who
// voted for the "truth" level as a reward. The PROPORTIONAL_REWARD_RATE
// of the reward is distributed to the voters in proportion to the coins
// they deposited. The rest of the reward is distributed to the voters
// evenly.
PROPORTIONAL_REWARD_RATE = 90; // 90%
// Attributes.
// The oracle creates three Epoch objects and uses them in a round-robin
// manner (commit => reveal => reclaim).
for (uint epoch_index = 0; epoch_index < 3; epoch_index++) {
for (uint level = 0; level < LEVEL_MAX; level++) {
epochs_[epoch_index].votes[level] = Vote(0, 0, false, false);
}
epochs_[epoch_index].deposit_account =
address(uint160(uint(keccak256(abi.encode(
"deposit_v5", epoch_index, block.number)))));
epochs_[epoch_index].reward_account =
address(uint160(uint(keccak256(abi.encode(
"reward_v5", epoch_index, block.number)))));
epochs_[epoch_index].reward_total = 0;
}
epochs_[epoch_id % 3].phase = Phase.COMMIT;
epochs_[(epoch_id + 1) % 3].phase = Phase.RECLAIM;
epochs_[(epoch_id + 2) % 3].phase = Phase.REVEAL;
// |epoch_id_| is a monotonically increasing ID (3, 4, 5, ...).
// The Epoch object at |epoch_id_ % 3| is in the commit phase.
// The Epoch object at |(epoch_id_ - 1) % 3| is in the reveal phase.
// The Epoch object at |(epoch_id_ - 2) % 3| is in the reclaim phase.
// The epoch ID starts with 3 because 0 in the commit entry is not
// distinguishable from an uninitialized commit entry in Solidity.
epoch_id_ = epoch_id;
}
// Do commit.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |hash|: The committed hash.
// |deposit|: The amount of the deposited coins.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// True if the commit succeeded. False otherwise.
function commit(address sender, bytes32 hash, uint deposit, JohnLawCoin_v2 coin)
public onlyOwner returns (bool) {
Epoch storage epoch = epochs_[epoch_id_ % 3];
require(epoch.phase == Phase.COMMIT, "co1");
if (coin.balanceOf(sender) < deposit) {
return false;
}
// One voter can commit only once per phase.
if (epoch.commits[sender].epoch_id == epoch_id_) {
return false;
}
// Create a commit entry.
epoch.commits[sender] = Commit(
hash, deposit, LEVEL_MAX, Phase.COMMIT, epoch_id_);
require(epoch.commits[sender].phase == Phase.COMMIT, "co2");
// Move the deposited coins to the deposit account.
coin.move(sender, epoch.deposit_account, deposit);
emit CommitEvent(sender, epoch_id_, hash, deposit);
return true;
}
// Do reveal.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |oracle_level|: The oracle level revealed by the voter.
// |salt|: The salt revealed by the voter.
//
// Returns
// ----------------
// True if the reveal succeeded. False otherwise.
function reveal(address sender, uint oracle_level, uint salt)
public onlyOwner returns (bool) {
Epoch storage epoch = epochs_[(epoch_id_ - 1) % 3];
require(epoch.phase == Phase.REVEAL, "rv1");
if (LEVEL_MAX <= oracle_level) {
return false;
}
if (epoch.commits[sender].epoch_id != epoch_id_ - 1) {
// The corresponding commit was not found.
return false;
}
// One voter can reveal only once per phase.
if (epoch.commits[sender].phase != Phase.COMMIT) {
return false;
}
epoch.commits[sender].phase = Phase.REVEAL;
// Check if the committed hash matches the revealed level and the salt.
bytes32 reveal_hash = encrypt(sender, oracle_level, salt);
bytes32 hash = epoch.commits[sender].hash;
if (hash != reveal_hash) {
return false;
}
// Update the commit entry with the revealed level.
epoch.commits[sender].oracle_level = oracle_level;
// Count up the vote.
epoch.votes[oracle_level].deposit += epoch.commits[sender].deposit;
epoch.votes[oracle_level].count += 1;
emit RevealEvent(sender, epoch_id_, oracle_level, salt);
return true;
}
// Do reclaim.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// A tuple of two values:
// - uint: The amount of the reclaimed coins. This becomes a positive value
// when the voter is eligible to reclaim their deposited coins.
// - uint: The amount of the reward. This becomes a positive value when the
// voter voted for the "truth" oracle level.
function reclaim(address sender, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
Epoch storage epoch = epochs_[(epoch_id_ - 2) % 3];
require(epoch.phase == Phase.RECLAIM, "rc1");
if (epoch.commits[sender].epoch_id != epoch_id_ - 2){
// The corresponding commit was not found.
return (0, 0);
}
// One voter can reclaim only once per phase.
if (epoch.commits[sender].phase != Phase.REVEAL) {
return (0, 0);
}
epoch.commits[sender].phase = Phase.RECLAIM;
uint deposit = epoch.commits[sender].deposit;
uint oracle_level = epoch.commits[sender].oracle_level;
if (oracle_level == LEVEL_MAX) {
return (0, 0);
}
require(0 <= oracle_level && oracle_level < LEVEL_MAX, "rc2");
if (!epoch.votes[oracle_level].should_reclaim) {
return (0, 0);
}
require(epoch.votes[oracle_level].count > 0, "rc3");
// Reclaim the deposited coins.
coin.move(epoch.deposit_account, sender, deposit);
uint reward = 0;
if (epoch.votes[oracle_level].should_reward) {
// The voter who voted for the "truth" level can receive the reward.
//
// The PROPORTIONAL_REWARD_RATE of the reward is distributed to the
// voters in proportion to the coins they deposited. This incentivizes
// voters who have more coins (and thus have more power on determining
// the "truth" level) to join the oracle.
//
// The rest of the reward is distributed to the voters evenly. This
// incentivizes more voters (including new voters) to join the oracle.
if (epoch.votes[oracle_level].deposit > 0) {
reward += (uint(PROPORTIONAL_REWARD_RATE) * epoch.reward_total *
deposit) / (uint(100) * epoch.votes[oracle_level].deposit);
}
reward += ((uint(100) - PROPORTIONAL_REWARD_RATE) * epoch.reward_total) /
(uint(100) * epoch.votes[oracle_level].count);
coin.move(epoch.reward_account, sender, reward);
}
emit ReclaimEvent(sender, epoch_id_, deposit, reward);
return (deposit, reward);
}
// Advance to the next phase. COMMIT => REVEAL, REVEAL => RECLAIM,
// RECLAIM => COMMIT.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// None.
function advance(JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
// Advance the phase.
epoch_id_ += 1;
// Step 1: Move the commit phase to the reveal phase.
Epoch storage epoch = epochs_[(epoch_id_ - 1) % 3];
require(epoch.phase == Phase.COMMIT, "ad1");
epoch.phase = Phase.REVEAL;
// Step 2: Move the reveal phase to the reclaim phase.
epoch = epochs_[(epoch_id_ - 2) % 3];
require(epoch.phase == Phase.REVEAL, "ad2");
epoch.phase = Phase.RECLAIM;
// The "truth" level is set to the mode of the weighted majority votes.
uint mode_level = getModeLevel();
if (0 <= mode_level && mode_level < LEVEL_MAX) {
uint deposit_revealed = 0;
uint deposit_to_reclaim = 0;
for (uint level = 0; level < LEVEL_MAX; level++) {
require(epoch.votes[level].should_reclaim == false, "ad3");
require(epoch.votes[level].should_reward == false, "ad4");
deposit_revealed += epoch.votes[level].deposit;
if ((mode_level < RECLAIM_THRESHOLD ||
mode_level - RECLAIM_THRESHOLD <= level) &&
level <= mode_level + RECLAIM_THRESHOLD) {
// Voters who voted for the oracle levels in [mode_level -
// reclaim_threshold, mode_level + reclaim_threshold] are eligible
// to reclaim their deposited coins. Other voters lose their deposited
// coins.
epoch.votes[level].should_reclaim = true;
deposit_to_reclaim += epoch.votes[level].deposit;
}
}
// Voters who voted for the "truth" level are eligible to receive the
// reward.
epoch.votes[mode_level].should_reward = true;
// Note: |deposit_revealed| is equal to |balanceOf(epoch.deposit_account)|
// only when all the voters who voted in the commit phase revealed
// their votes correctly in the reveal phase.
require(deposit_revealed <= coin.balanceOf(epoch.deposit_account), "ad5");
require(
deposit_to_reclaim <= coin.balanceOf(epoch.deposit_account), "ad6");
// The lost coins are moved to the reward account.
coin.move(epoch.deposit_account, epoch.reward_account,
coin.balanceOf(epoch.deposit_account) - deposit_to_reclaim);
}
// Move the collected tax to the reward account.
address tax_account = coin.tax_account_();
uint tax = coin.balanceOf(tax_account);
coin.move(tax_account, epoch.reward_account, tax);
// Set the total amount of the reward.
epoch.reward_total = coin.balanceOf(epoch.reward_account);
// Step 3: Move the reclaim phase to the commit phase.
uint epoch_index = epoch_id_ % 3;
epoch = epochs_[epoch_index];
require(epoch.phase == Phase.RECLAIM, "ad7");
uint burned = coin.balanceOf(epoch.deposit_account) +
coin.balanceOf(epoch.reward_account);
// Burn the remaining deposited coins.
coin.burn(epoch.deposit_account, coin.balanceOf(epoch.deposit_account));
// Burn the remaining reward.
coin.burn(epoch.reward_account, coin.balanceOf(epoch.reward_account));
// Initialize the Epoch object for the next commit phase.
//
// |epoch.commits_| cannot be cleared due to the restriction of Solidity.
// |epoch_id_| ensures the stale commit entries are not misused.
for (uint level = 0; level < LEVEL_MAX; level++) {
epoch.votes[level] = Vote(0, 0, false, false);
}
// Regenerate the account addresses just in case.
require(coin.balanceOf(epoch.deposit_account) == 0, "ad8");
require(coin.balanceOf(epoch.reward_account) == 0, "ad9");
epoch.deposit_account =
address(uint160(uint(keccak256(abi.encode(
"deposit_v5", epoch_index, block.number)))));
epoch.reward_account =
address(uint160(uint(keccak256(abi.encode(
"reward_v5", epoch_index, block.number)))));
epoch.reward_total = 0;
epoch.phase = Phase.COMMIT;
emit AdvancePhaseEvent(epoch_id_, tax, burned);
return burned;
}
// Return the oracle level that got the largest amount of deposited coins.
// In other words, return the mode of the votes weighted by the deposited
// coins.
//
// Parameters
// ----------------
// None.
//
// Returns
// ----------------
// If there are multiple modes, return the mode that has the largest votes.
// If there are multiple modes that have the largest votes, return the
// smallest mode. If there are no votes, return LEVEL_MAX.
function getModeLevel()
public onlyOwner view returns (uint) {
Epoch storage epoch = epochs_[(epoch_id_ - 2) % 3];
require(epoch.phase == Phase.RECLAIM, "gm1");
uint mode_level = LEVEL_MAX;
uint max_deposit = 0;
uint max_count = 0;
for (uint level = 0; level < LEVEL_MAX; level++) {
if (epoch.votes[level].count > 0 &&
(mode_level == LEVEL_MAX ||
max_deposit < epoch.votes[level].deposit ||
(max_deposit == epoch.votes[level].deposit &&
max_count < epoch.votes[level].count))){
max_deposit = epoch.votes[level].deposit;
max_count = epoch.votes[level].count;
mode_level = level;
}
}
return mode_level;
}
// Return the ownership of the JohnLawCoin contract to the ACB.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract.
//
// Returns
// ----------------
// None.
function revokeOwnership(JohnLawCoin_v2 coin)
public onlyOwner {
coin.transferOwnership(msg.sender);
}
// Public getter: Return the Vote object at |epoch_index| and |level|.
function getVote(uint epoch_index, uint level)
public view returns (uint, uint, bool, bool) {
require(0 <= epoch_index && epoch_index <= 2, "gv1");
require(0 <= level && level < LEVEL_MAX, "gv2");
Vote memory vote = epochs_[epoch_index].votes[level];
return (vote.deposit, vote.count, vote.should_reclaim, vote.should_reward);
}
// Public getter: Return the Commit object at |epoch_index| and |account|.
function getCommit(uint epoch_index, address account)
public view returns (bytes32, uint, uint, Phase, uint) {
require(0 <= epoch_index && epoch_index <= 2, "gc1");
Commit memory entry = epochs_[epoch_index].commits[account];
return (entry.hash, entry.deposit, entry.oracle_level,
entry.phase, entry.epoch_id);
}
// Public getter: Return the Epoch object at |epoch_index|.
function getEpoch(uint epoch_index)
public view returns (address, address, uint, Phase) {
require(0 <= epoch_index && epoch_index <= 2, "ge1");
return (epochs_[epoch_index].deposit_account,
epochs_[epoch_index].reward_account,
epochs_[epoch_index].reward_total,
epochs_[epoch_index].phase);
}
// Calculate a hash to be committed. Voters are expected to use this function
// to create a hash used in the commit phase.
//
// Parameters
// ----------------
// |sender|: The voter's account.
// |level|: The oracle level to vote.
// |salt|: The voter's salt.
//
// Returns
// ----------------
// The calculated hash value.
function encrypt(address sender, uint level, uint salt)
public pure returns (bytes32) {
return keccak256(abi.encode(sender, level, salt));
}
}
//------------------------------------------------------------------------------
// [BondOperation contract]
//
// The BondOperation contract increases / decreases the total coin supply by
// redeeming / issuing bonds. The bond budget is updated by the ACB every epoch.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract BondOperation_v5 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public BOND_PRICE;
uint public BOND_REDEMPTION_PRICE;
uint public BOND_REDEMPTION_PERIOD;
uint public BOND_REDEEMABLE_PERIOD;
// Attributes. See the comment in initialize().
JohnLawBond_v2 public bond_;
int public bond_budget_;
// Events.
event IncreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint issued_bonds, uint redemption_epoch);
event DecreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint redeemed_bonds, uint expired_bonds);
event UpdateBondBudgetEvent(uint indexed epoch_id, int delta,
int bond_budget, uint mint);
// Initializer.
//
// Parameters
// ----------------
// |bond|: The JohnLawBond contract. The ownership needs to be transferred
// to this contract.
function initialize(JohnLawBond_v2 bond, int bond_budget)
public initializer {
__Ownable_init();
// Constants.
// The bond structure.
//
// |<---BOND_REDEMPTION_PERIOD--->|<---BOND_REDEEMABLE_PERIOD--->|
// ^ ^ ^
// Issued Becomes redeemable Expired
//
// During BOND_REDEMPTION_PERIOD, the bonds are redeemable as long as the
// bond budget is negative. During BOND_REDEEMABLE_PERIOD, the bonds are
// redeemable regardless of the bond budget. After BOND_REDEEMABLE_PERIOD,
// the bonds are expired.
BOND_PRICE = 996; // One bond is sold for 996 coins.
BOND_REDEMPTION_PRICE = 1000; // One bond is redeemed for 1000 coins.
BOND_REDEMPTION_PERIOD = 12; // 12 epochs.
BOND_REDEEMABLE_PERIOD = 2; // 2 epochs.
// The JohnLawBond contract.
bond_ = bond;
// If |bond_budget_| is positive, it indicates the number of bonds the ACB
// can issue to decrease the total coin supply. If |bond_budget_| is
// negative, it indicates the number of bonds the ACB can redeem to
// increase the total coin supply.
bond_budget_ = bond_budget;
}
// Deprecate the contract.
function deprecate()
public onlyOwner {
bond_.transferOwnership(msg.sender);
}
// Increase the total bond supply by issuing bonds.
//
// Parameters
// ----------------
// |sender|: The sender account.
// |count|: The number of bonds to be issued.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// The redemption epoch of the issued bonds if it succeeds. 0 otherwise.
function increaseBondSupply(address sender, uint count,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
require(count > 0, "BondOperation: You must purchase at least one bond.");
require(bond_budget_ >= count.toInt256(),
"BondOperation: The bond budget is not enough.");
uint amount = BOND_PRICE * count;
require(coin.balanceOf(sender) >= amount,
"BondOperation: Your coin balance is not enough.");
// Set the redemption epoch of the bonds.
uint redemption_epoch = epoch_id + BOND_REDEMPTION_PERIOD;
// Issue new bonds.
bond_.mint(sender, redemption_epoch, count);
bond_budget_ -= count.toInt256();
require(bond_budget_ >= 0, "pb1");
require(bond_.balanceOf(sender, redemption_epoch) > 0, "pb2");
// Burn the corresponding coins.
coin.burn(sender, amount);
emit IncreaseBondSupplyEvent(sender, epoch_id, count, redemption_epoch);
return redemption_epoch;
}
// Decrease the total bond supply by redeeming bonds.
//
// Parameters
// ----------------
// |sender|: The sender account.
// |redemption_epochs|: An array of bonds to be redeemed. The bonds are
// identified by their redemption epochs.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// A tuple of two values:
// - The number of redeemed bonds.
// - The number of expired bonds.
function decreaseBondSupply(address sender, uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
uint redeemed_bonds = 0;
uint expired_bonds = 0;
for (uint i = 0; i < redemption_epochs.length; i++) {
uint redemption_epoch = redemption_epochs[i];
uint count = bond_.balanceOf(sender, redemption_epoch);
if (epoch_id < redemption_epoch) {
// If the bonds have not yet hit their redemption epoch, the
// BondOperation accepts the redemption as long as |bond_budget_| is
// negative.
if (bond_budget_ >= 0) {
continue;
}
if (count > (-bond_budget_).toUint256()) {
count = (-bond_budget_).toUint256();
}
bond_budget_ += count.toInt256();
}
if (epoch_id < redemption_epoch + BOND_REDEEMABLE_PERIOD) {
// If the bonds are not expired, mint the corresponding coins to the
// sender account.
uint amount = count * BOND_REDEMPTION_PRICE;
coin.mint(sender, amount);
redeemed_bonds += count;
} else {
expired_bonds += count;
}
// Burn the redeemed / expired bonds.
bond_.burn(sender, redemption_epoch, count);
}
emit DecreaseBondSupplyEvent(sender, epoch_id,
redeemed_bonds, expired_bonds);
return (redeemed_bonds, expired_bonds);
}
// Update the bond budget to increase or decrease the total coin supply.
//
// Parameters
// ----------------
// |delta|: The target increase or decrease of the total coin supply.
// |epoch_id|: The current epoch ID.
//
// Returns
// ----------------
// The amount of coins that cannot be increased by adjusting the bond budget
// and thus need to be newly minted.
function updateBondBudget(int delta, uint epoch_id)
public onlyOwner returns (uint) {
uint mint = 0;
uint bond_supply = validBondSupply(epoch_id);
if (delta == 0) {
// No change in the total coin supply.
bond_budget_ = 0;
} else if (delta > 0) {
// Increase the total coin supply.
uint count = delta.toUint256() / BOND_REDEMPTION_PRICE;
if (count <= bond_supply) {
// If there are sufficient bonds to redeem, increase the total coin
// supply by redeeming the bonds.
bond_budget_ = -count.toInt256();
} else {
// Otherwise, redeem all the issued bonds.
bond_budget_ = -bond_supply.toInt256();
// The remaining coins need to be newly minted.
mint = (count - bond_supply) * BOND_REDEMPTION_PRICE;
}
require(bond_budget_ <= 0, "cs1");
} else {
// Issue new bonds to decrease the total coin supply.
bond_budget_ = -delta / BOND_PRICE.toInt256();
require(bond_budget_ >= 0, "cs2");
}
require(bond_supply.toInt256() + bond_budget_ >= 0, "cs3");
emit UpdateBondBudgetEvent(epoch_id, delta, bond_budget_, mint);
return mint;
}
// Public getter: Return the valid bond supply; i.e., the total supply of
// not-yet-expired bonds.
function validBondSupply(uint epoch_id)
public view returns (uint) {
uint count = 0;
for (uint redemption_epoch =
(epoch_id > BOND_REDEEMABLE_PERIOD ?
epoch_id - BOND_REDEEMABLE_PERIOD + 1 : 0);
redemption_epoch <= epoch_id + BOND_REDEMPTION_PERIOD;
redemption_epoch++) {
count += bond_.bondSupplyAt(redemption_epoch);
}
return count;
}
// Return the ownership of the JohnLawCoin contract to the ACB.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract.
//
// Returns
// ----------------
// None.
function revokeOwnership(JohnLawCoin_v2 coin)
public onlyOwner {
coin.transferOwnership(msg.sender);
}
}
//------------------------------------------------------------------------------
// [OpenMarketOperation contract]
//
// The OpenMarketOperation contract increases / decreases the total coin supply
// by purchasing / selling ETH from the open market. The price between JLC and
// ETH is determined by a Dutch auction.
//
// Permission: Except public getters, only the ACB can call the methods.
//------------------------------------------------------------------------------
contract OpenMarketOperation_v5 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public PRICE_CHANGE_INTERVAL;
uint public PRICE_CHANGE_PERCENTAGE;
uint public PRICE_CHANGE_MAX;
uint public PRICE_MULTIPLIER;
// Attributes. See the comment in initialize().
uint public latest_price_;
bool public latest_price_updated_;
uint public start_price_;
int public coin_budget_;
// Events.
event IncreaseCoinSupplyEvent(uint requested_eth_amount, uint elapsed_time,
uint eth_amount, uint coin_amount);
event DecreaseCoinSupplyEvent(uint requested_coin_amount, uint elapsed_time,
uint eth_balance, uint eth_amount,
uint coin_amount);
event UpdateCoinBudgetEvent(int coin_budget);
// Initializer.
function initialize(uint latest_price, uint start_price, int coin_budget)
public initializer {
__Ownable_init();
// Constants.
// The price auction is implemented as a Dutch auction as follows:
//
// Let P be the latest price at which the open market operation exchanged
// JLC with ETH. The price is measured by ETH wei / JLC. When the price is
// P, it means 1 JLC is exchanged with P ETH wei.
//
// At the beginning of each epoch, the ACB sets the coin budget; i.e., the
// amount of JLC to be purchased / sold by the open market operation.
//
// When the open market operation increases the total coin supply,
// the auction starts with the price of P * PRICE_MULTIPLIER.
// Then the price is decreased by PRICE_CHANGE_PERCENTAGE % every
// PRICE_CHANGE_INTERVAL seconds. JLC and ETH are exchanged at the
// given price (the open market operation sells JLC and purchases ETH).
// The auction stops when the open market operation finished selling JLC
// in the coin budget.
//
// When the open market operation decreases the total coin supply,
// the auction starts with the price of P / PRICE_MULTIPLIER.
// Then the price is increased by PRICE_CHANGE_PERCENTAGE % every
// PRICE_CHANGE_INTERVAL seconds. JLC and ETH are exchanged at the
// given price (the open market operation sells ETH and purchases JLC).
// The auction stops when the open market operation finished purchasing JLC
// in the coin budget.
//
// To avoid the price from increasing / decreasing too much, the price
// is allowed to increase / decrease up to PRICE_CHANGE_MAX times.
//
// TODO: Change PRICE_CHANGE_INTERVAL to 8 * 60 * 60 before launching to the
// mainnet. It's set to 60 seconds for the Ropsten Testnet.
PRICE_CHANGE_INTERVAL = 60; // 8 hours
PRICE_CHANGE_PERCENTAGE = 15; // 15%
PRICE_CHANGE_MAX = 25;
PRICE_MULTIPLIER = 3;
// Attributes.
// The latest price at which the open market operation exchanged JLC with
// ETH.
latest_price_ = latest_price;
// Whether the latest price was updated in the current epoch.
latest_price_updated_ = false;
// The start price is updated at the beginning of each epoch.
start_price_ = start_price;
// The current coin budget.
coin_budget_ = coin_budget;
}
// Increase the total coin supply by purchasing ETH from the sender account.
// This method returns the amount of JLC and ETH to be exchanged. The actual
// change to the total coin supply and the ETH pool is made by the ACB.
//
// Parameters
// ----------------
// |requested_eth_amount|: The amount of ETH the sender is willing to pay.
// |elapsed_time|: The elapsed seconds from the current epoch start.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH to be exchanged. This can be smaller than
// |requested_eth_amount| when the open market operation does not have
// enough coin budget.
// - The amount of JLC to be exchanged.
function increaseCoinSupply(uint requested_eth_amount, uint elapsed_time)
public onlyOwner returns (uint, uint) {
require(coin_budget_ > 0,
"OpenMarketOperation: The coin budget must be positive.");
// Calculate the amount of JLC and ETH to be exchanged.
uint price = getCurrentPrice(elapsed_time);
uint coin_amount = requested_eth_amount / price;
if (coin_amount > coin_budget_.toUint256()) {
coin_amount = coin_budget_.toUint256();
}
uint eth_amount = coin_amount * price;
if (coin_amount > 0) {
latest_price_ = price;
latest_price_updated_ = true;
}
coin_budget_ -= coin_amount.toInt256();
require(coin_budget_ >= 0, "ic1");
require(eth_amount <= requested_eth_amount, "ic2");
emit IncreaseCoinSupplyEvent(requested_eth_amount, elapsed_time,
eth_amount, coin_amount);
return (eth_amount, coin_amount);
}
// Decrease the total coin supply by selling ETH to the sender account.
// This method returns the amount of JLC and ETH to be exchanged. The actual
// change to the total coin supply and the ETH pool is made by the ACB.
//
// Parameters
// ----------------
// |requested_coin_amount|: The amount of JLC the sender is willing to pay.
// |elapsed_time|: The elapsed seconds from the current epoch start.
// |eth_balance|: The ETH balance in the EthPool.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH to be exchanged.
// - The amount of JLC to be exchanged. This can be smaller than
// |requested_coin_amount| when the open market operation does not have
// enough ETH in the pool.
function decreaseCoinSupply(uint requested_coin_amount, uint elapsed_time,
uint eth_balance)
public onlyOwner returns (uint, uint) {
require(coin_budget_ < 0,
"OpenMarketOperation: The coin budget must be negative.");
// Calculate the amount of JLC and ETH to be exchanged.
uint price = getCurrentPrice(elapsed_time);
uint coin_amount = requested_coin_amount;
if (coin_amount >= (-coin_budget_).toUint256()) {
coin_amount = (-coin_budget_).toUint256();
}
uint eth_amount = coin_amount * price;
if (eth_amount >= eth_balance) {
eth_amount = eth_balance;
}
coin_amount = eth_amount / price;
if (coin_amount > 0) {
latest_price_ = price;
latest_price_updated_ = true;
}
coin_budget_ += coin_amount.toInt256();
require(coin_budget_ <= 0, "dc1");
require(coin_amount <= requested_coin_amount, "dc2");
emit DecreaseCoinSupplyEvent(requested_coin_amount, elapsed_time,
eth_balance, eth_amount, coin_amount);
return (eth_amount, coin_amount);
}
// Return the current price in the Dutch auction.
//
// Parameters
// ----------------
// |elapsed_time|: The elapsed seconds from the current epoch start.
//
// Returns
// ----------------
// The current price.
function getCurrentPrice(uint elapsed_time)
public view returns (uint) {
if (coin_budget_ > 0) {
uint price = start_price_;
for (uint i = 0;
i < elapsed_time / PRICE_CHANGE_INTERVAL && i < PRICE_CHANGE_MAX;
i++) {
price = price * (100 - PRICE_CHANGE_PERCENTAGE) / 100;
}
if (price == 0) {
price = 1;
}
return price;
} else if (coin_budget_ < 0) {
uint price = start_price_;
for (uint i = 0;
i < elapsed_time / PRICE_CHANGE_INTERVAL && i < PRICE_CHANGE_MAX;
i++) {
price = price * (100 + PRICE_CHANGE_PERCENTAGE) / 100;
}
return price;
}
return 0;
}
// Update the coin budget. The coin budget indicates how many coins should
// be added to / removed from the total coin supply; i.e., the amount of JLC
// to be sold / purchased by the open market operation. The ACB calls the
// method at the beginning of each epoch.
//
// Parameters
// ----------------
// |coin_budget|: The coin budget.
//
// Returns
// ----------------
// None.
function updateCoinBudget(int coin_budget)
public onlyOwner {
if (latest_price_updated_ == false) {
if (coin_budget_ > 0) {
// If no exchange was observed in the previous epoch, the price setting
// was too high. Lower the price.
latest_price_ = latest_price_ / PRICE_MULTIPLIER + 1;
} else if (coin_budget_ < 0) {
// If no exchange was observed in the previous epoch, the price setting
// was too low. Raise the price.
latest_price_ = latest_price_ * PRICE_MULTIPLIER;
}
}
coin_budget_ = coin_budget;
latest_price_updated_ = false;
require(latest_price_ > 0, "uc1");
if (coin_budget_ > 0) {
start_price_ = latest_price_ * PRICE_MULTIPLIER;
} else if (coin_budget_ == 0) {
start_price_ = 0;
} else {
start_price_ = latest_price_ / PRICE_MULTIPLIER + 1;
}
emit UpdateCoinBudgetEvent(coin_budget_);
}
}
//------------------------------------------------------------------------------
// [ACB contract]
//
// The ACB stabilizes the USD / JLC exchange rate to 1.0 with algorithmically
// defined monetary policies:
//
// 1. The ACB obtains the exchange rate from the oracle.
// 2. If the exchange rate is 1.0, the ACB does nothing.
// 3. If the exchange rate is higher than 1.0, the ACB increases the total coin
// supply by redeeming issued bonds (regardless of their redemption dates).
// If that is not enough to supply sufficient coins, the ACB performs an open
// market operation to sell JLC and purchase ETH to increase the total coin
// supply.
// 4. If the exchange rate is lower than 1.0, the ACB decreases the total coin
// supply by issuing new bonds. If the exchange rate drops down to 0.6, the
// ACB performs an open market operation to sell ETH and purchase JLC to
// decrease the total coin supply.
//
// Permission: All the methods are public. No one (including the genesis
// account) is privileged to influence the monetary policies of the ACB. The ACB
// is fully decentralized and there is truly no gatekeeper. The only exceptions
// are a few methods the genesis account may use to upgrade the smart contracts
// to fix bugs during a development phase.
//------------------------------------------------------------------------------
contract ACB_v5 is OwnableUpgradeable, PausableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
bytes32 public constant NULL_HASH = 0;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint[] public LEVEL_TO_EXCHANGE_RATE;
uint public EXCHANGE_RATE_DIVISOR;
uint public EPOCH_DURATION;
uint public DEPOSIT_RATE;
uint public DAMPING_FACTOR;
// Used only in testing. This cannot be put in a derived contract due to
// a restriction of @openzeppelin/truffle-upgrades.
uint public _timestamp_for_testing;
// Attributes. See the comment in initialize().
JohnLawCoin_v2 public coin_;
Oracle_v3 public old_oracle_;
Oracle_v5 public oracle_;
BondOperation_v5 public bond_operation_;
OpenMarketOperation_v5 public open_market_operation_;
EthPool_v2 public eth_pool_;
Logging_v2 public logging_;
uint public oracle_level_;
uint public current_epoch_start_;
uint public age_;
// Events.
event PayableEvent(address indexed sender, uint value);
event UpdateEpochEvent(uint epoch_id, uint current_epoch_start, uint tax,
uint burned, int delta, uint mint);
event VoteEvent(address indexed sender, uint indexed epoch_id,
bytes32 hash, uint oracle_level, uint salt,
bool commit_result, bool reveal_result,
uint deposited, uint reclaimed, uint rewarded,
bool epoch_updated);
event PurchaseBondsEvent(address indexed sender, uint indexed epoch_id,
uint purchased_bonds, uint redemption_epoch);
event RedeemBondsEvent(address indexed sender, uint indexed epoch_id,
uint redeemed_bonds, uint expired_bonds);
event PurchaseCoinsEvent(address indexed sender, uint requested_eth_amount,
uint eth_amount, uint coin_amount);
event SellCoinsEvent(address indexed sender, uint requested_coin_amount,
uint eth_amount, uint coin_amount);
// Initializer. The ownership of the contracts needs to be transferred to the
// ACB just after the initializer is invoked.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract.
// |oracle|: The Oracle contract.
// |bond_operation|: The BondOperation contract.
// |open_market_operation|: The OpenMarketOperation contract.
// |eth_pool|: The EthPool contract.
// |logging|: The Logging contract.
function initialize(JohnLawCoin_v2 coin, Oracle_v3 old_oracle,
Oracle_v5 oracle, BondOperation_v5 bond_operation,
OpenMarketOperation_v5 open_market_operation,
EthPool_v2 eth_pool,
Logging_v2 logging, uint oracle_level,
uint current_epoch_start)
public initializer {
__Ownable_init();
__Pausable_init();
// Constants.
// The following table shows the mapping from the oracle level to the
// exchange rate. Voters can vote for one of the oracle levels.
//
// ----------------------------------
// | oracle level | exchange rate |
// ----------------------------------
// | 0 | 1 JLC = 0.6 USD |
// | 1 | 1 JLC = 0.7 USD |
// | 2 | 1 JLC = 0.8 USD |
// | 3 | 1 JLC = 0.9 USD |
// | 4 | 1 JLC = 1.0 USD |
// | 5 | 1 JLC = 1.1 USD |
// | 6 | 1 JLC = 1.2 USD |
// | 7 | 1 JLC = 1.3 USD |
// | 8 | 1 JLC = 1.4 USD |
// ----------------------------------
//
// Voters are expected to look up the current exchange rate using
// real-world currency exchangers and vote for the oracle level that is
// closest to the current exchange rate. Strictly speaking, the current
// exchange rate is defined as the exchange rate at the point when the
// current epoch started (i.e., current_epoch_start_).
//
// In the bootstrap phase where no currency exchanger supports JLC <->
// USD conversion, voters are expected to vote for the oracle level 5
// (i.e., 1 JLC = 1.1 USD). This helps increase the total coin supply
// gradually and incentivize early adopters in the bootstrap phase. Once
// a currency exchanger supports the conversion, voters are expected to
// vote for the oracle level that is closest to the real-world exchange
// rate.
//
// Note that 10000000 coins (corresponding to 10 M USD) are given to the
// genesis account initially. This is important to make sure that the
// genesis account has power to determine the exchange rate until the
// ecosystem stabilizes. Once a real-world currency exchanger supports
// the conversion and the oracle gets a sufficient number of honest voters
// to agree on the real-world exchange rate consistently, the genesis
// account can lose its power by decreasing its coin balance, moving the
// oracle to a fully decentralized system. This mechanism is mandatory
// to stabilize the exchange rate and bootstrap the ecosystem successfully.
// LEVEL_TO_EXCHANGE_RATE is the mapping from the oracle levels to the
// exchange rates. The real exchange rate is obtained by dividing the values
// by EXCHANGE_RATE_DIVISOR. For example, 11 corresponds to the exchange
// rate of 1.1. This translation is needed to avoid using float numbers in
// Solidity.
LEVEL_TO_EXCHANGE_RATE = [6, 7, 8, 9, 10, 11, 12, 13, 14];
EXCHANGE_RATE_DIVISOR = 10;
// The duration of the epoch. The ACB adjusts the total coin supply once
// per epoch. Voters can vote once per epoch.
EPOCH_DURATION = 60; // 1 week.
// The percentage of the coin balance voters need to deposit.
DEPOSIT_RATE = 10; // 10%.
// A damping factor to avoid minting or burning too many coins in one epoch.
DAMPING_FACTOR = 10; // 10%.
// Attributes.
// The JohnLawCoin contract.
coin_ = coin;
// The Oracle contract.
old_oracle_ = old_oracle;
// The Oracle contract.
oracle_ = oracle;
// The BondOperation contract.
bond_operation_ = bond_operation;
// The OpenMarketOperation contract.
open_market_operation_ = open_market_operation;
// The EthPool contract.
eth_pool_ = eth_pool;
// The Logging contract.
logging_ = logging;
// The current oracle level.
oracle_level_ = oracle_level;
// The timestamp when the current epoch started.
current_epoch_start_ = current_epoch_start;
age_ = 0;
/*
require(LEVEL_TO_EXCHANGE_RATE.length == oracle.LEVEL_MAX(), "AC1");
*/
}
// Deprecate the ACB. Only the genesis account can call this method.
function deprecate()
public onlyOwner {
coin_.transferOwnership(msg.sender);
old_oracle_.transferOwnership(msg.sender);
oracle_.transferOwnership(msg.sender);
bond_operation_.transferOwnership(msg.sender);
open_market_operation_.transferOwnership(msg.sender);
eth_pool_.transferOwnership(msg.sender);
logging_.transferOwnership(msg.sender);
}
// Pause the ACB in emergency cases. Only the genesis account can call this
// method.
function pause()
public onlyOwner {
if (!paused()) {
_pause();
}
coin_.pause();
}
// Unpause the ACB. Only the genesis account can call this method.
function unpause()
public onlyOwner {
if (paused()) {
_unpause();
}
coin_.unpause();
}
// Payable fallback to receive and store ETH. Give us tips :)
fallback() external payable {
require(msg.data.length == 0, "fb1");
emit PayableEvent(msg.sender, msg.value);
}
receive() external payable {
emit PayableEvent(msg.sender, msg.value);
}
// Withdraw the tips. Only the genesis account can call this method.
function withdrawTips()
public whenNotPaused onlyOwner {
(bool success,) =
payable(msg.sender).call{value: address(this).balance}("");
require(success, "wt1");
}
// A struct to pack local variables. This is needed to avoid a stack-too-deep
// error in Solidity.
struct VoteResult {
uint epoch_id;
bool epoch_updated;
bool reveal_result;
bool commit_result;
uint deposited;
uint reclaimed;
uint rewarded;
}
function _getLevelMax()
internal whenNotPaused view returns (uint) {
if (age_ <= 2) {
return old_oracle_.LEVEL_MAX();
}
return oracle_.LEVEL_MAX();
}
function _getModeLevel()
internal whenNotPaused view returns (uint) {
if (age_ <= 2) {
return old_oracle_.getModeLevel();
}
return oracle_.getModeLevel();
}
// Vote for the exchange rate. The voter can commit a vote to the current
// epoch N, reveal their vote in the epoch N-1, and reclaim the deposited
// coins and get a reward for their vote in the epoch N-2 at the same time.
//
// Parameters
// ----------------
// |hash|: The hash to be committed in the current epoch N. Specify
// ACB.NULL_HASH if you do not want to commit and only want to reveal and
// reclaim previous votes.
// |oracle_level|: The oracle level you voted for in the epoch N-1.
// |salt|: The salt you used in the epoch N-1.
//
// Returns
// ----------------
// A tuple of six values:
// - boolean: Whether the commit succeeded or not.
// - boolean: Whether the reveal succeeded or not.
// - uint: The amount of the deposited coins.
// - uint: The amount of the reclaimed coins.
// - uint: The amount of the reward.
// - boolean: Whether this vote updated the epoch.
function vote(bytes32 hash, uint oracle_level, uint salt)
public whenNotPaused returns (bool, bool, uint, uint, uint, bool) {
VoteResult memory result;
result.epoch_id = oracle_.epoch_id_();
result.epoch_updated = false;
if (getTimestamp() >= current_epoch_start_ + EPOCH_DURATION) {
// Start a new epoch.
result.epoch_updated = true;
result.epoch_id += 1;
current_epoch_start_ = getTimestamp();
age_ += 1;
// Advance to the next epoch. Provide the |tax| coins to the oracle
// as a reward.
uint tax = coin_.balanceOf(coin_.tax_account_());
uint burned = 0;
if (age_ <= 2) {
// Advance the old oracle first to give the tax to the old oracle.
coin_.transferOwnership(address(old_oracle_));
burned = old_oracle_.advance(coin_);
old_oracle_.revokeOwnership(coin_);
coin_.transferOwnership(address(oracle_));
uint ret = oracle_.advance(coin_);
require(ret == 0, "vo1");
oracle_.revokeOwnership(coin_);
} else if (age_ == 3) {
// Advance the new oracle first to give the tax to the new oracle.
coin_.transferOwnership(address(oracle_));
uint ret = oracle_.advance(coin_);
require(ret == 0, "vo2");
oracle_.revokeOwnership(coin_);
coin_.transferOwnership(address(old_oracle_));
burned = old_oracle_.advance(coin_);
old_oracle_.revokeOwnership(coin_);
} else {
// Advance the new oracle first to give the tax to the new oracle.
coin_.transferOwnership(address(oracle_));
burned = oracle_.advance(coin_);
oracle_.revokeOwnership(coin_);
coin_.transferOwnership(address(old_oracle_));
uint ret = old_oracle_.advance(coin_);
require(ret == 0, "vo3");
old_oracle_.revokeOwnership(coin_);
}
// Reset the tax account address just in case.
coin_.resetTaxAccount();
require(coin_.balanceOf(coin_.tax_account_()) == 0, "vo4");
int delta = 0;
oracle_level_ = _getModeLevel();
if (oracle_level_ != _getLevelMax()) {
require(0 <= oracle_level_ &&
oracle_level_ < _getLevelMax(), "vo5");
// Translate the oracle level to the exchange rate.
uint exchange_rate = LEVEL_TO_EXCHANGE_RATE[oracle_level_];
// Calculate the amount of coins to be minted or burned based on the
// Quantity Theory of Money. If the exchange rate is 1.1 (i.e., 1 JLC
// = 1.1 USD), the total coin supply is increased by 10%. If the
// exchange rate is 0.8 (i.e., 1 JLC = 0.8 USD), the total coin supply
// is decreased by 20%.
delta = coin_.totalSupply().toInt256() *
(int(exchange_rate) - int(EXCHANGE_RATE_DIVISOR)) /
int(EXCHANGE_RATE_DIVISOR);
// To avoid increasing or decreasing too many coins in one epoch,
// multiply the damping factor.
delta = delta * int(DAMPING_FACTOR) / 100;
}
// Update the bond budget.
uint mint = bond_operation_.updateBondBudget(delta, result.epoch_id);
// Update the coin budget.
if (oracle_level_ == 0 && delta < 0) {
require(mint == 0, "vo6");
open_market_operation_.updateCoinBudget(delta);
} else {
open_market_operation_.updateCoinBudget(mint.toInt256());
}
logging_.updateEpoch(
result.epoch_id, mint, burned, delta, coin_.totalSupply(),
oracle_level_, current_epoch_start_, tax);
logging_.updateBondBudget(
result.epoch_id, bond_operation_.bond_budget_(),
bond_operation_.bond_().totalSupply(),
bond_operation_.validBondSupply(result.epoch_id));
logging_.updateCoinBudget(
result.epoch_id, open_market_operation_.coin_budget_(),
address(eth_pool_).balance,
open_market_operation_.latest_price_());
emit UpdateEpochEvent(result.epoch_id, current_epoch_start_,
tax, burned, delta, mint);
}
// Commit.
//
// The voter needs to deposit the DEPOSIT_RATE percentage of their coin
// balance.
result.deposited = coin_.balanceOf(msg.sender) * DEPOSIT_RATE / 100;
if (hash == NULL_HASH) {
result.deposited = 0;
}
require(age_ >= 1, "vo7");
coin_.transferOwnership(address(oracle_));
result.commit_result =
oracle_.commit(msg.sender, hash, result.deposited, coin_);
oracle_.revokeOwnership(coin_);
if (!result.commit_result) {
result.deposited = 0;
}
// Reveal.
if (age_ <= 1) {
coin_.transferOwnership(address(old_oracle_));
result.reveal_result = old_oracle_.reveal(msg.sender, oracle_level, salt);
old_oracle_.revokeOwnership(coin_);
} else {
coin_.transferOwnership(address(oracle_));
result.reveal_result = oracle_.reveal(msg.sender, oracle_level, salt);
oracle_.revokeOwnership(coin_);
}
// Reclaim.
if (age_ <= 2) {
coin_.transferOwnership(address(old_oracle_));
(result.reclaimed, result.rewarded) =
old_oracle_.reclaim(msg.sender, coin_);
old_oracle_.revokeOwnership(coin_);
} else {
coin_.transferOwnership(address(oracle_));
(result.reclaimed, result.rewarded) = oracle_.reclaim(msg.sender, coin_);
oracle_.revokeOwnership(coin_);
}
logging_.vote(result.epoch_id, result.commit_result,
result.reveal_result, result.deposited,
result.reclaimed, result.rewarded);
emit VoteEvent(
msg.sender, result.epoch_id, hash, oracle_level, salt,
result.commit_result, result.reveal_result, result.deposited,
result.reclaimed, result.rewarded, result.epoch_updated);
return (result.commit_result, result.reveal_result, result.deposited,
result.reclaimed, result.rewarded, result.epoch_updated);
}
// Purchase bonds.
//
// Parameters
// ----------------
// |count|: The number of bonds to purchase.
//
// Returns
// ----------------
// The redemption epoch of the purchased bonds.
function purchaseBonds(uint count)
public whenNotPaused returns (uint) {
uint epoch_id = oracle_.epoch_id_();
coin_.transferOwnership(address(bond_operation_));
uint redemption_epoch =
bond_operation_.increaseBondSupply(address(msg.sender), count,
epoch_id, coin_);
bond_operation_.revokeOwnership(coin_);
logging_.purchaseBonds(epoch_id, count);
emit PurchaseBondsEvent(address(msg.sender), epoch_id,
count, redemption_epoch);
return redemption_epoch;
}
// Redeem bonds.
//
// Parameters
// ----------------
// |redemption_epochs|: An array of bonds to be redeemed. The bonds are
// identified by their redemption epochs.
//
// Returns
// ----------------
// The number of successfully redeemed bonds.
function redeemBonds(uint[] memory redemption_epochs)
public whenNotPaused returns (uint) {
uint epoch_id = oracle_.epoch_id_();
coin_.transferOwnership(address(bond_operation_));
(uint redeemed_bonds, uint expired_bonds) =
bond_operation_.decreaseBondSupply(
address(msg.sender), redemption_epochs, epoch_id, coin_);
bond_operation_.revokeOwnership(coin_);
logging_.redeemBonds(epoch_id, redeemed_bonds, expired_bonds);
emit RedeemBondsEvent(address(msg.sender), epoch_id,
redeemed_bonds, expired_bonds);
return redeemed_bonds;
}
// Pay ETH and purchase JLC from the open market operation.
//
// Parameters
// ----------------
// The sender needs to pay |requested_eth_amount| ETH.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH the sender paid. This value can be smaller than
// |requested_eth_amount| when the open market operation does not have enough
// coin budget. The remaining ETH is returned to the sender's wallet.
// - The amount of JLC the sender purchased.
function purchaseCoins()
public whenNotPaused payable returns (uint, uint) {
uint requested_eth_amount = msg.value;
uint elapsed_time = getTimestamp() - current_epoch_start_;
// Calculate the amount of ETH and JLC to be exchanged.
(uint eth_amount, uint coin_amount) =
open_market_operation_.increaseCoinSupply(
requested_eth_amount, elapsed_time);
coin_.mint(msg.sender, coin_amount);
require(address(this).balance >= requested_eth_amount, "pc1");
bool success;
(success,) =
payable(address(eth_pool_)).call{value: eth_amount}(
abi.encodeWithSignature("increaseEth()"));
require(success, "pc2");
logging_.purchaseCoins(oracle_.epoch_id_(), eth_amount, coin_amount);
// Pay back the remaining ETH to the sender. This may trigger any arbitrary
// operations in an external smart contract. This must be called at the very
// end of purchaseCoins().
(success,) =
payable(msg.sender).call{value: requested_eth_amount - eth_amount}("");
require(success, "pc3");
emit PurchaseCoinsEvent(msg.sender, requested_eth_amount,
eth_amount, coin_amount);
return (eth_amount, coin_amount);
}
// Pay JLC and purchase ETH from the open market operation.
//
// Parameters
// ----------------
// |requested_coin_amount|: The amount of JLC the sender is willing to pay.
//
// Returns
// ----------------
// A tuple of two values:
// - The amount of ETH the sender purchased.
// - The amount of JLC the sender paid. This value can be smaller than
// |requested_coin_amount| when the open market operation does not have
// enough ETH in the pool.
function sellCoins(uint requested_coin_amount)
public whenNotPaused returns (uint, uint) {
// The sender does not have enough coins.
require(coin_.balanceOf(msg.sender) >= requested_coin_amount,
"OpenMarketOperation: Your coin balance is not enough.");
// Calculate the amount of ETH and JLC to be exchanged.
uint elapsed_time = getTimestamp() - current_epoch_start_;
(uint eth_amount, uint coin_amount) =
open_market_operation_.decreaseCoinSupply(
requested_coin_amount, elapsed_time, address(eth_pool_).balance);
coin_.burn(msg.sender, coin_amount);
logging_.sellCoins(oracle_.epoch_id_(), eth_amount, coin_amount);
// Send ETH to the sender. This may trigger any arbitrary operations in an
// external smart contract. This must be called at the very end of
// sellCoins().
eth_pool_.decreaseEth(msg.sender, eth_amount);
emit SellCoinsEvent(msg.sender, requested_coin_amount,
eth_amount, coin_amount);
return (eth_amount, coin_amount);
}
// Calculate a hash to be committed to the oracle. Voters are expected to call
// this function to create the hash.
//
// Parameters
// ----------------
// |level|: The oracle level to vote.
// |salt|: The voter's salt.
//
// Returns
// ----------------
// The calculated hash value.
function encrypt(uint level, uint salt)
public view returns (bytes32) {
address sender = msg.sender;
if (age_ <= 2) {
return old_oracle_.encrypt(sender, level, salt);
}
return oracle_.encrypt(sender, level, salt);
}
// Public getter: Return the current timestamp in seconds.
function getTimestamp()
public virtual view returns (uint) {
// block.timestamp is better than block.number because the granularity of
// the epoch update is EPOCH_DURATION (1 week).
return block.timestamp;
}
}
| Deprecate the contract. | function deprecate()
public onlyOwner {
bond_.transferOwnership(msg.sender);
}
| 5,366,779 |
pragma solidity ^0.4.18;
import "../token/ERC20/StandardToken.sol";
/**
* @title GPayCoin G支付积分合约,
* 合约内容:
* 发行方:G支付互联网科技有限公司
* 积分名称: GPayCoin
* 发行总量: 2100 0000
* 积分单位: GPC
* 最小流通单位: 0.0001GPC
* RMB兑换:1RMB = 1GPC
*
* Features:
* 1、采用基于以太坊ERC20标准
* 2、G支付积分,应用于G支付项目内部点对点转账、消费、投资、理财、服务等业务与黄金珠宝产业支付、结算。
* 3、采用区块链分布式账本,信息公开透明、可追根溯源、不可篡改,具有信用的积分。
* @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `StandardToken` functions.
*/
contract GPayCoin is StandardToken {
string public constant name = "GPayCoin"; // solium-disable-line uppercase
string public constant symbol = "GPC"; // solium-disable-line uppercase
uint8 public constant decimals = 4; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 21000000 * (10 ** uint256(decimals));
/**
* 构造函数
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function GPayCoin() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
| 构造函数 Constructor that gives msg.sender all of existing tokens./ | function GPayCoin() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
| 14,015,120 |
pragma solidity 0.4.24;
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library Buffer {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
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) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte string to a 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.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a 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, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to 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, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to 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, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to 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, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
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 appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.appendUint8(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.appendUint8(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.appendUint8(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.appendUint8(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 value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string 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);
}
}
/**
* @title Library for common Chainlink functions
* @dev Uses imported CBOR library for encoding to buffer
*/
library Chainlink {
uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase
using CBOR for Buffer.buffer;
struct Request {
bytes32 id;
address callbackAddress;
bytes4 callbackFunctionId;
uint256 nonce;
Buffer.buffer buf;
}
/**
* @notice Initializes a Chainlink request
* @dev Sets the ID, callback address, and callback function signature on the request
* @param self The uninitialized request
* @param _id The Job Specification ID
* @param _callbackAddress The callback address
* @param _callbackFunction The callback function signature
* @return The initialized request
*/
function initialize(
Request memory self,
bytes32 _id,
address _callbackAddress,
bytes4 _callbackFunction
) internal pure returns (Chainlink.Request memory) {
Buffer.init(self.buf, defaultBufferSize);
self.id = _id;
self.callbackAddress = _callbackAddress;
self.callbackFunctionId = _callbackFunction;
return self;
}
/**
* @notice Sets the data for the buffer without encoding CBOR on-chain
* @dev CBOR can be closed with curly-brackets {} or they can be left off
* @param self The initialized request
* @param _data The CBOR data
*/
function setBuffer(Request memory self, bytes _data)
internal pure
{
Buffer.init(self.buf, _data.length);
Buffer.append(self.buf, _data);
}
/**
* @notice Adds a string value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The string value to add
*/
function add(Request memory self, string _key, string _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeString(_value);
}
/**
* @notice Adds a bytes value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The bytes value to add
*/
function addBytes(Request memory self, string _key, bytes _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeBytes(_value);
}
/**
* @notice Adds a int256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The int256 value to add
*/
function addInt(Request memory self, string _key, int256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeInt(_value);
}
/**
* @notice Adds a uint256 value to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _value The uint256 value to add
*/
function addUint(Request memory self, string _key, uint256 _value)
internal pure
{
self.buf.encodeString(_key);
self.buf.encodeUInt(_value);
}
/**
* @notice Adds an array of strings to the request with a given key name
* @param self The initialized request
* @param _key The name of the key
* @param _values The array of string values to add
*/
function addStringArray(Request memory self, string _key, string[] memory _values)
internal pure
{
self.buf.encodeString(_key);
self.buf.startArray();
for (uint256 i = 0; i < _values.length; i++) {
self.buf.encodeString(_values[i]);
}
self.buf.endSequence();
}
}
interface ENSInterface {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
interface LinkTokenInterface {
function allowance(address owner, address spender) external returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external returns (uint256 balance);
function decimals() external returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external returns (string tokenName);
function symbol() external returns (string tokenSymbol);
function totalSupply() external returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
interface ChainlinkRequestInterface {
function oracleRequest(
address sender,
uint256 payment,
bytes32 id,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 nonce,
uint256 version,
bytes data
) external;
function cancelOracleRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunctionId,
uint256 expiration
) external;
}
interface PointerInterface {
function getAddress() external view returns (address);
}
contract ENSResolver {
function addr(bytes32 node) public view returns (address);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title The ChainlinkClient contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Chainlink network
*/
contract ChainlinkClient {
using Chainlink for Chainlink.Request;
using SafeMath for uint256;
uint256 constant internal LINK = 10**18;
uint256 constant private AMOUNT_OVERRIDE = 0;
address constant private SENDER_OVERRIDE = 0x0;
uint256 constant private ARGS_VERSION = 1;
bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link");
bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle");
address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private ens;
bytes32 private ensNode;
LinkTokenInterface private link;
ChainlinkRequestInterface private oracle;
uint256 private requests = 1;
mapping(bytes32 => address) private pendingRequests;
event ChainlinkRequested(bytes32 indexed id);
event ChainlinkFulfilled(bytes32 indexed id);
event ChainlinkCancelled(bytes32 indexed id);
/**
* @notice Creates a request that can hold additional parameters
* @param _specId The Job Specification ID that the request will be created for
* @param _callbackAddress The callback address that the response will be sent to
* @param _callbackFunctionSignature The callback function signature to use for the callback address
* @return A Chainlink Request struct in memory
*/
function buildChainlinkRequest(
bytes32 _specId,
address _callbackAddress,
bytes4 _callbackFunctionSignature
) internal pure returns (Chainlink.Request memory) {
Chainlink.Request memory req;
return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev Calls `chainlinkRequestTo` with the stored oracle address
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return The request ID
*/
function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32)
{
return sendChainlinkRequestTo(oracle, _req, _payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param _oracle The address of the oracle for the request
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return The request ID
*/
function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32 requestId)
{
requestId = keccak256(abi.encodePacked(this, requests));
_req.nonce = requests;
pendingRequests[requestId] = _oracle;
emit ChainlinkRequested(requestId);
require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle");
requests += 1;
return requestId;
}
/**
* @notice Allows a request to be cancelled if it has not been fulfilled
* @dev Requires keeping track of the expiration value emitted from the oracle contract.
* Deletes the request from the `pendingRequests` mapping.
* Emits ChainlinkCancelled event.
* @param _requestId The request ID
* @param _payment The amount of LINK sent for the request
* @param _callbackFunc The callback function specified for the request
* @param _expiration The time of the expiration for the request
*/
function cancelChainlinkRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunc,
uint256 _expiration
)
internal
{
ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]);
delete pendingRequests[_requestId];
emit ChainlinkCancelled(_requestId);
requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration);
}
/**
* @notice Sets the stored oracle address
* @param _oracle The address of the oracle contract
*/
function setChainlinkOracle(address _oracle) internal {
oracle = ChainlinkRequestInterface(_oracle);
}
/**
* @notice Sets the LINK token address
* @param _link The address of the LINK token contract
*/
function setChainlinkToken(address _link) internal {
link = LinkTokenInterface(_link);
}
/**
* @notice Sets the Chainlink token address for the public
* network as given by the Pointer contract
*/
function setPublicChainlinkToken() internal {
setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
}
/**
* @notice Retrieves the stored address of the LINK token
* @return The address of the LINK token
*/
function chainlinkTokenAddress()
internal
view
returns (address)
{
return address(link);
}
/**
* @notice Retrieves the stored address of the oracle contract
* @return The address of the oracle contract
*/
function chainlinkOracleAddress()
internal
view
returns (address)
{
return address(oracle);
}
/**
* @notice Allows for a request which was created on another contract to be fulfilled
* on this contract
* @param _oracle The address of the oracle contract that will fulfill the request
* @param _requestId The request ID used for the response
*/
function addChainlinkExternalRequest(address _oracle, bytes32 _requestId)
internal
notPendingRequest(_requestId)
{
pendingRequests[_requestId] = _oracle;
}
/**
* @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS
* @dev Accounts for subnodes having different resolvers
* @param _ens The address of the ENS contract
* @param _node The ENS node hash
*/
function useChainlinkWithENS(address _ens, bytes32 _node)
internal
{
ens = ENSInterface(_ens);
ensNode = _node;
bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
ENSResolver resolver = ENSResolver(ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
/**
* @notice Sets the stored oracle contract with the address resolved by ENS
* @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously
*/
function updateChainlinkOracleWithENS()
internal
{
bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME));
ENSResolver resolver = ENSResolver(ens.resolver(oracleSubnode));
setChainlinkOracle(resolver.addr(oracleSubnode));
}
/**
* @notice Encodes the request to be sent to the oracle contract
* @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types
* will be validated in the oracle contract.
* @param _req The initialized Chainlink Request
* @return The bytes payload for the `transferAndCall` method
*/
function encodeRequest(Chainlink.Request memory _req)
private
view
returns (bytes memory)
{
return abi.encodeWithSelector(
oracle.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
_req.id,
_req.callbackAddress,
_req.callbackFunctionId,
_req.nonce,
ARGS_VERSION,
_req.buf.buf);
}
/**
* @notice Ensures that the fulfillment is valid for this contract
* @dev Use if the contract developer prefers methods instead of modifiers for validation
* @param _requestId The request ID for fulfillment
*/
function validateChainlinkCallback(bytes32 _requestId)
internal
recordChainlinkFulfillment(_requestId)
// solhint-disable-next-line no-empty-blocks
{}
/**
* @dev Reverts if the sender is not the oracle of the request.
* Emits ChainlinkFulfilled event.
* @param _requestId The request ID for fulfillment
*/
modifier recordChainlinkFulfillment(bytes32 _requestId) {
require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request");
delete pendingRequests[_requestId];
emit ChainlinkFulfilled(_requestId);
_;
}
/**
* @dev Reverts if the request is already pending
* @param _requestId The request ID for fulfillment
*/
modifier notPendingRequest(bytes32 _requestId) {
require(pendingRequests[_requestId] == address(0), "Request is already pending");
_;
}
}
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
event NewRound(uint256 indexed roundId, address indexed startedBy);
}
library SignedSafeMath {
/**
* @dev Adds two int256s and makes sure the result doesn't overflow. Signed
* integers aren't supported by the SafeMath library, thus this method
* @param _a The first number to be added
* @param _a The second number to be added
*/
function add(int256 _a, int256 _b)
internal
pure
returns (int256)
{
int256 c = _a + _b;
require((_b >= 0 && c >= _a) || (_b < 0 && c < _a), "SignedSafeMath: addition overflow");
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title An example Chainlink contract with aggregation
* @notice Requesters can use this contract as a framework for creating
* requests to multiple Chainlink nodes and running aggregation
* as the contract receives answers.
*/
contract Aggregator is AggregatorInterface, ChainlinkClient, Ownable {
using SignedSafeMath for int256;
struct Answer {
uint128 minimumResponses;
uint128 maxResponses;
int256[] responses;
}
event ResponseReceived(int256 indexed response, uint256 indexed answerId, address indexed sender);
int256 private currentAnswerValue;
uint256 private updatedTimestampValue;
uint256 private latestCompletedAnswer;
uint128 public paymentAmount;
uint128 public minimumResponses;
bytes32[] public jobIds;
address[] public oracles;
uint256 private answerCounter = 1;
mapping(address => bool) public authorizedRequesters;
mapping(bytes32 => uint256) private requestAnswers;
mapping(uint256 => Answer) private answers;
mapping(uint256 => int256) private currentAnswers;
mapping(uint256 => uint256) private updatedTimestamps;
uint256 constant private MAX_ORACLE_COUNT = 45;
/**
* @notice Deploy with the address of the LINK token and arrays of matching
* length containing the addresses of the oracles and their corresponding
* Job IDs.
* @dev Sets the LinkToken address for the network, addresses of the oracles,
* and jobIds in storage.
* @param _link The address of the LINK token
* @param _paymentAmount the amount of LINK to be sent to each oracle for each request
* @param _minimumResponses the minimum number of responses
* before an answer will be calculated
* @param _oracles An array of oracle addresses
* @param _jobIds An array of Job IDs
*/
constructor(
address _link,
uint128 _paymentAmount,
uint128 _minimumResponses,
address[] _oracles,
bytes32[] _jobIds
) public Ownable() {
setChainlinkToken(_link);
updateRequestDetails(_paymentAmount, _minimumResponses, _oracles, _jobIds);
}
/**
* @notice Creates a Chainlink request for each oracle in the oracles array.
* @dev This example does not include request parameters. Reference any documentation
* associated with the Job IDs used to determine the required parameters per-request.
*/
function requestRateUpdate()
external
ensureAuthorizedRequester()
{
Chainlink.Request memory request;
bytes32 requestId;
uint256 oraclePayment = paymentAmount;
for (uint i = 0; i < oracles.length; i++) {
request = buildChainlinkRequest(jobIds[i], this, this.chainlinkCallback.selector);
requestId = sendChainlinkRequestTo(oracles[i], request, oraclePayment);
requestAnswers[requestId] = answerCounter;
}
answers[answerCounter].minimumResponses = minimumResponses;
answers[answerCounter].maxResponses = uint128(oracles.length);
answerCounter = answerCounter.add(1);
emit NewRound(answerCounter, msg.sender);
}
/**
* @notice Receives the answer from the Chainlink node.
* @dev This function can only be called by the oracle that received the request.
* @param _clRequestId The Chainlink request ID associated with the answer
* @param _response The answer provided by the Chainlink node
*/
function chainlinkCallback(bytes32 _clRequestId, int256 _response)
external
{
validateChainlinkCallback(_clRequestId);
uint256 answerId = requestAnswers[_clRequestId];
delete requestAnswers[_clRequestId];
answers[answerId].responses.push(_response);
emit ResponseReceived(_response, answerId, msg.sender);
updateLatestAnswer(answerId);
deleteAnswer(answerId);
}
/**
* @notice Updates the arrays of oracles and jobIds with new values,
* overwriting the old values.
* @dev Arrays are validated to be equal length.
* @param _paymentAmount the amount of LINK to be sent to each oracle for each request
* @param _minimumResponses the minimum number of responses
* before an answer will be calculated
* @param _oracles An array of oracle addresses
* @param _jobIds An array of Job IDs
*/
function updateRequestDetails(
uint128 _paymentAmount,
uint128 _minimumResponses,
address[] _oracles,
bytes32[] _jobIds
)
public
onlyOwner()
validateAnswerRequirements(_minimumResponses, _oracles, _jobIds)
{
paymentAmount = _paymentAmount;
minimumResponses = _minimumResponses;
jobIds = _jobIds;
oracles = _oracles;
}
/**
* @notice Allows the owner of the contract to withdraw any LINK balance
* available on the contract.
* @dev The contract will need to have a LINK balance in order to create requests.
* @param _recipient The address to receive the LINK tokens
* @param _amount The amount of LINK to send from the contract
*/
function transferLINK(address _recipient, uint256 _amount)
public
onlyOwner()
{
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(_recipient, _amount), "LINK transfer failed");
}
/**
* @notice Called by the owner to permission other addresses to generate new
* requests to oracles.
* @param _requester the address whose permissions are being set
* @param _allowed boolean that determines whether the requester is
* permissioned or not
*/
function setAuthorization(address _requester, bool _allowed)
external
onlyOwner()
{
authorizedRequesters[_requester] = _allowed;
}
/**
* @notice Cancels an outstanding Chainlink request.
* The oracle contract requires the request ID and additional metadata to
* validate the cancellation. Only old answers can be cancelled.
* @param _requestId is the identifier for the chainlink request being cancelled
* @param _payment is the amount of LINK paid to the oracle for the request
* @param _expiration is the time when the request expires
*/
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
uint256 _expiration
)
external
ensureAuthorizedRequester()
{
uint256 answerId = requestAnswers[_requestId];
require(answerId < latestCompletedAnswer, "Cannot modify an in-progress answer");
delete requestAnswers[_requestId];
answers[answerId].responses.push(0);
deleteAnswer(answerId);
cancelChainlinkRequest(
_requestId,
_payment,
this.chainlinkCallback.selector,
_expiration
);
}
/**
* @notice Called by the owner to kill the contract. This transfers all LINK
* balance and ETH balance (if there is any) to the owner.
*/
function destroy()
external
onlyOwner()
{
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
transferLINK(owner, linkToken.balanceOf(address(this)));
selfdestruct(owner);
}
/**
* @dev Performs aggregation of the answers received from the Chainlink nodes.
* Assumes that at least half the oracles are honest and so can't contol the
* middle of the ordered responses.
* @param _answerId The answer ID associated with the group of requests
*/
function updateLatestAnswer(uint256 _answerId)
private
ensureMinResponsesReceived(_answerId)
ensureOnlyLatestAnswer(_answerId)
{
uint256 responseLength = answers[_answerId].responses.length;
uint256 middleIndex = responseLength.div(2);
int256 currentAnswerTemp;
if (responseLength % 2 == 0) {
int256 median1 = quickselect(answers[_answerId].responses, middleIndex);
int256 median2 = quickselect(answers[_answerId].responses, middleIndex.add(1)); // quickselect is 1 indexed
currentAnswerTemp = median1.add(median2) / 2; // signed integers are not supported by SafeMath
} else {
currentAnswerTemp = quickselect(answers[_answerId].responses, middleIndex.add(1)); // quickselect is 1 indexed
}
currentAnswerValue = currentAnswerTemp;
latestCompletedAnswer = _answerId;
updatedTimestampValue = now;
updatedTimestamps[_answerId] = now;
currentAnswers[_answerId] = currentAnswerTemp;
emit AnswerUpdated(currentAnswerTemp, _answerId, now);
}
/**
* @notice get the most recently reported answer
*/
function latestAnswer()
external
view
returns (int256)
{
return currentAnswers[latestCompletedAnswer];
}
/**
* @notice get the last updated at block timestamp
*/
function latestTimestamp()
external
view
returns (uint256)
{
return updatedTimestamps[latestCompletedAnswer];
}
/**
* @notice get past rounds answers
* @param _roundId the answer number to retrieve the answer for
*/
function getAnswer(uint256 _roundId)
external
view
returns (int256)
{
return currentAnswers[_roundId];
}
/**
* @notice get block timestamp when an answer was last updated
* @param _roundId the answer number to retrieve the updated timestamp for
*/
function getTimestamp(uint256 _roundId)
external
view
returns (uint256)
{
return updatedTimestamps[_roundId];
}
/**
* @notice get the latest completed round where the answer was updated
*/
function latestRound() external view returns (uint256) {
return latestCompletedAnswer;
}
/**
* @dev Returns the kth value of the ordered array
* See: http://www.cs.yale.edu/homes/aspnes/pinewiki/QuickSelect.html
* @param _a The list of elements to pull from
* @param _k The index, 1 based, of the elements you want to pull from when ordered
*/
function quickselect(int256[] memory _a, uint256 _k)
private
pure
returns (int256)
{
int256[] memory a = _a;
uint256 k = _k;
uint256 aLen = a.length;
int256[] memory a1 = new int256[](aLen);
int256[] memory a2 = new int256[](aLen);
uint256 a1Len;
uint256 a2Len;
int256 pivot;
uint256 i;
while (true) {
pivot = a[aLen.div(2)];
a1Len = 0;
a2Len = 0;
for (i = 0; i < aLen; i++) {
if (a[i] < pivot) {
a1[a1Len] = a[i];
a1Len++;
} else if (a[i] > pivot) {
a2[a2Len] = a[i];
a2Len++;
}
}
if (k <= a1Len) {
aLen = a1Len;
(a, a1) = swap(a, a1);
} else if (k > (aLen.sub(a2Len))) {
k = k.sub(aLen.sub(a2Len));
aLen = a2Len;
(a, a2) = swap(a, a2);
} else {
return pivot;
}
}
}
/**
* @dev Swaps the pointers to two uint256 arrays in memory
* @param _a The pointer to the first in memory array
* @param _b The pointer to the second in memory array
*/
function swap(int256[] memory _a, int256[] memory _b)
private
pure
returns(int256[] memory, int256[] memory)
{
return (_b, _a);
}
/**
* @dev Cleans up the answer record if all responses have been received.
* @param _answerId The identifier of the answer to be deleted
*/
function deleteAnswer(uint256 _answerId)
private
ensureAllResponsesReceived(_answerId)
{
delete answers[_answerId];
}
/**
* @dev Prevents taking an action if the minimum number of responses has not
* been received for an answer.
* @param _answerId The the identifier of the answer that keeps track of the responses.
*/
modifier ensureMinResponsesReceived(uint256 _answerId) {
if (answers[_answerId].responses.length >= answers[_answerId].minimumResponses) {
_;
}
}
/**
* @dev Prevents taking an action if not all responses are received for an answer.
* @param _answerId The the identifier of the answer that keeps track of the responses.
*/
modifier ensureAllResponsesReceived(uint256 _answerId) {
if (answers[_answerId].responses.length == answers[_answerId].maxResponses) {
_;
}
}
/**
* @dev Prevents taking an action if a newer answer has been recorded.
* @param _answerId The current answer's identifier.
* Answer IDs are in ascending order.
*/
modifier ensureOnlyLatestAnswer(uint256 _answerId) {
if (latestCompletedAnswer <= _answerId) {
_;
}
}
/**
* @dev Ensures corresponding number of oracles and jobs.
* @param _oracles The list of oracles.
* @param _jobIds The list of jobs.
*/
modifier validateAnswerRequirements(
uint256 _minimumResponses,
address[] _oracles,
bytes32[] _jobIds
) {
require(_oracles.length <= MAX_ORACLE_COUNT, "cannot have more than 45 oracles");
require(_oracles.length >= _minimumResponses, "must have at least as many oracles as responses");
require(_oracles.length == _jobIds.length, "must have exactly as many oracles as job IDs");
_;
}
/**
* @dev Reverts if `msg.sender` is not authorized to make requests.
*/
modifier ensureAuthorizedRequester() {
require(authorizedRequesters[msg.sender] || msg.sender == owner, "Not an authorized address for creating requests");
_;
}
} | Retrieves the stored address of the oracle contract return The address of the oracle contract/ | function chainlinkOracleAddress()
internal
view
returns (address)
{
return address(oracle);
}
| 464,626 |
// SPDX-License-Identifier: MIT
pragma solidity >= 0.5.0;
pragma experimental ABIEncoderV2;
import './ERC721Mintable.sol';
import './SquareVerifier.sol';
// TODO define a contract call to the zokrates generated solidity contract <Verifier> or <renamedVerifier>
// TODO define another contract named SolnSquareVerifier that inherits from your ERC721Mintable class
contract SolnSquareVerifier is ERC721Mintable, SquareVerifier {
uint256 public solutionCount; // for testing
// SquareVerifier private squareVerifier;
// TODO define a solutions struct that can hold an index & an address
struct Solution {
address tokenOwner;
uint256 tokenId;
}
// TODO define an array of the above struct
Solution[] private solutions;
// TODO define a mapping to store unique solutions submitted
// Give tokenId => Return array position
mapping(uint256 => uint) private solutionMappings;
// TODO Create an event to emit when a solution is added
event SolutionAdded(Solution solution);
constructor(string memory name, string memory symbol, string memory baseTokenURI)
ERC721Mintable(name, symbol, baseTokenURI) public {
solutionCount = 0;
}
// TODO Create a function to add the solutions to the array and emit the event
function AddSolution(
address tokenAddress,
uint256 tokenId,
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[2] memory input
) public {
require(tokenAddress != address(0), "Invalid Address");
if(solutionMappings[tokenId] != 0) // Solution already exists for this token
return;
bool validProof = verifyTx( a,
b,
c,
input);
require(validProof, "SolnSquareVerifier: Invalid Proof");
Solution memory sol = Solution( { tokenOwner: tokenAddress,
tokenId: tokenId
});
solutions.push(sol);
solutionMappings[tokenId] = solutions.length; //to reference solution in array will need to subtract 1. Not doing it here because checking for existence by checking for zero
solutionCount++;
emit SolutionAdded(sol);
}
// TODO Create a function to mint new NFT only after the solution has been verified
// - make sure the solution is unique (has not been used before)
// - make sure you handle metadata as well as tokenSupply
function mintNewNFT(address tokenAddress,
uint256 tokenId,
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[2] memory input) public {
AddSolution(tokenAddress, tokenId, a, b, c, input);
// Don't use the tokenAddress passed in, solution may have been added previously
// Need to use the token address for the solution
// solutions[array_position].tokenOwner
// solutionMappings[tokenId] returns the LENGTH of the array at the time of adding
// solutionMappings[tokenId]-1 returns the arrat position of the solution
// require(tokenAddress == solutions[solutionMappings[tokenId]-1].tokenOwner, "SolnSquareVerifier: You must be the owner to mint this token");
mint(solutions[solutionMappings[tokenId]-1].tokenOwner, tokenId);
}
}
| TODO Create a function to add the solutions to the array and emit the event | function AddSolution(
address tokenAddress,
uint256 tokenId,
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[2] memory input
) public {
require(tokenAddress != address(0), "Invalid Address");
return;
bool validProof = verifyTx( a,
b,
c,
input);
require(validProof, "SolnSquareVerifier: Invalid Proof");
Solution memory sol = Solution( { tokenOwner: tokenAddress,
tokenId: tokenId
});
solutions.push(sol);
solutionCount++;
emit SolutionAdded(sol);
}
| 6,409,536 |
pragma solidity ^0.4.13;
/**
* Math operations with safety checks
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract UinfoToken is StandardToken {
using SafeMath for uint256;
uint8 public constant decimals = 18;
uint public constant INITIAL_SUPPLY = 10 ** (9 + uint(decimals));
string public constant name = "Ur Infomation,Useful Infomation";
string public constant symbol = "UINFO";
function UinfoToken () public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
} | Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/ | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
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;
}
| 1,658,508 |
pragma solidity 0.5.16;
// Inheritance
import "./Owned.sol";
import "./MixinResolver.sol";
import "./MixinSystemSettings.sol";
import "./interfaces/IIssuer.sol";
// Libraries
import "./SafeDecimalMath.sol";
// Internal references
import "./interfaces/IPynth.sol";
import "./interfaces/IPeriFinance.sol";
import "./interfaces/IFeePool.sol";
import "./interfaces/IPeriFinanceState.sol";
import "./interfaces/IExchanger.sol";
import "./interfaces/IDelegateApprovals.sol";
import "./interfaces/IExchangeRates.sol";
import "./interfaces/IEtherCollateral.sol";
import "./interfaces/IEtherCollateralpUSD.sol";
import "./interfaces/IHasBalance.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/ILiquidations.sol";
import "./interfaces/ICollateralManager.sol";
import "./interfaces/IExternalTokenStakeManager.sol";
import "./interfaces/ICrossChainManager.sol";
interface IRewardEscrowV2 {
// Views
function balanceOf(address account) external view returns (uint);
}
interface IIssuerInternalDebtCache {
function updateCachedPynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external;
function updateCachedPynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateDebtCacheValidity(bool currentlyInvalid) external;
function cacheInfo()
external
view
returns (
uint cachedDebt,
uint timestamp,
bool isInvalid,
bool isStale
);
}
// https://docs.peri.finance/contracts/source/contracts/issuer
contract Issuer is Owned, MixinSystemSettings, IIssuer {
using SafeMath for uint;
using SafeDecimalMath for uint;
// Available Pynths which can be used with the system
IPynth[] public availablePynths;
mapping(bytes32 => IPynth) public pynths;
mapping(address => bytes32) public pynthsByAddress;
/* ========== ENCODED NAMES ========== */
bytes32 internal constant pUSD = "pUSD";
bytes32 internal constant pETH = "pETH";
bytes32 internal constant PERI = "PERI";
// Flexible storage names
bytes32 public constant CONTRACT_NAME = "Issuer";
bytes32 internal constant LAST_ISSUE_EVENT = "lastIssueEvent";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_PERIFINANCE = "PeriFinance";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals";
bytes32 private constant CONTRACT_ETHERCOLLATERAL = "EtherCollateral";
bytes32 private constant CONTRACT_ETHERCOLLATERAL_PUSD = "EtherCollateralpUSD";
bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_PERIFINANCEESCROW = "PeriFinanceEscrow";
bytes32 private constant CONTRACT_LIQUIDATIONS = "Liquidations";
bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache";
bytes32 private constant CONTRACT_EXTOKENSTAKEMANAGER = "ExternalTokenStakeManager";
bytes32 private constant CONTRACT_CROSSCHAINMANAGER = "CrossChainManager";
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](15);
newAddresses[0] = CONTRACT_PERIFINANCE;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_PERIFINANCESTATE;
newAddresses[4] = CONTRACT_FEEPOOL;
newAddresses[5] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[6] = CONTRACT_ETHERCOLLATERAL;
newAddresses[7] = CONTRACT_ETHERCOLLATERAL_PUSD;
newAddresses[8] = CONTRACT_REWARDESCROW_V2;
newAddresses[9] = CONTRACT_PERIFINANCEESCROW;
newAddresses[10] = CONTRACT_LIQUIDATIONS;
newAddresses[11] = CONTRACT_DEBTCACHE;
newAddresses[12] = CONTRACT_COLLATERALMANAGER;
newAddresses[13] = CONTRACT_EXTOKENSTAKEMANAGER;
newAddresses[14] = CONTRACT_CROSSCHAINMANAGER;
return combineArrays(existingAddresses, newAddresses);
}
function periFinance() internal view returns (IPeriFinance) {
return IPeriFinance(requireAndGetAddress(CONTRACT_PERIFINANCE));
}
function exTokenStakeManager() internal view returns (IExternalTokenStakeManager) {
return IExternalTokenStakeManager(requireAndGetAddress(CONTRACT_EXTOKENSTAKEMANAGER));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function periFinanceState() internal view returns (IPeriFinanceState) {
return IPeriFinanceState(requireAndGetAddress(CONTRACT_PERIFINANCESTATE));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function liquidations() internal view returns (ILiquidations) {
return ILiquidations(requireAndGetAddress(CONTRACT_LIQUIDATIONS));
}
function delegateApprovals() internal view returns (IDelegateApprovals) {
return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS));
}
function etherCollateral() internal view returns (IEtherCollateral) {
return IEtherCollateral(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL));
}
function etherCollateralpUSD() internal view returns (IEtherCollateralpUSD) {
return IEtherCollateralpUSD(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL_PUSD));
}
function collateralManager() internal view returns (ICollateralManager) {
return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function periFinanceEscrow() internal view returns (IHasBalance) {
return IHasBalance(requireAndGetAddress(CONTRACT_PERIFINANCEESCROW));
}
function debtCache() internal view returns (IIssuerInternalDebtCache) {
return IIssuerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE));
}
function crossChainManager() internal view returns (ICrossChainManager) {
return ICrossChainManager(requireAndGetAddress(CONTRACT_CROSSCHAINMANAGER));
}
function _availableCurrencyKeysWithOptionalPERI(bool withPERI) internal view returns (bytes32[] memory) {
bytes32[] memory currencyKeys = new bytes32[](availablePynths.length + (withPERI ? 1 : 0));
for (uint i = 0; i < availablePynths.length; i++) {
currencyKeys[i] = pynthsByAddress[address(availablePynths[i])];
}
if (withPERI) {
currencyKeys[availablePynths.length] = PERI;
}
return currencyKeys;
}
function _totalIssuedPynths(bytes32 currencyKey, bool excludeCollateral)
internal
view
returns (uint totalIssued, bool anyRateIsInvalid)
{
(uint debt, , bool cacheIsInvalid, bool cacheIsStale) = debtCache().cacheInfo();
anyRateIsInvalid = cacheIsInvalid || cacheIsStale;
IExchangeRates exRates = exchangeRates();
// Add total issued pynths from non peri collateral back into the total if not excluded
if (!excludeCollateral) {
// Get the pUSD equivalent amount of all the MC issued pynths.
(uint nonPeriDebt, bool invalid) = collateralManager().totalLong();
debt = debt.add(nonPeriDebt);
anyRateIsInvalid = anyRateIsInvalid || invalid;
// Now add the ether collateral stuff as we are still supporting it.
debt = debt.add(etherCollateralpUSD().totalIssuedPynths());
// Add ether collateral pETH
(uint ethRate, bool ethRateInvalid) = exRates.rateAndInvalid(pETH);
uint ethIssuedDebt = etherCollateral().totalIssuedPynths().multiplyDecimalRound(ethRate);
debt = debt.add(ethIssuedDebt);
anyRateIsInvalid = anyRateIsInvalid || ethRateInvalid;
}
if (currencyKey == pUSD) {
return (debt, anyRateIsInvalid);
}
(uint currencyRate, bool currencyRateInvalid) = exRates.rateAndInvalid(currencyKey);
return (debt.divideDecimalRound(currencyRate), anyRateIsInvalid || currencyRateInvalid);
}
function _debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey)
internal
view
returns (
uint debtBalance,
uint totalSystemValue,
bool anyRateIsInvalid
)
{
IPeriFinanceState state = periFinanceState();
// What was their initial debt ownership?
(uint initialDebtOwnership, uint debtEntryIndex) = state.issuanceData(_issuer);
// What's the total value of the system excluding ETH backed pynths in their requested currency?
(totalSystemValue, anyRateIsInvalid) = crossChainManager().getTotalNetworkAdaptedTotalSystemValue(currencyKey);
// If it's zero, they haven't issued, and they have no debt.
// Note: it's more gas intensive to put this check here rather than before _totalIssuedPynths
// if they have 0 PERI, but it's a necessary trade-off
if (initialDebtOwnership == 0) return (0, totalSystemValue, anyRateIsInvalid);
// Figure out the global debt percentage delta from when they entered the system.
// This is a high precision integer of 27 (1e27) decimals.
uint _debtLedgerLength = state.debtLedgerLength();
uint systemDebt = state.debtLedger(debtEntryIndex);
uint currentDebtOwnership;
if (_debtLedgerLength == 0 || systemDebt == 0) {
currentDebtOwnership = 0;
} else {
currentDebtOwnership = state
.lastDebtLedgerEntry()
.divideDecimalRoundPrecise(systemDebt)
.multiplyDecimalRoundPrecise(initialDebtOwnership);
}
// Their debt balance is their portion of the total system value.
uint highPrecisionBalance =
totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise(currentDebtOwnership);
// Convert back into 18 decimals (1e18)
debtBalance = highPrecisionBalance.preciseDecimalToDecimal();
}
function _canBurnPynths(address account) internal view returns (bool) {
return now >= _lastIssueEvent(account).add(getMinimumStakeTime());
}
function _lastIssueEvent(address account) internal view returns (uint) {
// Get the timestamp of the last issue this account made
return flexibleStorage().getUIntValue(CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)));
}
function _remainingIssuablePynths(address _issuer)
internal
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt,
bool anyRateIsInvalid
)
{
(alreadyIssued, totalSystemDebt, anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, pUSD);
(uint issuable, bool isInvalid) = _maxIssuablePynths(_issuer);
maxIssuable = issuable;
anyRateIsInvalid = anyRateIsInvalid || isInvalid;
if (alreadyIssued >= maxIssuable) {
maxIssuable = 0;
} else {
maxIssuable = maxIssuable.sub(alreadyIssued);
}
}
function _periToUSD(uint amount, uint periRate) internal pure returns (uint) {
return amount.multiplyDecimalRound(periRate);
}
function _usdToPeri(uint amount, uint periRate) internal pure returns (uint) {
return amount.divideDecimalRound(periRate);
}
function _maxIssuablePynths(address _issuer) internal view returns (uint, bool) {
// What is the value of their PERI balance in pUSD
(uint periRate, bool periRateIsInvalid) = exchangeRates().rateAndInvalid(PERI);
uint periCollateral = _periToUSD(_collateral(_issuer), periRate);
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(_issuer, pUSD);
uint destinationValue = periCollateral.add(externalTokenStaked);
// They're allowed to issue up to issuanceRatio of that value
return (destinationValue.multiplyDecimal(getIssuanceRatio()), periRateIsInvalid);
}
function _collateralisationRatio(address _issuer) internal view returns (uint, bool) {
uint totalOwnedPeriFinance = _collateral(_issuer);
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(_issuer, PERI);
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, PERI);
// it's more gas intensive to put this check here if they have 0 PERI, but it complies with the interface
if (totalOwnedPeriFinance == 0 && externalTokenStaked == 0) return (0, anyRateIsInvalid);
uint totalOwned = totalOwnedPeriFinance.add(externalTokenStaked);
return (debtBalance.divideDecimal(totalOwned), anyRateIsInvalid);
}
function _collateral(address account) internal view returns (uint) {
uint balance = IERC20(address(periFinance())).balanceOf(account);
if (address(periFinanceEscrow()) != address(0)) {
balance = balance.add(periFinanceEscrow().balanceOf(account));
}
if (address(rewardEscrowV2()) != address(0)) {
balance = balance.add(rewardEscrowV2().balanceOf(account));
}
return balance;
}
function _amountsToFitClaimable(
uint _currentDebt,
uint _stakedExTokenAmount,
uint _periCollateral
) internal view returns (uint burnAmount, uint exTokenAmountToUnstake) {
uint targetRatio = getIssuanceRatio();
uint exTokenQuota = getExternalTokenQuota();
uint initialCRatio = _currentDebt.divideDecimal(_stakedExTokenAmount.add(_periCollateral));
// it doesn't satisfy target c-ratio
if (initialCRatio > targetRatio) {
uint maxAllowedExTokenStakeAmountByPeriCollateral =
_periCollateral.multiplyDecimal(exTokenQuota.divideDecimal(SafeDecimalMath.unit().sub(exTokenQuota)));
exTokenAmountToUnstake = _stakedExTokenAmount > maxAllowedExTokenStakeAmountByPeriCollateral
? _stakedExTokenAmount.sub(maxAllowedExTokenStakeAmountByPeriCollateral)
: 0;
burnAmount = _currentDebt.sub(
_periCollateral.add(_stakedExTokenAmount).sub(exTokenAmountToUnstake).multiplyDecimal(targetRatio)
);
// it satisfies target c-ratio but violates external token quota
} else {
uint currentExTokenQuota = _stakedExTokenAmount.multiplyDecimal(targetRatio).divideDecimal(_currentDebt);
require(currentExTokenQuota > exTokenQuota, "Account is already claimable");
burnAmount = (_stakedExTokenAmount.multiplyDecimal(targetRatio).sub(_currentDebt.multiplyDecimal(exTokenQuota)))
.divideDecimal(SafeDecimalMath.unit().sub(exTokenQuota));
exTokenAmountToUnstake = burnAmount.divideDecimal(targetRatio);
}
}
/**
* @notice It calculates maximum issue/stake(external token) amount to meet external token quota limit.
*
* @param _from target address
* @param _debtBalance current debt balance[pUSD]
* @param _stakedAmount currently target address's external token staked amount[pUSD]
* @param _currencyKey currency key of external token to stake
*/
function _maxExternalTokenStakeAmount(
address _from,
uint _debtBalance,
uint _stakedAmount,
bytes32 _currencyKey
) internal view returns (uint issueAmount, uint stakeAmount) {
uint targetRatio = getIssuanceRatio();
uint quotaLimit = getExternalTokenQuota();
uint maxAllowedStakingAmount = _debtBalance.multiplyDecimal(quotaLimit).divideDecimal(targetRatio);
if (_stakedAmount >= maxAllowedStakingAmount) {
return (0, 0);
}
stakeAmount = ((maxAllowedStakingAmount).sub(_stakedAmount)).divideDecimal(SafeDecimalMath.unit().sub(quotaLimit));
uint balance = IERC20(exTokenStakeManager().getTokenAddress(_currencyKey)).balanceOf(_from);
stakeAmount = balance < stakeAmount ? balance : stakeAmount;
issueAmount = stakeAmount.multiplyDecimal(targetRatio);
}
function canBurnPynths(address account) external view returns (bool) {
return _canBurnPynths(account);
}
function availableCurrencyKeys() external view returns (bytes32[] memory) {
return _availableCurrencyKeysWithOptionalPERI(false);
}
function availablePynthCount() external view returns (uint) {
return availablePynths.length;
}
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) {
(, anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(_availableCurrencyKeysWithOptionalPERI(true));
}
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral)
external
view
returns (uint totalIssued, bool anyRateIsInvalid)
{
(totalIssued, anyRateIsInvalid) = _totalIssuedPynths(currencyKey, excludeEtherCollateral);
}
function lastIssueEvent(address account) external view returns (uint) {
return _lastIssueEvent(account);
}
function collateralisationRatio(address _issuer) external view returns (uint cratio) {
(cratio, ) = _collateralisationRatio(_issuer);
}
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid)
{
return _collateralisationRatio(_issuer);
}
function collateral(address account) external view returns (uint) {
return _collateral(account);
}
function debtBalanceOf(address _issuer, bytes32 currencyKey) external view returns (uint debtBalance) {
IPeriFinanceState state = periFinanceState();
// What was their initial debt ownership?
(uint initialDebtOwnership, ) = state.issuanceData(_issuer);
// If it's zero, they haven't issued, and they have no debt.
if (initialDebtOwnership == 0) return 0;
(debtBalance, , ) = _debtBalanceOfAndTotalDebt(_issuer, currencyKey);
}
function remainingIssuablePynths(address _issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
)
{
(maxIssuable, alreadyIssued, totalSystemDebt, ) = _remainingIssuablePynths(_issuer);
}
function maxIssuablePynths(address _issuer) external view returns (uint) {
(uint maxIssuable, ) = _maxIssuablePynths(_issuer);
return maxIssuable;
}
function externalTokenQuota(
address _account,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) external view returns (uint) {
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_account, pUSD);
_requireRatesNotInvalid(anyRateIsInvalid);
uint estimatedQuota =
exTokenStakeManager().externalTokenQuota(_account, debtBalance, _additionalpUSD, _additionalExToken, _isIssue);
return estimatedQuota;
}
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid)
{
// How many PERI do they have, excluding escrow?
// Note: We're excluding escrow here because we're interested in their transferable amount
// and escrowed PERI are not transferable.
// How many of those will be locked by the amount they've issued?
// Assuming issuance ratio is 20%, then issuing 20 PERI of value would require
// 100 PERI to be locked in their wallet to maintain their collateralisation ratio
// The locked periFinance value can exceed their balance.
(uint debtBalance, , bool rateIsInvalid) = _debtBalanceOfAndTotalDebt(account, PERI);
uint debtAppliedIssuanceRatio = debtBalance.divideDecimalRound(getIssuanceRatio());
uint externalTokenStaked = exTokenStakeManager().combinedStakedAmountOf(account, PERI);
// If external token staked balance is larger than required collateral amount for current debt,
// no PERI would be locked. (But it violates external token staking quota rule)
uint lockedPeriFinanceValue =
debtAppliedIssuanceRatio > externalTokenStaked ? debtAppliedIssuanceRatio.sub(externalTokenStaked) : 0;
// If we exceed the balance, no PERI are transferable, otherwise the difference is.
if (lockedPeriFinanceValue >= balance) {
transferable = 0;
} else {
transferable = balance.sub(lockedPeriFinanceValue);
}
anyRateIsInvalid = rateIsInvalid;
}
function amountsToFitClaimable(address _account) external view returns (uint burnAmount, uint exTokenAmountToUnstake) {
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_account, pUSD);
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_account, pUSD);
(uint periRate, bool isPeriInvalid) = exchangeRates().rateAndInvalid(PERI);
uint periCollateralToUSD = _periToUSD(_collateral(_account), periRate);
_requireRatesNotInvalid(anyRateIsInvalid || isPeriInvalid);
(burnAmount, exTokenAmountToUnstake) = _amountsToFitClaimable(
debtBalance,
combinedStakedAmount,
periCollateralToUSD
);
}
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory) {
uint numKeys = currencyKeys.length;
IPynth[] memory addresses = new IPynth[](numKeys);
for (uint i = 0; i < numKeys; i++) {
addresses[i] = pynths[currencyKeys[i]];
}
return addresses;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _addPynth(IPynth pynth) internal {
bytes32 currencyKey = pynth.currencyKey();
require(pynths[currencyKey] == IPynth(0), "Pynth exists");
require(pynthsByAddress[address(pynth)] == bytes32(0), "Pynth address already exists");
availablePynths.push(pynth);
pynths[currencyKey] = pynth;
pynthsByAddress[address(pynth)] = currencyKey;
emit PynthAdded(currencyKey, address(pynth));
}
function addPynth(IPynth pynth) external onlyOwner {
_addPynth(pynth);
// Invalidate the cache to force a snapshot to be recomputed. If a pynth were to be added
// back to the system and it still somehow had cached debt, this would force the value to be
// updated.
debtCache().updateDebtCacheValidity(true);
}
function addPynths(IPynth[] calldata pynthsToAdd) external onlyOwner {
uint numPynths = pynthsToAdd.length;
for (uint i = 0; i < numPynths; i++) {
_addPynth(pynthsToAdd[i]);
}
// Invalidate the cache to force a snapshot to be recomputed.
debtCache().updateDebtCacheValidity(true);
}
function _removePynth(bytes32 currencyKey) internal {
address pynthToRemove = address(pynths[currencyKey]);
require(pynthToRemove != address(0), "Pynth doesn't exist");
require(IERC20(pynthToRemove).totalSupply() == 0, "Pynth supply exists");
require(currencyKey != pUSD, "Cannot remove pynth");
// Remove the pynth from the availablePynths array.
for (uint i = 0; i < availablePynths.length; i++) {
if (address(availablePynths[i]) == pynthToRemove) {
delete availablePynths[i];
// Copy the last pynth into the place of the one we just deleted
// If there's only one pynth, this is pynths[0] = pynths[0].
// If we're deleting the last one, it's also a NOOP in the same way.
availablePynths[i] = availablePynths[availablePynths.length - 1];
// Decrease the size of the array by one.
availablePynths.length--;
break;
}
}
// And remove it from the pynths mapping
delete pynthsByAddress[pynthToRemove];
delete pynths[currencyKey];
emit PynthRemoved(currencyKey, pynthToRemove);
}
function removePynth(bytes32 currencyKey) external onlyOwner {
// Remove its contribution from the debt pool snapshot, and
// invalidate the cache to force a new snapshot.
IIssuerInternalDebtCache cache = debtCache();
cache.updateCachedPynthDebtWithRate(currencyKey, 0);
cache.updateDebtCacheValidity(true);
_removePynth(currencyKey);
}
function removePynths(bytes32[] calldata currencyKeys) external onlyOwner {
uint numKeys = currencyKeys.length;
// Remove their contributions from the debt pool snapshot, and
// invalidate the cache to force a new snapshot.
IIssuerInternalDebtCache cache = debtCache();
uint[] memory zeroRates = new uint[](numKeys);
cache.updateCachedPynthDebtsWithRates(currencyKeys, zeroRates);
cache.updateDebtCacheValidity(true);
for (uint i = 0; i < numKeys; i++) {
_removePynth(currencyKeys[i]);
}
}
function issuePynths(
address _issuer,
bytes32 _currencyKey,
uint _issueAmount
) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
if (_currencyKey != PERI) {
uint amountToStake = _issueAmount.divideDecimalRound(getIssuanceRatio());
(uint initialDebtOwnership, ) = periFinanceState().issuanceData(_issuer);
// Condition of policy, user must have any amount of PERI locked before staking external token.
require(initialDebtOwnership > 0, "User has no debt");
exTokenStakeManager().stake(_issuer, amountToStake, _currencyKey, pUSD);
}
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
uint afterDebtBalance = _issuePynths(_issuer, _issueAmount, maxIssuable, existingDebt, totalSystemDebt, false);
// For preventing additional gas consumption by calculating debt twice, the quota checker is placed here.
exTokenStakeManager().requireNotExceedsQuotaLimit(_issuer, afterDebtBalance, 0, 0, true);
}
function issueMaxPynths(address _issuer) external onlyPeriFinance {
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
_issuePynths(_issuer, 0, maxIssuable, existingDebt, totalSystemDebt, true);
}
function issuePynthsToMaxQuota(address _issuer, bytes32 _currencyKey) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
require(_currencyKey != PERI, "Only external token allowed to stake");
(uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) =
_remainingIssuablePynths(_issuer);
_requireRatesNotInvalid(anyRateIsInvalid);
require(existingDebt > 0, "User has no debt");
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_issuer, pUSD);
(uint issueAmountToQuota, uint stakeAmountToQuota) =
_maxExternalTokenStakeAmount(_issuer, existingDebt, combinedStakedAmount, _currencyKey);
require(issueAmountToQuota > 0 && stakeAmountToQuota > 0, "Not available to stake");
exTokenStakeManager().stake(_issuer, stakeAmountToQuota, _currencyKey, pUSD);
// maxIssuable should be increased for increased collateral
maxIssuable = maxIssuable.add(issueAmountToQuota);
uint afterDebtBalance = _issuePynths(_issuer, issueAmountToQuota, maxIssuable, existingDebt, totalSystemDebt, false);
// For preventing additional gas consumption by calculating debt twice, the quota checker is placed here.
exTokenStakeManager().requireNotExceedsQuotaLimit(_issuer, afterDebtBalance, 0, 0, true);
}
function burnPynths(
address _from,
bytes32 _currencyKey,
uint _burnAmount
) external onlyPeriFinance {
_requireCurrencyKeyIsNotpUSD(_currencyKey);
uint remainingDebt = _voluntaryBurnPynths(_from, _burnAmount, false, false);
if (_currencyKey == PERI) {
exTokenStakeManager().requireNotExceedsQuotaLimit(_from, remainingDebt, 0, 0, false);
} else {
exTokenStakeManager().unstake(_from, _burnAmount.divideDecimalRound(getIssuanceRatio()), _currencyKey, pUSD);
}
}
function fitToClaimable(address _from) external onlyPeriFinance {
(uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_from, pUSD);
uint combinedStakedAmount = exTokenStakeManager().combinedStakedAmountOf(_from, pUSD);
(uint periRate, bool isPeriInvalid) = exchangeRates().rateAndInvalid(PERI);
uint periCollateralToUSD = _periToUSD(_collateral(_from), periRate);
_requireRatesNotInvalid(anyRateIsInvalid || isPeriInvalid);
(uint burnAmount, uint amountToUnstake) =
_amountsToFitClaimable(debtBalance, combinedStakedAmount, periCollateralToUSD);
_voluntaryBurnPynths(_from, burnAmount, true, false);
exTokenStakeManager().unstakeMultipleTokens(_from, amountToUnstake, pUSD);
}
function exit(address _from) external onlyPeriFinance {
_voluntaryBurnPynths(_from, 0, true, true);
bytes32[] memory tokenList = exTokenStakeManager().getTokenList();
for (uint i = 0; i < tokenList.length; i++) {
uint stakedAmount = exTokenStakeManager().stakedAmountOf(_from, tokenList[i], tokenList[i]);
if (stakedAmount == 0) {
continue;
}
exTokenStakeManager().unstake(_from, stakedAmount, tokenList[i], tokenList[i]);
}
}
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external onlyPeriFinance returns (uint totalRedeemed, uint amountToLiquidate) {
// Ensure waitingPeriod and pUSD balance is settled as burning impacts the size of debt pool
require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, pUSD), "pUSD needs to be settled");
// Check account is liquidation open
require(liquidations().isOpenForLiquidation(account), "Account not open for liquidation");
// require liquidator has enough pUSD
require(IERC20(address(pynths[pUSD])).balanceOf(liquidator) >= pusdAmount, "Not enough pUSD");
uint liquidationPenalty = liquidations().liquidationPenalty();
// What is their debt in pUSD?
(uint debtBalance, uint totalDebtIssued, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, pUSD);
(uint periRate, bool periRateInvalid) = exchangeRates().rateAndInvalid(PERI);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
uint collateralForAccount = _collateral(account);
uint amountToFixRatio =
liquidations().calculateAmountToFixCollateral(debtBalance, _periToUSD(collateralForAccount, periRate));
// Cap amount to liquidate to repair collateral ratio based on issuance ratio
amountToLiquidate = amountToFixRatio < pusdAmount ? amountToFixRatio : pusdAmount;
// what's the equivalent amount of peri for the amountToLiquidate?
uint periRedeemed = _usdToPeri(amountToLiquidate, periRate);
// Add penalty
totalRedeemed = periRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty));
// if total PERI to redeem is greater than account's collateral
// account is under collateralised, liquidate all collateral and reduce pUSD to burn
if (totalRedeemed > collateralForAccount) {
// set totalRedeemed to all transferable collateral
totalRedeemed = collateralForAccount;
// whats the equivalent pUSD to burn for all collateral less penalty
amountToLiquidate = _periToUSD(
collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)),
periRate
);
}
// burn pUSD from messageSender (liquidator) and reduce account's debt
_burnPynths(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued);
// Remove liquidation flag if amount liquidated fixes ratio
if (amountToLiquidate == amountToFixRatio) {
// Remove liquidation
liquidations().removeAccountInLiquidation(account);
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _requireRatesNotInvalid(bool anyRateIsInvalid) internal pure {
require(!anyRateIsInvalid, "A pynth or PERI rate is invalid");
}
function _requireCanIssueOnBehalf(address issueForAddress, address from) internal view {
require(delegateApprovals().canIssueFor(issueForAddress, from), "Not approved to act on behalf");
}
function _requireCanBurnOnBehalf(address burnForAddress, address from) internal view {
require(delegateApprovals().canBurnFor(burnForAddress, from), "Not approved to act on behalf");
}
function _requireCurrencyKeyIsNotpUSD(bytes32 _currencyKey) internal pure {
require(_currencyKey != pUSD, "pUSD isn't stakable");
}
function _issuePynths(
address from,
uint amount,
uint maxIssuable,
uint existingDebt,
uint totalSystemDebt,
bool issueMax
) internal returns (uint afterDebt) {
if (!issueMax) {
require(amount <= maxIssuable, "Amount too large");
} else {
amount = maxIssuable;
}
// Keep track of the debt they're about to create
_addToDebtRegister(from, amount, existingDebt, totalSystemDebt);
// record issue timestamp
_setLastIssueEvent(from);
// Create their pynths
pynths[pUSD].issue(from, amount);
// Account for the issued debt in the cache
debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit());
// Store their locked PERI amount to determine their fee % for the period
_appendAccountIssuanceRecord(from);
afterDebt = existingDebt.add(amount);
}
function _burnPynths(
address debtAccount,
address burnAccount,
uint amountBurnt,
uint existingDebt,
uint totalDebtIssued
) internal returns (uint) {
// liquidation requires pUSD to be already settled / not in waiting period
require(amountBurnt <= existingDebt, "Trying to burn more than debt");
// Remove liquidated debt from the ledger
_removeFromDebtRegister(debtAccount, amountBurnt, existingDebt, totalDebtIssued);
uint pUSDBalance = IERC20(address(pynths[pUSD])).balanceOf(burnAccount);
uint deviation = pUSDBalance < amountBurnt ? amountBurnt.sub(pUSDBalance) : pUSDBalance.sub(amountBurnt);
amountBurnt = deviation < 10 ? pUSDBalance : amountBurnt;
// pynth.burn does a safe subtraction on balance (so it will revert if there are not enough pynths).
pynths[pUSD].burn(burnAccount, amountBurnt);
// Account for the burnt debt in the cache.
debtCache().updateCachedPynthDebtWithRate(pUSD, SafeDecimalMath.unit());
// Store their debtRatio against a fee period to determine their fee/rewards % for the period
_appendAccountIssuanceRecord(debtAccount);
return amountBurnt;
}
// If burning to target, `amount` is ignored, and the correct quantity of pUSD is burnt to reach the target
// c-ratio, allowing fees to be claimed. In this case, pending settlements will be skipped as the user
// will still have debt remaining after reaching their target.
function _voluntaryBurnPynths(
address from,
uint amount,
bool burnToTarget,
bool burnMax
) internal returns (uint remainingDebt) {
if (!burnToTarget) {
// If not burning to target, then burning requires that the minimum stake time has elapsed.
require(_canBurnPynths(from), "Minimum stake time not reached");
// First settle anything pending into pUSD as burning or issuing impacts the size of the debt pool
(, uint refunded, uint numEntriesSettled) = exchanger().settle(from, pUSD);
if (numEntriesSettled > 0) {
amount = exchanger().calculateAmountAfterSettlement(from, pUSD, amount, refunded);
}
}
(uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, pUSD);
(uint maxIssuablePynthsForAccount, bool periRateInvalid) = _maxIssuablePynths(from);
_requireRatesNotInvalid(anyRateIsInvalid || periRateInvalid);
require(existingDebt > 0, "No debt to forgive");
if (burnMax) {
amount = existingDebt;
}
uint amountBurnt = _burnPynths(from, from, amount, existingDebt, totalSystemValue);
remainingDebt = existingDebt.sub(amount);
// Check and remove liquidation if existingDebt after burning is <= maxIssuablePynths
// Issuance ratio is fixed so should remove any liquidations
if (existingDebt >= amountBurnt && remainingDebt <= maxIssuablePynthsForAccount) {
liquidations().removeAccountInLiquidation(from);
}
}
function _setLastIssueEvent(address account) internal {
// Set the timestamp of the last issuePynths
flexibleStorage().setUIntValue(
CONTRACT_NAME,
keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)),
block.timestamp
);
}
function _appendAccountIssuanceRecord(address from) internal {
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = periFinanceState().issuanceData(from);
feePool().appendAccountIssuanceRecord(from, initialDebtOwnership, debtEntryIndex);
}
function _addToDebtRegister(
address from,
uint amount,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
// What will the new total be including the new value?
uint newTotalDebtIssued = amount.add(totalDebtIssued);
// What is their percentage (as a high precision int) of the total debt?
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
// And what effect does this percentage change have on the global debt holding of other issuers?
// The delta specifically needs to not take into account any existing debt as it's already
// accounted for in the delta from when they issued previously.
// The delta is a high precision integer.
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
// And what does their debt ownership look like including this previous stake?
if (existingDebt > 0) {
debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
} else {
// If they have no debt, they're a new issuer; record this.
state.incrementTotalIssuerCount();
}
// Save the debt entry parameters
state.setCurrentIssuanceData(from, debtPercentage);
crossChainManager().addTotalNetworkDebt(amount);
// Save the total debt entry parameters
crossChainManager().setCrossNetworkUserDebt(from, state.debtLedgerLength());
// And if we're the first, push 1 as there was no effect to any other holders, otherwise push
// the change for the rest of the debt holders. The debt ledger holds high precision integers.
if (state.debtLedgerLength() > 0 && state.lastDebtLedgerEntry() != 0) {
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
} else {
state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
function _removeFromDebtRegister(
address from,
uint debtToRemove,
uint existingDebt,
uint totalDebtIssued
) internal {
IPeriFinanceState state = periFinanceState();
// What will the new total after taking out the withdrawn amount
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint delta = 0;
// What will the debt delta be if there is any debt left?
// Set delta to 0 if no more debt left in system after user
if (newTotalDebtIssued > 0) {
// What is the percentage of the withdrawn debt (as a high precision int) of the total debt after?
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued);
// And what effect does this percentage change have on the global debt holding of other issuers?
// The delta specifically needs to not take into account any existing debt as it's already
// accounted for in the delta from when they issued previously.
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
}
// Are they exiting the system, or are they just decreasing their debt position?
if (debtToRemove == existingDebt) {
state.setCurrentIssuanceData(from, 0);
state.decrementTotalIssuerCount();
crossChainManager().clearCrossNetworkUserDebt(from);
} else {
// What percentage of the debt will they be left with?
uint newDebt = existingDebt.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
// Store the debt percentage and debt ledger as high precision integers
state.setCurrentIssuanceData(from, newDebtPercentage);
crossChainManager().setCrossNetworkUserDebt(from, state.debtLedgerLength());
}
crossChainManager().subtractTotalNetworkDebt(debtToRemove);
// Update our cumulative ledger. This is also a high precision integer.
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
}
/* ========== MODIFIERS ========== */
function _onlyPeriFinance() internal view {
require(msg.sender == address(periFinance()), "Issuer: Only the periFinance contract can perform this action");
}
modifier onlyPeriFinance() {
_onlyPeriFinance(); // Use an internal function to save code size.
_;
}
/* ========== EVENTS ========== */
event PynthAdded(bytes32 currencyKey, address pynth);
event PynthRemoved(bytes32 currencyKey, address pynth);
}
| ========== VIEWS ========== / | function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](15);
newAddresses[0] = CONTRACT_PERIFINANCE;
newAddresses[1] = CONTRACT_EXCHANGER;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_PERIFINANCESTATE;
newAddresses[4] = CONTRACT_FEEPOOL;
newAddresses[5] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[6] = CONTRACT_ETHERCOLLATERAL;
newAddresses[7] = CONTRACT_ETHERCOLLATERAL_PUSD;
newAddresses[8] = CONTRACT_REWARDESCROW_V2;
newAddresses[9] = CONTRACT_PERIFINANCEESCROW;
newAddresses[10] = CONTRACT_LIQUIDATIONS;
newAddresses[11] = CONTRACT_DEBTCACHE;
newAddresses[12] = CONTRACT_COLLATERALMANAGER;
newAddresses[13] = CONTRACT_EXTOKENSTAKEMANAGER;
newAddresses[14] = CONTRACT_CROSSCHAINMANAGER;
return combineArrays(existingAddresses, newAddresses);
}
| 12,654,232 |
./full_match/5/0x8792C8f923454196539AB9D7Fa97F69951AC7278/sources/contracts/6/forwarder/BiconomyForwarder.sol | verifies the domain separator used has been registered via registerDomainSeparator() recreates the 32 byte hash signed by the user's wallet (as per EIP712 specifications) verifies the signature using Open Zeppelin's ECDSA library signature valid if call doesn't throw req : request being executed domainSeparator : the domain separator presented to the user when signing sig : the signature generated by the user's wallet/ solhint-disable-next-line no-inline-assembly / | function _verifySigEIP712(
ERC20ForwardRequest calldata req,
bytes32 domainSeparator,
bytes memory sig)
internal
view
{
uint256 id;
assembly {
id := chainid()
}
require(req.deadline == 0 || block.timestamp + 20 <= req.deadline, "request expired");
require(domains[domainSeparator], "unregistered domain separator");
require(chainId == id, "potential replay attack on the fork");
bytes32 digest =
keccak256(abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(abi.encode(REQUEST_TYPEHASH,
req.from,
req.to,
req.token,
req.txGas,
req.tokenGasPrice,
req.batchId,
nonces[req.from][req.batchId],
req.deadline,
keccak256(req.data)
))));
require(digest.recover(sig) == req.from, "signature mismatch");
}
| 7,037,293 |
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() 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);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyNewOwner {
require(msg.sender == newOwner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public onlyNewOwner {
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
function disown() public onlyOwner {
owner = address(0);
newOwner = msg.sender;
emit OwnershipTransferred(msg.sender, address(0));
}
function rejectOwnership() public onlyNewOwner {
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
//
// Symbol : Chowe
// Name : Chowe Fermi-Dirac Token
// Total supply: 1
// Decimals : 0
//
// Share. Enjoy.
//
// (c) by Chris Howe 2018. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract ChoweToken is ERC20Interface, Owned {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Chowe";
name = "Chowe Fermi-Dirac Token";
decimals = 0;
_totalSupply = 1;
balances[msg.sender] = 1;
balances[address(0)] = 0;
emit Transfer(address(0), msg.sender, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
require(balances[to]==0 && tokens==1);
if (msg.sender != owner) {
require(balances[msg.sender] > 0);
balances[msg.sender] = balances[msg.sender] - 1;
} else {
_totalSupply = _totalSupply + 1;
}
if (to != address(0)) {
balances[to] = 1;
} else {
_totalSupply = _totalSupply-1;
}
emit Transfer(msg.sender, to, 1);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(balances[to]==0 && tokens==1);
if (from != owner) {
require(balances[from]>0);
balances[from] = balances[from] - 1;
} else {
_totalSupply = _totalSupply + 1;
}
require(allowed[from][msg.sender]>0);
allowed[from][msg.sender] = allowed[from][msg.sender] - 1;
if (to != address(0)) {
balances[to] = 1;
} else {
_totalSupply = _totalSupply + 1;
}
emit Transfer(from, to, 1);
return true;
}
// ------------------------------------------------------------------------
// This override of the Owned contract ensures that the new owner of the
// contract has a token
// ------------------------------------------------------------------------
function acceptOwnership() public {
address oldOwner = owner;
super.acceptOwnership();
// The owner MUST have a token, so create one if needed
if( balances[msg.sender] == 0) {
balances[msg.sender] = 1;
_totalSupply = _totalSupply + 1;
emit Transfer(oldOwner, msg.sender, 1);
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ------------------------------------------------------------------------ Total supply ------------------------------------------------------------------------ | function totalSupply() public view returns (uint) {
return _totalSupply;
}
| 14,990,277 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {
AccessControlUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {SafeERC20} from "../libs/SafeERC20.sol";
import {PRBMathUD60x18} from "prb-math/contracts/PRBMathUD60x18.sol";
/**
@title Staked MPH
@author Zefram Lou
@notice The MPH staking contract
*/
contract xMPH is ERC20Upgradeable, AccessControlUpgradeable {
using SafeERC20 for ERC20;
using PRBMathUD60x18 for uint256;
uint256 internal constant PRECISION = 10**18;
uint256 internal constant MAX_REWARD_UNLOCK_PERIOD = 365 days;
bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE");
uint256 public constant MIN_AMOUNT = 10**9;
ERC20 public mph;
uint256 public rewardUnlockPeriod;
uint256 public currentUnlockEndTimestamp;
uint256 public lastRewardTimestamp;
uint256 public lastRewardAmount;
event DistributeReward(uint256 rewardAmount);
function __xMPH_init(
address _mph,
uint256 _rewardUnlockPeriod,
address _distributor
) internal initializer {
__ERC20_init("Staked MPH", "xMPH");
__AccessControl_init();
__xMPH_init_unchained(_mph, _rewardUnlockPeriod, _distributor);
}
function __xMPH_init_unchained(
address _mph,
uint256 _rewardUnlockPeriod,
address _distributor
) internal initializer {
// Validate input
require(
_mph != address(0) && _distributor != address(0),
"xMPH: 0 address"
);
require(
_rewardUnlockPeriod > 0 &&
_rewardUnlockPeriod <= MAX_REWARD_UNLOCK_PERIOD,
"xMPH: invalid _rewardUnlockPeriod"
);
// _distributor and msg.sender are given DISTRIBUTOR_ROLE
// DISTRIBUTOR_ROLE is managed by itself
// msg.sender is given DEFAULT_ADMIN_ROLE which enables
// calling setRewardUnlockPeriod()
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(DISTRIBUTOR_ROLE, msg.sender);
_setupRole(DISTRIBUTOR_ROLE, _distributor);
_setRoleAdmin(DISTRIBUTOR_ROLE, DISTRIBUTOR_ROLE);
mph = ERC20(_mph);
rewardUnlockPeriod = _rewardUnlockPeriod;
// force the deployer to deposit to prevent rounding schenanigans
_deposit(MIN_AMOUNT);
}
/**
@param _mph The MPH token
@param _rewardUnlockPeriod The length of each reward distribution period, in seconds
@param _distributor The account that will call distributeReward()
*/
function initialize(
address _mph,
uint256 _rewardUnlockPeriod,
address _distributor
) external initializer {
__xMPH_init(_mph, _rewardUnlockPeriod, _distributor);
}
/**
@notice Deposit MPH to get xMPH
@dev The amount can't be 0
@param _mphAmount The amount of MPH to deposit
@return shareAmount The amount of xMPH minted
*/
function deposit(uint256 _mphAmount)
external
virtual
returns (uint256 shareAmount)
{
return _deposit(_mphAmount);
}
/**
@notice Withdraw MPH using xMPH
@dev The amount can't be 0
@param _shareAmount The amount of xMPH to burn
@return mphAmount The amount of MPH withdrawn
*/
function withdraw(uint256 _shareAmount)
external
virtual
returns (uint256 mphAmount)
{
return _withdraw(_shareAmount);
}
/**
@notice Compute the amount of MPH that can be withdrawn by burning
1 xMPH. Increases linearly during a reward distribution period.
@dev Initialized to be PRECISION (representing 1 MPH = 1 xMPH)
@return The amount of MPH that can be withdrawn by burning
1 xMPH
*/
function getPricePerFullShare() public view returns (uint256) {
uint256 totalShares = totalSupply();
uint256 mphBalance = mph.balanceOf(address(this));
if (totalShares == 0 || mphBalance == 0) {
return PRECISION;
}
uint256 _lastRewardAmount = lastRewardAmount;
uint256 _currentUnlockEndTimestamp = currentUnlockEndTimestamp;
if (
_lastRewardAmount == 0 ||
block.timestamp >= _currentUnlockEndTimestamp
) {
// no rewards or rewards fully unlocked
// entire balance is withdrawable
return mphBalance.div(totalShares);
} else {
// rewards not fully unlocked
// deduct locked rewards from balance
uint256 _lastRewardTimestamp = lastRewardTimestamp;
uint256 lockedRewardAmount =
(_lastRewardAmount *
(_currentUnlockEndTimestamp - block.timestamp)) /
(_currentUnlockEndTimestamp - _lastRewardTimestamp);
return (mphBalance - lockedRewardAmount).div(totalShares);
}
}
/**
@notice Distributes MPH rewards to xMPH holders
@dev When not in a distribution period, start a new one with rewardUnlockPeriod seconds.
When in a distribution period, add rewards to current period
*/
function distributeReward(uint256 rewardAmount) external virtual {
_distributeReward(rewardAmount);
}
function setRewardUnlockPeriod(uint256 newValue) external {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "xMPH: not admin");
require(
newValue > 0 && newValue <= MAX_REWARD_UNLOCK_PERIOD,
"xMPH: invalid value"
);
rewardUnlockPeriod = newValue;
}
/**
@dev See {deposit}
*/
function _deposit(uint256 _mphAmount)
internal
virtual
returns (uint256 shareAmount)
{
require(_mphAmount > 0, "xMPH: amount");
shareAmount = _mphAmount.div(getPricePerFullShare());
_mint(msg.sender, shareAmount);
mph.safeTransferFrom(msg.sender, address(this), _mphAmount);
}
/**
@dev See {withdraw}
*/
function _withdraw(uint256 _shareAmount)
internal
virtual
returns (uint256 mphAmount)
{
require(
totalSupply() >= _shareAmount + MIN_AMOUNT && _shareAmount > 0,
"xMPH: amount"
);
mphAmount = _shareAmount.mul(getPricePerFullShare());
_burn(msg.sender, _shareAmount);
mph.safeTransfer(msg.sender, mphAmount);
}
/**
@dev See {distributeReward}
*/
function _distributeReward(uint256 rewardAmount) internal {
require(totalSupply() >= MIN_AMOUNT, "xMPH: supply");
require(rewardAmount >= MIN_AMOUNT, "xMPH: reward");
require(
rewardAmount < type(uint256).max / PRECISION,
"xMPH: rewards too large, would lock"
);
require(hasRole(DISTRIBUTOR_ROLE, msg.sender), "xMPH: not distributor");
// transfer rewards from sender
mph.safeTransferFrom(msg.sender, address(this), rewardAmount);
if (block.timestamp >= currentUnlockEndTimestamp) {
// start new reward period
currentUnlockEndTimestamp = block.timestamp + rewardUnlockPeriod;
lastRewardTimestamp = block.timestamp;
lastRewardAmount = rewardAmount;
} else {
// add rewards to current reward period
uint256 lockedRewardAmount =
(lastRewardAmount *
(currentUnlockEndTimestamp - block.timestamp)) /
(currentUnlockEndTimestamp - lastRewardTimestamp);
lastRewardTimestamp = block.timestamp;
lastRewardAmount = rewardAmount + lockedRewardAmount;
}
emit DistributeReward(rewardAmount);
}
uint256[45] private __gap;
}
| Validate input _distributor and msg.sender are given DISTRIBUTOR_ROLE DISTRIBUTOR_ROLE is managed by itself msg.sender is given DEFAULT_ADMIN_ROLE which enables calling setRewardUnlockPeriod() force the deployer to deposit to prevent rounding schenanigans | function __xMPH_init_unchained(
address _mph,
uint256 _rewardUnlockPeriod,
address _distributor
) internal initializer {
require(
_mph != address(0) && _distributor != address(0),
"xMPH: 0 address"
);
require(
_rewardUnlockPeriod > 0 &&
_rewardUnlockPeriod <= MAX_REWARD_UNLOCK_PERIOD,
"xMPH: invalid _rewardUnlockPeriod"
);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(DISTRIBUTOR_ROLE, msg.sender);
_setupRole(DISTRIBUTOR_ROLE, _distributor);
_setRoleAdmin(DISTRIBUTOR_ROLE, DISTRIBUTOR_ROLE);
mph = ERC20(_mph);
rewardUnlockPeriod = _rewardUnlockPeriod;
_deposit(MIN_AMOUNT);
}
@param _rewardUnlockPeriod The length of each reward distribution period, in seconds
@param _distributor The account that will call distributeReward()
| 15,791,759 |
pragma solidity ^0.5.0;
import "./StoreManagersInterface.sol";
contract Stores {
address owner;
address funds;
struct StoreItem {
string image;
string title;
uint256 price;
uint16 quantity;
bool available;
bool exist;
}
struct Store {
string name;
bool active;
uint256 balance;
uint64[] itemCodes;
bool exist;
}
uint16[] storeCodes;
mapping(uint16 => Store) public stores;
mapping(uint16 => mapping(uint64 => StoreItem)) public storeItems;
StoreManagersInterface storeManagers;
address storeManagersAddress;
// get the deployed address for StoreManagers contract
constructor(address storeManagersContractAddress) public {
owner = msg.sender;
/*
check that address is not zero, this is a check for a valid address
since by default it will be zero if not assigned.
*/
require(storeManagersContractAddress != address(0));
storeManagersAddress = storeManagersContractAddress;
/*
assign it to the interface so that it's easier to determine what calls can be done
to that contract.
*/
storeManagers = StoreManagersInterface(storeManagersContractAddress);
}
modifier restricted() {
// calls the store manager to check if the sender is a store manager.
require(storeManagers.isActiveStoreManager(msg.sender)); _;
}
modifier ownerRestricted() {
require(owner == msg.sender); _;
}
function getAllStoreCodes() public view returns (uint16[] memory) {
return storeCodes;
}
function getAllItemCodes(uint16 storeCode) public view returns (uint64[] memory) {
return stores[storeCode].itemCodes;
}
function add(
uint16 storeCode,
string memory name,
bool active,
uint256 balance
) restricted public payable {
// check that received values are correct.
require(storeCode >= 0);
require(!stores[storeCode].exist, "item with this code already exists");
// checks that the name is not empty
require(bytes(name).length > 0, "name should not be left empty");
require(balance >= 0, "balance should be greater than 0");
// add store codes to array, and add mapping with that storecode.
storeCodes.push(storeCode);
stores[storeCode].name = name;
stores[storeCode].active = active;
stores[storeCode].balance = balance;
stores[storeCode].exist = true;
}
function update(
uint16 storeCode,
string memory name,
bool active,
uint256 balance
) restricted public payable {
require(storeCode >= 0);
require(stores[storeCode].exist, "item should already be available");
require(bytes(name).length > 0, "image should not be left empty");
require(balance >= 0, "balance should be greater than 0");
stores[storeCode].name = name;
stores[storeCode].active = active;
stores[storeCode].balance = balance;
}
function addItem(
uint16 storeCode,
uint64 code,
string memory image,
string memory title,
uint256 price,
uint16 quantity,
bool available
) restricted public payable {
// checks that the data passed is correct
require(storeCode >= 0);
require(code >= 0);
require(!storeItems[storeCode][code].exist, "item with this code already exists");
require(bytes(image).length > 0, "image should not be left empty");
require(bytes(title).length > 0, "title should not be left empty");
require(price >= 0, "price should be 0 or more");
require(quantity >= 0, "quantity should be 0 or more");
// add store item to item codes in the store mapping
stores[storeCode].itemCodes.push(code);
// add item to the store items mapping.
storeItems[storeCode][code].image = image;
storeItems[storeCode][code].title = title;
storeItems[storeCode][code].price = price;
storeItems[storeCode][code].quantity = quantity;
storeItems[storeCode][code].available = available;
storeItems[storeCode][code].exist = true;
}
function updateItem(
uint16 storeCode,
uint64 code,
string memory image,
string memory title,
uint256 price,
uint16 quantity,
bool available
) restricted public payable {
require(code >= 0, "code should be greated than 0");
require(storeItems[storeCode][code].exist, "item with this code should already exist to update");
require(bytes(image).length > 0, "image should not be left empty");
require(bytes(title).length > 0, "title should not be left empty");
require(price >= 0, "price should be 0 or more");
require(quantity >= 0, "quantity should be 0 or more");
// get the values and update
storeItems[storeCode][code].image = image;
storeItems[storeCode][code].title = title;
storeItems[storeCode][code].price = price;
storeItems[storeCode][code].quantity = quantity;
// sets to available false if quantity is zero.
if(quantity == 0){
available = false;
}
storeItems[storeCode][code].available = available;
}
function getBalance() ownerRestricted public view returns (uint256) {
return address(this).balance;
}
function buyItem(
uint16 storeCode,
uint64 code,
uint16 quantity
) public payable {
require(storeCode >= 0, "storeCode should be greated than 0");
require(code >= 0, "code should be greated than 0");
require(quantity >= 0, "quantity should be 0 or more");
require(storeItems[storeCode][code].available == true, "item should be available");
require(storeItems[storeCode][code].exist, "item with this code should already exist to update");
require(storeItems[storeCode][code].quantity >= quantity, "stock quantity should be more");
/*
first withdraw the funds, then reduce quantity from store.
This is import due to reentrancy issues.
*/
withdrawFunds(storeCode, code, quantity);
storeItems[storeCode][code].quantity = storeItems[storeCode][code].quantity - quantity;
// checks if quantity is zero and changes item status to not available.
if(storeItems[storeCode][code].quantity == 0){
storeItems[storeCode][code].available = false;
}
}
function withdrawFunds(
uint16 storeCode,
uint64 code,
uint16 quantity
) private {
// calculates the outstanding balance, to be check with the passed value.
uint256 outstandingBalance = storeItems[storeCode][code].price * quantity;
require(msg.sender.balance >= outstandingBalance, "Not enough balance!");
require(outstandingBalance == msg.value, "Oustanding balance does not match");
// transfer the money to the contract.
msg.sender.transfer(msg.value);
// add balance to the store.
stores[storeCode].balance += msg.value;
}
// function to be called by the owner to transfer funds before deploying a new contract
function destroy() ownerRestricted public {
selfdestruct(address(uint160(owner)));
}
function() external payable {
revert();
}
} | calculates the outstanding balance, to be check with the passed value. transfer the money to the contract. add balance to the store. | function withdrawFunds(
uint16 storeCode,
uint64 code,
uint16 quantity
) private {
uint256 outstandingBalance = storeItems[storeCode][code].price * quantity;
require(msg.sender.balance >= outstandingBalance, "Not enough balance!");
require(outstandingBalance == msg.value, "Oustanding balance does not match");
msg.sender.transfer(msg.value);
stores[storeCode].balance += msg.value;
}
| 13,075,237 |
pragma solidity ^0.6.2;
import "./ERC777GSN.sol";
import "./ERC777WithAdminOperatorUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
contract PToken is
Initializable,
AccessControlUpgradeable,
ERC777GSNUpgradeable,
ERC777WithAdminOperatorUpgradeable
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes4 public ORIGIN_CHAIN_ID;
event Redeem(
address indexed redeemer,
uint256 value,
string underlyingAssetRecipient,
bytes userData,
bytes4 originChainId,
bytes4 destinationChainId
);
function initialize(
string memory tokenName,
string memory tokenSymbol,
address defaultAdmin,
bytes4 originChainId
)
public initializer
{
address[] memory defaultOperators;
__AccessControl_init();
__ERC777_init(tokenName, tokenSymbol, defaultOperators);
__ERC777GSNUpgradeable_init(defaultAdmin, defaultAdmin);
__ERC777WithAdminOperatorUpgradeable_init(defaultAdmin);
_setupRole(DEFAULT_ADMIN_ROLE, defaultAdmin);
ORIGIN_CHAIN_ID = originChainId;
}
modifier onlyMinter {
require(hasRole(MINTER_ROLE, _msgSender()), "Caller is not a minter");
_;
}
modifier onlyAdmin {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller is not an admin");
_;
}
function mint(
address recipient,
uint256 value
)
external
returns (bool)
{
mint(recipient, value, "", "");
return true;
}
function mint(
address recipient,
uint256 value,
bytes memory userData,
bytes memory operatorData
)
public
onlyMinter
returns (bool)
{
require(
recipient != address(this) ,
"Recipient cannot be the token contract address!"
);
_mint(recipient, value, userData, operatorData);
return true;
}
function redeem(
uint256 amount,
string calldata underlyingAssetRecipient,
bytes4 destinationChainId
)
external
returns (bool)
{
redeem(amount, "", underlyingAssetRecipient, destinationChainId);
return true;
}
function redeem(
uint256 amount,
bytes memory userData,
string memory underlyingAssetRecipient,
bytes4 destinationChainId
)
public
{
_burn(_msgSender(), amount, userData, "");
emit Redeem(
_msgSender(),
amount,
underlyingAssetRecipient,
userData,
ORIGIN_CHAIN_ID,
destinationChainId
);
}
function operatorRedeem(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData,
string calldata underlyingAssetRecipient,
bytes4 destinationChainId
)
external
{
require(
isOperatorFor(_msgSender(), account),
"ERC777: caller is not an operator for holder"
);
_burn(account, amount, userData, operatorData);
emit Redeem(account, amount, underlyingAssetRecipient, userData, ORIGIN_CHAIN_ID, destinationChainId);
}
function grantMinterRole(address _account) external {
grantRole(MINTER_ROLE, _account);
}
function revokeMinterRole(address _account) external {
revokeRole(MINTER_ROLE, _account);
}
function hasMinterRole(address _account) external view returns (bool) {
return hasRole(MINTER_ROLE, _account);
}
function _msgSender()
internal
view
override(ContextUpgradeable, ERC777GSNUpgradeable)
returns (address payable)
{
return GSNRecipientUpgradeable._msgSender();
}
function _msgData()
internal
view
override(ContextUpgradeable, ERC777GSNUpgradeable)
returns (bytes memory)
{
return GSNRecipientUpgradeable._msgData();
}
function changeOriginChainId(
bytes4 _newOriginChainId
)
public
onlyAdmin
returns (bool success)
{
ORIGIN_CHAIN_ID = _newOriginChainId;
return true;
}
}
pragma solidity ^0.6.2;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/GSN/GSNRecipientUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC777/ERC777Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract ERC777GSNUpgradeable is Initializable, OwnableUpgradeable, GSNRecipientUpgradeable, ERC777Upgradeable {
using ECDSAUpgradeable for bytes32;
uint256 constant GSN_RATE_UNIT = 10**18;
enum GSNErrorCodes {
INVALID_SIGNER,
INSUFFICIENT_BALANCE
}
address public gsnTrustedSigner;
address public gsnFeeTarget;
uint256 public gsnExtraGas; // the gas cost of _postRelayedCall()
function __ERC777GSNUpgradeable_init(
address _gsnTrustedSigner,
address _gsnFeeTarget
)
public
initializer
{
__GSNRecipient_init();
__Ownable_init();
require(_gsnTrustedSigner != address(0), "trusted signer is the zero address");
gsnTrustedSigner = _gsnTrustedSigner;
require(_gsnFeeTarget != address(0), "fee target is the zero address");
gsnFeeTarget = _gsnFeeTarget;
gsnExtraGas = 40000;
}
function _msgSender() internal view virtual override(ContextUpgradeable, GSNRecipientUpgradeable) returns (address payable) {
return GSNRecipientUpgradeable._msgSender();
}
function _msgData() internal view virtual override(ContextUpgradeable, GSNRecipientUpgradeable) returns (bytes memory) {
return GSNRecipientUpgradeable._msgData();
}
function setTrustedSigner(address _gsnTrustedSigner) public onlyOwner {
require(_gsnTrustedSigner != address(0), "trusted signer is the zero address");
gsnTrustedSigner = _gsnTrustedSigner;
}
function setFeeTarget(address _gsnFeeTarget) public onlyOwner {
require(_gsnFeeTarget != address(0), "fee target is the zero address");
gsnFeeTarget = _gsnFeeTarget;
}
function setGSNExtraGas(uint _gsnExtraGas) public onlyOwner {
gsnExtraGas = _gsnExtraGas;
}
/**
* @dev Ensures that only transactions with a trusted signature can be relayed through the GSN.
*/
function acceptRelayedCall(
address relay,
address from,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory approvalData,
uint256 /* maxPossibleCharge */
)
override
public
view
returns (uint256, bytes memory)
{
(uint256 feeRate, bytes memory signature) = abi.decode(approvalData, (uint, bytes));
bytes memory blob = abi.encodePacked(
feeRate,
relay,
from,
encodedFunction,
transactionFee,
gasPrice,
gasLimit,
nonce, // Prevents replays on RelayHub
getHubAddr(), // Prevents replays in multiple RelayHubs
address(this) // Prevents replays in multiple recipients
);
if (keccak256(blob).toEthSignedMessageHash().recover(signature) == gsnTrustedSigner) {
return _approveRelayedCall(abi.encode(feeRate, from, transactionFee, gasPrice));
} else {
return _rejectRelayedCall(uint256(GSNErrorCodes.INVALID_SIGNER));
}
}
function _preRelayedCall(bytes memory context) override internal returns (bytes32) {}
function _postRelayedCall(bytes memory context, bool, uint256 actualCharge, bytes32) override internal {
(uint256 feeRate, address from, uint256 transactionFee, uint256 gasPrice) =
abi.decode(context, (uint256, address, uint256, uint256));
// actualCharge is an _estimated_ charge, which assumes postRelayedCall will use all available gas.
// This implementation's gas cost can be roughly estimated as 10k gas, for the two SSTORE operations in an
// ERC20 transfer.
uint256 overestimation = _computeCharge(_POST_RELAYED_CALL_MAX_GAS.sub(gsnExtraGas), gasPrice, transactionFee);
uint fee = actualCharge.sub(overestimation).mul(feeRate).div(GSN_RATE_UNIT);
if (fee > 0) {
_send(from, gsnFeeTarget, fee, "", "", false);
}
}
}
pragma solidity ^0.6.2;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC777/ERC777Upgradeable.sol";
contract ERC777WithAdminOperatorUpgradeable is Initializable, ERC777Upgradeable {
address public adminOperator;
event AdminOperatorChange(address oldOperator, address newOperator);
event AdminTransferInvoked(address operator);
function __ERC777WithAdminOperatorUpgradeable_init(
address _adminOperator
) public
initializer {
adminOperator = _adminOperator;
}
/**
* @dev Similar to {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function adminTransfer(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
public
{
require(_msgSender() == adminOperator, "caller is not the admin operator");
_send(sender, recipient, amount, data, operatorData, false);
emit AdminTransferInvoked(adminOperator);
}
/**
* @dev Only the actual admin operator can change the address
*/
function setAdminOperator(address adminOperator_) public {
require(_msgSender() == adminOperator, "Only the actual admin operator can change the address");
emit AdminOperatorChange(adminOperator, adminOperator_);
adminOperator = adminOperator_;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "./IRelayRecipientUpgradeable.sol";
import "./IRelayHubUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Base GSN recipient contract: includes the {IRelayRecipient} interface
* and enables GSN support on all contracts in the inheritance tree.
*
* TIP: This contract is abstract. The functions {IRelayRecipient-acceptRelayedCall},
* {_preRelayedCall}, and {_postRelayedCall} are not implemented and must be
* provided by derived contracts. See the
* xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategies] for more
* information on how to use the pre-built {GSNRecipientSignature} and
* {GSNRecipientERC20Fee}, or how to write your own.
*/
abstract contract GSNRecipientUpgradeable is Initializable, IRelayRecipientUpgradeable, ContextUpgradeable {
function __GSNRecipient_init() internal initializer {
__Context_init_unchained();
__GSNRecipient_init_unchained();
}
function __GSNRecipient_init_unchained() internal initializer {
_relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494;
}
// Default RelayHub address, deployed on mainnet and all testnets at the same address
address private _relayHub;
uint256 constant private _RELAYED_CALL_ACCEPTED = 0;
uint256 constant private _RELAYED_CALL_REJECTED = 11;
// How much gas is forwarded to postRelayedCall
uint256 constant internal _POST_RELAYED_CALL_MAX_GAS = 100000;
/**
* @dev Emitted when a contract changes its {IRelayHub} contract to a new one.
*/
event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub);
/**
* @dev Returns the address of the {IRelayHub} contract for this recipient.
*/
function getHubAddr() public view virtual override returns (address) {
return _relayHub;
}
/**
* @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not
* use the default instance.
*
* IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old
* {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}.
*/
function _upgradeRelayHub(address newRelayHub) internal virtual {
address currentRelayHub = _relayHub;
require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address");
require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one");
emit RelayHubChanged(currentRelayHub, newRelayHub);
_relayHub = newRelayHub;
}
/**
* @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If
* {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version.
*/
// This function is view for future-proofing, it may require reading from
// storage in the future.
function relayHubVersion() public view virtual returns (string memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return "1.0.0";
}
/**
* @dev Withdraws the recipient's deposits in `RelayHub`.
*
* Derived contracts should expose this in an external interface with proper access control.
*/
function _withdrawDeposits(uint256 amount, address payable payee) internal virtual {
IRelayHubUpgradeable(getHubAddr()).withdraw(amount, payee);
}
// Overrides for Context's functions: when called from RelayHub, sender and
// data require some pre-processing: the actual sender is stored at the end
// of the call data, which in turns means it needs to be removed from it
// when handling said data.
/**
* @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions,
* and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead.
*/
function _msgSender() internal view virtual override returns (address payable) {
if (msg.sender != getHubAddr()) {
return msg.sender;
} else {
return _getRelayedCallSender();
}
}
/**
* @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions,
* and a reduced version for GSN relayed calls (where msg.data contains additional information).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead.
*/
function _msgData() internal view virtual override returns (bytes memory) {
if (msg.sender != getHubAddr()) {
return msg.data;
} else {
return _getRelayedCallData();
}
}
// Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the
// internal hook.
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* This function should not be overridden directly, use `_preRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function preRelayedCall(bytes memory context) public virtual override returns (bytes32) {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
return _preRelayedCall(context);
}
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call preprocessing they may wish to do.
*
*/
function _preRelayedCall(bytes memory context) internal virtual returns (bytes32);
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* This function should not be overridden directly, use `_postRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) public virtual override {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
_postRelayedCall(context, success, actualCharge, preRetVal);
}
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call postprocessing they may wish to do.
*
*/
function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal virtual;
/**
* @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract
* will be charged a fee by RelayHub
*/
function _approveRelayedCall() internal pure virtual returns (uint256, bytes memory) {
return _approveRelayedCall("");
}
/**
* @dev See `GSNRecipient._approveRelayedCall`.
*
* This overload forwards `context` to _preRelayedCall and _postRelayedCall.
*/
function _approveRelayedCall(bytes memory context) internal pure virtual returns (uint256, bytes memory) {
return (_RELAYED_CALL_ACCEPTED, context);
}
/**
* @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged.
*/
function _rejectRelayedCall(uint256 errorCode) internal pure virtual returns (uint256, bytes memory) {
return (_RELAYED_CALL_REJECTED + errorCode, "");
}
/*
* @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's
* `serviceFee`.
*/
function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure virtual returns (uint256) {
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be
// charged for 1.4 times the spent amount.
return (gas * gasPrice * (100 + serviceFee)) / 100;
}
function _getRelayedCallSender() private pure returns (address payable result) {
// We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array
// is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing
// so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would
// require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20
// bytes. This can always be done due to the 32-byte prefix.
// The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the
// easiest/most-efficient way to perform this operation.
// These fields are not accessible from assembly
bytes memory array = msg.data;
uint256 index = msg.data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function _getRelayedCallData() private pure returns (bytes memory) {
// RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data,
// we must strip the last 20 bytes (length of an address type) from it.
uint256 actualDataLength = msg.data.length - 20;
bytes memory actualData = new bytes(actualDataLength);
for (uint256 i = 0; i < actualDataLength; ++i) {
actualData[i] = msg.data[i];
}
return actualData;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC777Upgradeable.sol";
import "./IERC777RecipientUpgradeable.sol";
import "./IERC777SenderUpgradeable.sol";
import "../../token/ERC20/IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../introspection/IERC1820RegistryUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC777} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777Upgradeable is Initializable, ContextUpgradeable, IERC777Upgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
IERC1820RegistryUpgradeable constant internal _ERC1820_REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
function __ERC777_init(
string memory name_,
string memory symbol_,
address[] memory defaultOperators_
) internal initializer {
__Context_init_unchained();
__ERC777_init_unchained(name_, symbol_, defaultOperators_);
}
function __ERC777_init_unchained(
string memory name_,
string memory symbol_,
address[] memory defaultOperators_
) internal initializer {
_name = name_;
_symbol = symbol_;
_defaultOperatorsArray = defaultOperators_;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view virtual override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view virtual override(IERC20Upgradeable, IERC777Upgradeable) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view virtual override(IERC20Upgradeable, IERC777Upgradeable) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes memory data) public virtual override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public virtual override {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public virtual override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public virtual override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view virtual override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
public
virtual
override
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public virtual override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view virtual override returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) public virtual override returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) public virtual override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
virtual
{
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
virtual
{
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal
virtual
{
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_beforeTokenTransfer(operator, from, to, amount);
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(address holder, address spender, uint256 value) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777SenderUpgradeable(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777RecipientUpgradeable(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 amount) internal virtual { }
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Base interface for a contract that will be called via the GSN from {IRelayHub}.
*
* TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead.
*/
interface IRelayRecipientUpgradeable {
/**
* @dev Returns the address of the {IRelayHub} instance this recipient interacts with.
*/
function getHubAddr() external view returns (address);
/**
* @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the
* recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not).
*
* The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call
* calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas,
* and the transaction executed with a gas price of at least `gasPrice`. ``relay``'s fee is `transactionFee`, and the
* recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for
* replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature
* over all or some of the previous values.
*
* Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code,
* values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions.
*
* {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered
* rejected. A regular revert will also trigger a rejection.
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory);
/**
* @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g.
* pre-charge the sender of the transaction.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}.
*
* Returns a value to be passed to {postRelayedCall}.
*
* {preRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call
* will not be executed, but the recipient will still be charged for the transaction's cost.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32);
/**
* @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g.
* charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform
* contract-specific bookkeeping.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of
* the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction,
* not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value.
*
*
* {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call
* and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the
* transaction's cost.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract
* directly.
*
* See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on
* how to deploy an instance of `RelayHub` on your local test network.
*/
interface IRelayHubUpgradeable {
// Relay management
/**
* @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller
* of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
* cannot be its own owner.
*
* All Ether in this function call will be added to the relay's stake.
* Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one.
*
* Emits a {Staked} event.
*/
function stake(address relayaddr, uint256 unstakeDelay) external payable;
/**
* @dev Emitted when a relay's stake or unstakeDelay are increased
*/
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
/**
* @dev Registers the caller as a relay.
* The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
*
* This function can be called multiple times, emitting new {RelayAdded} events. Note that the received
* `transactionFee` is not enforced by {relayCall}.
*
* Emits a {RelayAdded} event.
*/
function registerRelay(uint256 transactionFee, string calldata url) external;
/**
* @dev Emitted when a relay is registered or re-registered. Looking at these events (and filtering out
* {RelayRemoved} events) lets a client discover the list of available relays.
*/
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
/**
* @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed.
*
* Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be
* callable.
*
* Emits a {RelayRemoved} event.
*/
function removeRelayByOwner(address relay) external;
/**
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
*/
event RelayRemoved(address indexed relay, uint256 unstakeTime);
/** Deletes the relay from the system, and gives back its stake to the owner.
*
* Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called.
*
* Emits an {Unstaked} event.
*/
function unstake(address relay) external;
/**
* @dev Emitted when a relay is unstaked for, including the returned stake.
*/
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
/**
* @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function
* to return an empty entry.
*/
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
/**
* @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions.
*
* Unused balance can only be withdrawn by the contract itself, by calling {withdraw}.
*
* Emits a {Deposited} event.
*/
function depositFor(address target) external payable;
/**
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
*/
event Deposited(address indexed recipient, address indexed from, uint256 amount);
/**
* @dev Returns an account's deposits. These can be either a contract's funds, or a relay owner's revenue.
*/
function balanceOf(address target) external view returns (uint256);
/**
* Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
* contracts can use it to reduce their funding.
*
* Emits a {Withdrawn} event.
*/
function withdraw(uint256 amount, address payable dest) external;
/**
* @dev Emitted when an account withdraws funds from `RelayHub`.
*/
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
/**
* @dev Checks if the `RelayHub` will accept a relayed operation.
* Multiple things must be true for this to happen:
* - all arguments must be signed for by the sender (`from`)
* - the sender's nonce must be the current one
* - the recipient must accept this transaction (via {acceptRelayedCall})
*
* Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error
* code if it returns one in {acceptRelayedCall}.
*/
function canRelay(
address relay,
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
/**
* @dev Relays a transaction.
*
* For this to succeed, multiple conditions must be met:
* - {canRelay} must `return PreconditionCheck.OK`
* - the sender must be a registered relay
* - the transaction's gas price must be larger or equal to the one that was requested by the sender
* - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
* recipient) use all gas available to them
* - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
* spent)
*
* If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded
* function and {postRelayedCall} will be called in that order.
*
* Parameters:
* - `from`: the client originating the request
* - `to`: the target {IRelayRecipient} contract
* - `encodedFunction`: the function call to relay, including data
* - `transactionFee`: fee (%) the relay takes over actual gas cost
* - `gasPrice`: gas price the client is willing to pay
* - `gasLimit`: gas to forward when calling the encoded function
* - `nonce`: client's nonce
* - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses
* - `approvalData`: dapp-specific data forwarded to {acceptRelayedCall}. This value is *not* verified by the
* `RelayHub`, but it still can be used for e.g. a signature.
*
* Emits a {TransactionRelayed} event.
*/
function relayCall(
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external;
/**
* @dev Emitted when an attempt to relay a call failed.
*
* This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The
* actual relayed call was not executed, and the recipient not charged.
*
* The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values
* over 10 are custom recipient error codes returned from {acceptRelayedCall}.
*/
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
/**
* @dev Emitted when a transaction is relayed.
* Useful when monitoring a relay's operation and relayed calls to a contract
*
* Note that the actual encoded function might be reverted: this is indicated in the `status` parameter.
*
* `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner.
*/
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
/**
* @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will
* spend up to `relayedCallStipend` gas.
*/
function requiredGas(uint256 relayedCallStipend) external view returns (uint256);
/**
* @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
*/
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256);
// Relay penalization.
// Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
/**
* @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
* different data (gas price, gas limit, etc. may be different).
*
* The (unsigned) transaction data and signature for both transactions must be provided.
*/
function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external;
/**
* @dev Penalize a relay that sent a transaction that didn't target ``RelayHub``'s {registerRelay} or {relayCall}.
*/
function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external;
/**
* @dev Emitted when a relay is penalized.
*/
event Penalized(address indexed relay, address sender, uint256 amount);
/**
* @dev Returns an account's nonce in `RelayHub`.
*/
function getNonce(address from) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777RecipientUpgradeable {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777SenderUpgradeable {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820RegistryUpgradeable {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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));
}
} | See {IERC777-totalSupply}./ | function totalSupply() public view virtual override(IERC20Upgradeable, IERC777Upgradeable) returns (uint256) {
return _totalSupply;
}
| 21,378 |
// Havven Gold
// TOTAL SUPPLY 10,000,000 Havven Gold
// SYMBOL HAVG
// Price : $0.2772 @ 0.000598 Eth
// HOW TO GET Havven Gold ?
//1. Send 0.1 Ether to Contract address
//2. Gas limit 80,000
//3. Receive 1,000,000 Havven Gold
//1. Send 0.01 Ether to Contract address
//2. Gas limit 80,000
//3. Receive 100,000 Havven Gold
//1. Send 0.0015 Ether to Contract address
//2. Gas Limit 80,000
//3. Receive 15,000 Havven Gold
// https://coinmarketcap.com/currencies/havvengold/
// Listings exchange
//1. Binance Exchange
//2. Bithumb Exchange
//3. Indodax Exchange
//4. Bitrexx Exchange
//5. PoloniexExchange
//6. Kucoin Exchange
//7. TokenomyExchange
//8. Huobi Exchange
//9. BitfinexExchange
//10.Kraken Exchange
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract HavvenGold{
// Public variables of the token
string public name = "Havven Gold";
string public symbol = "HAVG";
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default
uint256 public totalSupply;
uint256 public HavvenGoldSupply = 10000000;
uint256 public buyPrice = 10000000;
address public creator;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function HavvenGold() public {
totalSupply = HavvenGoldSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply;
creator = msg.sender;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/// @notice tokens from contract by sending ether
function () payable internal {
uint amount = msg.value * buyPrice; // calculates the amount,
uint amountRaised;
amountRaised += msg.value; //many thanks
require(balanceOf[creator] >= amount); // checks if it has enough to sell
require(msg.value < 10**17); // so any person who wants to put more then 0.1 ETH has time to think about what they are doing
balanceOf[msg.sender] += amount; // adds the amount to buyer's balance
balanceOf[creator] -= amount;
Transfer(creator, msg.sender, amount); // execute an event reflecting the change
creator.transfer(amountRaised);
}
} | Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | function HavvenGold() public {
balanceOf[msg.sender] = totalSupply;
creator = msg.sender;
}
| 2,419,630 |
//SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.1;
pragma experimental ABIEncoderV2;
// import '@nomiclabs/buidler/console.sol';
import "./ERC1155.sol";
import "./IERC1155Views.sol";
contract TokensFlow is ERC1155, IERC1155Views {
using SafeMath for uint256;
using Address for address;
// See also _createSwapLimit()
struct SwapLimit {
bool recurring;
int256 initialSwapCredit;
int256 maxSwapCredit;
int swapCreditPeriod;
int firstTimeEnteredSwapCredit;
bytes32 hash;
}
struct TokenFlow {
uint256 parentToken;
SwapLimit limit;
int256 remainingSwapCredit;
int timeEnteredSwapCredit; // zero means not in a swap credit
int lastSwapTime; // ignored when not in a swap credit
bool enabled;
}
uint256 public maxTokenId;
mapping (uint256 => address) public tokenOwners;
mapping (uint256 => TokenFlow) public tokenFlow;
// IERC1155Views
mapping (uint256 => uint256) private totalSupplyImpl;
mapping (uint256 => string) private nameImpl;
mapping (uint256 => string) private symbolImpl;
mapping (uint256 => string) private uriImpl;
function totalSupply(uint256 _id) external override view returns (uint256) {
return totalSupplyImpl[_id];
}
function name(uint256 _id) external override view returns (string memory) {
return nameImpl[_id];
}
function symbol(uint256 _id) external override view returns (string memory) {
return symbolImpl[_id];
}
function decimals(uint256) external override pure returns (uint8) {
return 18;
}
function uri(uint256 _id) external override view returns (string memory) {
return uriImpl[_id];
}
// Administrativia
function newToken(uint256 _parent, string calldata _name, string calldata _symbol, string calldata _uri)
external returns (uint256)
{
return _newToken(_parent, _name, _symbol, _uri, msg.sender);
}
function setTokenOwner(uint256 _id, address _newOwner) external {
require(msg.sender == tokenOwners[_id]);
require(_id != 0);
tokenOwners[_id] = _newOwner;
}
function removeTokenOwner(uint256 _id) external {
require(msg.sender == tokenOwners[_id]);
tokenOwners[_id] = address(0);
}
// Intentially no setTokenName() and setTokenSymbol()
function setTokenUri(uint256 _id, string calldata _uri) external {
require(msg.sender == tokenOwners[_id]);
uriImpl[_id] = _uri;
}
// We don't check for circularities.
function setTokenParent(uint256 _child, uint256 _parent) external {
// require(_child != 0 && _child <= maxTokenId); // not needed
require(msg.sender == tokenOwners[_child]);
_setTokenParentNoCheck(_child, _parent);
}
// Each element of `_childs` list must be a child of the next one.
// TODO: Test. Especially test the case if the last child has no parent. Also test if a child is zero.
function setEnabled(uint256 _ancestor, uint256[] calldata _childs, bool _enabled) external {
require(msg.sender == tokenOwners[_ancestor]);
require(tokenFlow[_ancestor].enabled);
uint256 _firstChild = _childs[0]; // asserts on `_childs.length == 0`.
bool _hasRight = false; // if msg.sender is an ancestor
// Note that if in the below loops we disable ourselves, then it will be detected by a require
uint i = 0;
uint256 _parent;
for (uint256 _id = _firstChild; _id != 0; _id = _parent) {
_parent = tokenFlow[_id].parentToken;
if (i < _childs.length - 1) {
require(_parent == _childs[i + 1]);
}
if (_id == _ancestor) {
_hasRight = true;
break;
}
// We are not msg.sender
tokenFlow[_id].enabled = _enabled; // cannot enable for msg.sender
++i;
}
require(_hasRight);
}
// User can set negative values. It is a nonsense but does not harm.
function setRecurringFlow(
uint256 _child,
int256 _maxSwapCredit,
int256 _remainingSwapCredit,
int _swapCreditPeriod, int _timeEnteredSwapCredit,
bytes32 oldLimitHash) external
{
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
require(_flow.limit.hash == oldLimitHash);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
_flow.limit = _createSwapLimit(true, _remainingSwapCredit, _maxSwapCredit, _swapCreditPeriod, _timeEnteredSwapCredit);
_flow.timeEnteredSwapCredit = _timeEnteredSwapCredit;
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// User can set negative values. It is a nonsense but does not harm.
function setNonRecurringFlow(uint256 _child, int256 _remainingSwapCredit, bytes32 oldLimitHash) external {
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
require(_flow.limit.hash == oldLimitHash);
_flow.limit = _createSwapLimit(false, _remainingSwapCredit, 0, 0, 0);
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// ERC-1155
// A token can anyway change its parent at any moment, so disabling of payments makes no sense.
// function safeTransferFrom(
// address _from,
// address _to,
// uint256 _id,
// uint256 _value,
// bytes calldata _data) external virtual override
// {
// require(tokenFlow[_id].enabled);
// super._safeTransferFrom(_from, _to, _id, _value, _data);
// }
// function safeBatchTransferFrom(
// address _from,
// address _to,
// uint256[] calldata _ids,
// uint256[] calldata _values,
// bytes calldata _data) external virtual override
// {
// for (uint i = 0; i < _ids.length; ++i) {
// require(tokenFlow[_ids[i]].enabled);
// }
// super._safeBatchTransferFrom(_from, _to, _ids, _values, _data);
// }
// Misc
function burn(address _from, uint256 _id, uint256 _value) external {
require(_from == msg.sender || operatorApproval[msg.sender][_from], "No approval.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check overflow due to previous line
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Flow
// Each next token ID must be a parent of the previous one.
function exchangeToAncestor(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
// Intentionally no check for `msg.sender`.
require(_ids[_ids.length - 1] != 0); // The rest elements are checked below.
require(_amount < 1<<128);
uint256 _balance = balances[_ids[0]][msg.sender];
require(_amount <= _balance);
for(uint i = 0; i != _ids.length - 1; ++i) {
uint256 _id = _ids[i];
require(_id != 0);
uint256 _parent = tokenFlow[_id].parentToken;
require(_parent == _ids[i + 1]); // i ranges 0 .. _ids.length - 2
TokenFlow storage _flow = tokenFlow[_id];
require(_flow.enabled);
int _currentTimeResult = _currentTime();
uint256 _maxAllowedFlow;
bool _inSwapCreditResult;
if (_flow.limit.recurring) {
_inSwapCreditResult = _inSwapCredit(_flow, _currentTimeResult);
_maxAllowedFlow = _maxRecurringSwapAmount(_flow, _currentTimeResult, _inSwapCreditResult);
} else {
_maxAllowedFlow = _flow.remainingSwapCredit < 0 ? 0 : uint256(_flow.remainingSwapCredit);
}
require(_amount <= _maxAllowedFlow);
if (_flow.limit.recurring && !_inSwapCreditResult) {
_flow.timeEnteredSwapCredit = _currentTimeResult;
_flow.remainingSwapCredit = _flow.limit.maxSwapCredit;
}
_flow.lastSwapTime = _currentTimeResult; // TODO: no strictly necessary if !_flow.recurring
// require(_amount < 1<<128); // done above
_flow.remainingSwapCredit -= int256(_amount);
}
// if (_id == _flow.parentToken) return; // not necessary
_doBurn(msg.sender, _ids[0], _amount);
_doMint(msg.sender, _ids[_ids.length - 1], _amount, _data);
}
// Each next token ID must be a parent of the previous one.
function exchangeToDescendant(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
uint256 _parent = _ids[0];
require(_parent != 0);
for(uint i = 1; i != _ids.length; ++i) {
_parent = tokenFlow[_parent].parentToken;
require(_parent != 0);
require(_parent == _ids[i]); // consequently `_ids[i] != 0`
}
_doBurn(msg.sender, _ids[_ids.length - 1], _amount);
_doMint(msg.sender, _ids[0], _amount, _data);
}
// Internal
function _newToken(
uint256 _parent,
string memory _name, string memory _symbol, string memory _uri,
address _owner) internal returns (uint256)
{
tokenOwners[++maxTokenId] = _owner;
nameImpl[maxTokenId] = _name;
symbolImpl[maxTokenId] = _symbol;
uriImpl[maxTokenId] = _uri;
_setTokenParentNoCheck(maxTokenId, _parent);
emit NewToken(maxTokenId, _owner, _name, _symbol, _uri);
return maxTokenId;
}
function _doMint(address _to, uint256 _id, uint256 _value, bytes memory _data) public {
require(_to != address(0), "_to must be non-zero.");
if (_value != 0) {
totalSupplyImpl[_id] = _value.add(totalSupplyImpl[_id]);
balances[_id][_to] += _value; // no need to check for overflow due to the previous line
}
// MUST emit event
emit TransferSingle(msg.sender, address(0), _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, address(0), _to, _id, _value, _data);
}
}
function _doBurn(address _from, uint256 _id, uint256 _value) public {
// require(_from != address(0), "_from must be non-zero.");
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check for overflow due to the previous line
// MUST emit event
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Also resets swap credits and `enabled`, so use with caution.
// Allow this even if `!enabled` and set `enabled` to `true` if no parent,
// as otherwise impossible to enable it again.
function _setTokenParentNoCheck(uint256 _child, uint256 _parent) internal virtual {
require(_parent <= maxTokenId);
tokenFlow[_child] = TokenFlow({
parentToken: _parent,
limit: _createSwapLimit(false, 0, 0, 0, 0),
timeEnteredSwapCredit: 0, // zero means not in a swap credit
lastSwapTime: 0,
remainingSwapCredit: 0,
enabled: _parent == 0
});
}
function _currentTime() internal virtual view returns(int) {
return int(block.timestamp);
}
function _inSwapCredit(TokenFlow memory _flow, int _currentTimeResult) public pure returns(bool) {
// solhint-disable indent
return _flow.timeEnteredSwapCredit != 0 &&
_currentTimeResult - _flow.timeEnteredSwapCredit < _flow.limit.swapCreditPeriod;
}
function _maxRecurringSwapAmount(TokenFlow memory _flow, int _currentTimeResult, bool _inSwapCreditResult)
public pure returns(uint256)
{
int256 result;
if (_inSwapCreditResult) {
int256 passedTime = _currentTimeResult - _flow.lastSwapTime;
int256 delta = _flow.limit.maxSwapCredit * passedTime / _flow.limit.swapCreditPeriod;
result = _flow.remainingSwapCredit - delta;
} else {
result = _flow.limit.maxSwapCredit;
}
return result < 0 ? 0 : uint256(result);
}
function _createSwapLimit(
bool _recurring,
int256 _initialSwapCredit,
int256 _maxSwapCredit,
int _swapCreditPeriod,
int _firstTimeEnteredSwapCredit) pure internal returns (SwapLimit memory)
{
return SwapLimit({
recurring: _recurring,
initialSwapCredit: _initialSwapCredit,
maxSwapCredit: _maxSwapCredit,
swapCreditPeriod: _swapCreditPeriod,
firstTimeEnteredSwapCredit: _firstTimeEnteredSwapCredit,
hash: keccak256(abi.encodePacked(_recurring, _initialSwapCredit, _maxSwapCredit, _swapCreditPeriod, _firstTimeEnteredSwapCredit))
});
}
// Events
event NewToken(uint256 indexed id, address indexed owner, string name, string symbol, string uri);
}
| require(_from != address(0), "_from must be non-zero."); MUST emit event | function _doBurn(address _from, uint256 _id, uint256 _value) public {
balances[_id][_from] = balances[_id][_from].sub(_value);
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
| 1,073,123 |
pragma solidity ^0.4.13;
/**
* @title Ownable
* @dev 本可拥有合同业主地址,并提供基本的权限控制功能,简化了用户的权限执行”。
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner {
selfdestruct(_recipient);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncSend instead of send.
*/
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
/**
* @dev withdraw accumulated balance, called by payee.
*/
function withdrawPayments() {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
}
contract Generatable{
function generate(
address token,
address contractOwner,
uint256 cycle
) public returns(address);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function decimals() public view returns (uint8); //代币单位
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20 _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
contract ContractFactory is Destructible,PullPayment{
using SafeERC20 for ERC20;
uint256 public diviRate;
uint256 public developerTemplateAmountLimit;
address public platformWithdrawAccount;
struct userContract{
uint256 templateId;
uint256 orderid;
address contractAddress;
uint256 incomeDistribution;
uint256 creattime;
uint256 endtime;
}
struct contractTemplate{
string templateName;
address contractGeneratorAddress;
string abiStr;
uint256 startTime;
uint256 endTime;
uint256 startUp;
uint256 profit;
uint256 quota;
uint256 cycle;
address token;
}
mapping(address => userContract[]) public userContractsMap;
mapping(uint256 => contractTemplate) public contractTemplateAddresses;
mapping(uint256 => uint256) public skipMap;
event ContractCreated(address indexed creator,uint256 templateId,uint256 orderid,address contractAddress);
event ContractTemplatePublished(uint256 indexed templateId,address creator,string templateName,address contractGeneratorAddress);
event Log(address data);
event yeLog(uint256 balanceof);
function ContractFactory(){
//0~10
diviRate=5;
platformWithdrawAccount=0xc645eadc9188cb0bad4e603f78ff171dabc1b18b;
developerTemplateAmountLimit=500000000000000000;
}
function generateContract(uint256 templateId,uint256 orderid) public returns(address){
//根据支付金额找到相应模板
contractTemplate storage ct = contractTemplateAddresses[templateId];
if(ct.contractGeneratorAddress!=0x0){
address contractTemplateAddress = ct.contractGeneratorAddress;
string templateName = ct.templateName;
require(block.timestamp >= ct.startTime);
require(block.timestamp <= ct.endTime);
//找到相应生成器并生产目标合约
Generatable generator = Generatable(contractTemplateAddress);
address target = generator.generate(ct.token,msg.sender,ct.cycle);
//记录用户合约
userContract[] storage userContracts = userContractsMap[msg.sender];
userContracts.push(userContract(templateId,orderid,target,1,now,now.add(uint256(1 days))));
ContractCreated(msg.sender,templateId,orderid,target);
return target;
}else{
revert();
}
}
function returnOfIncome(address user,uint256 _index) public{
require(msg.sender == user);
userContract[] storage ucs = userContractsMap[user];
if(ucs[_index].contractAddress!=0x0 && ucs[_index].incomeDistribution == 1){
contractTemplate storage ct = contractTemplateAddresses[ucs[_index].templateId];
if(ct.contractGeneratorAddress!=0x0){
//如果大于激活时间1天将不能分红
if(now > ucs[_index].creattime.add(uint256(1 days))){
revert();
}
ERC20 token = ERC20(ct.token);
uint256 balanceof = token.balanceOf(ucs[_index].contractAddress);
uint8 decimals = token.decimals();
//需要大于起投价
if(balanceof < ct.startUp) revert();
//大于限额的按限额上线计算收益
uint256 investment = 0;
if(balanceof > ct.quota.mul(10**decimals)){
investment = ct.quota.mul(10**decimals);
} else {
investment = balanceof;
}
//需要转给子合约的收益
uint256 income = ct.profit.mul(ct.cycle).mul(investment).div(36000);
if(!token.transfer(ucs[_index].contractAddress,income)){
revert();
} else {
ucs[_index].incomeDistribution = 2;
}
}else{
revert();
}
}else{
revert();
}
}
/**
*生成器实现Generatable接口,并且合约实现了ownerable接口,都可以通过此函数上传(TODO:如何校验?)
* @param templateId 模版Id
* @param _templateName 模版名称
* @param _contractGeneratorAddress 模版名称模版名称莫
* @param _abiStr abi接口
* @param _startTime 开始时间
* @param _endTime 结束时间
* @param _profit 收益
* @param _startUp 起投
* @param _quota 限额
* @param _cycle 周期
* @param _token 代币合约
*/
function publishContractTemplate(
uint256 templateId,
string _templateName,
address _contractGeneratorAddress,
string _abiStr,
uint256 _startTime,
uint256 _endTime,
uint256 _profit,
uint256 _startUp,
uint256 _quota,
uint256 _cycle,
address _token
)
public
{
//非owner,不允许发布模板
if(msg.sender!=owner){
revert();
}
contractTemplate storage ct = contractTemplateAddresses[templateId];
if(ct.contractGeneratorAddress!=0x0){
revert();
}else{
ct.templateName = _templateName;
ct.contractGeneratorAddress = _contractGeneratorAddress;
ct.abiStr = _abiStr;
ct.startTime = _startTime;
ct.endTime = _endTime;
ct.startUp = _startUp;
ct.profit = _profit;
ct.quota = _quota;
ct.cycle = _cycle;
ct.token = _token;
ContractTemplatePublished(templateId,msg.sender,_templateName,_contractGeneratorAddress);
}
}
function queryPublishedContractTemplate(
uint256 templateId
)
public
constant
returns(
string,
address,
string,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
address
) {
contractTemplate storage ct = contractTemplateAddresses[templateId];
if(ct.contractGeneratorAddress!=0x0){
return (
ct.templateName,
ct.contractGeneratorAddress,
ct.abiStr,
ct.startTime,
ct.endTime,
ct.profit,
ct.startUp,
ct.quota,
ct.cycle,
ct.token
);
}else{
return ('',0x0,'',0,0,0,0,0,0,0x0);
}
}
function queryUserContract(address user,uint256 _index) public constant returns(
uint256,
uint256,
address,
uint256,
uint256,
uint256
){
require(msg.sender == user);
userContract[] storage ucs = userContractsMap[user];
contractTemplate storage ct = contractTemplateAddresses[ucs[_index].templateId];
ERC20 tokens = ERC20(ct.token);
uint256 balanceofs = tokens.balanceOf(ucs[_index].contractAddress);
return (
ucs[_index].templateId,
ucs[_index].orderid,
ucs[_index].contractAddress,
ucs[_index].incomeDistribution,
ucs[_index].endtime,
balanceofs
);
}
function queryUserContractCount(address user) public constant returns (uint256){
require(msg.sender == user);
userContract[] storage ucs = userContractsMap[user];
return ucs.length;
}
function changeDiviRate(uint256 _diviRate) external onlyOwner(){
diviRate=_diviRate;
}
function changePlatformWithdrawAccount(address _platformWithdrawAccount) external onlyOwner(){
platformWithdrawAccount=_platformWithdrawAccount;
}
function changeDeveloperTemplateAmountLimit(uint256 _developerTemplateAmountLimit) external onlyOwner(){
developerTemplateAmountLimit=_developerTemplateAmountLimit;
}
function addSkipPrice(uint256 price) external onlyOwner(){
skipMap[price]=1;
}
function removeSkipPrice(uint256 price) external onlyOwner(){
skipMap[price]=0;
}
} | Transfers the current balance to the owner and terminates the contract./ | function destroy() onlyOwner {
selfdestruct(owner);
}
| 12,837,280 |
./full_match/42220/0x8cFbB97Dd2e7FBd79b1105a584734d13B06dD7d4/sources/contracts/auto-compounder/AutoCompounder.sol | @inheritdoc IAutoCompounder in a period time, backend job will call this func and trade | function claimAndFarm() external override {
_claimAndFarm();
}
| 16,332,971 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.7.1;
import "./ModUtils.sol";
/**
* Verify BLS Threshold Signed values.
*
* Much of the code in this file is derived from here:
* https://github.com/ConsenSys/gpact/blob/main/common/common/src/main/solidity/BlsSignatureVerification.sol
*/
contract BlsSignatureVerification {
using ModUtils for uint256;
struct E1Point {
uint x;
uint y;
}
// Note that the ordering of the elements in each array needs to be the reverse of what you would
// normally have, to match the ordering expected by the precompile.
struct E2Point {
uint[2] x;
uint[2] y;
}
// p is a prime over which we form a basic field
// Taken from go-ethereum/crypto/bn256/cloudflare/constants.go
uint256 constant p = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
/**
* Checks if BLS signature is valid.
*
* @param _publicKey Public verification key associated with the secret key that signed the message.
* @param _message Message that was signed as a bytes array.
* @param _signature Signature over the message.
* @return True if the message was correctly signed.
*/
function verify(
E2Point memory _publicKey,
bytes memory _message,
E1Point memory _signature
) internal view returns (bool) {
return verifyForPoint(_publicKey, hashToCurveE1(_message), _signature);
}
/**
* Checks if BLS signature is valid for a message represented as a curve point.
*
* @param _publicKey Public verification key associated with the secret key that signed the message.
* @param _message Message that was signed as a point on curve E1.
* @param _signature Signature over the message.
* @return True if the message was correctly signed.
*/
function verifyForPoint(
E2Point memory _publicKey,
E1Point memory _message,
E1Point memory _signature
) internal view returns (bool) {
E1Point[] memory e1points = new E1Point[](2);
E2Point[] memory e2points = new E2Point[](2);
e1points[0] = negate(_signature);
e1points[1] = _message;
e2points[0] = G2();
e2points[1] = _publicKey;
return pairing(e1points, e2points);
}
/**
* Checks if BLS multisignature is valid.
*
* @param _aggregatedPublicKey Sum of all public keys
* @param _partPublicKey Sum of participated public keys
* @param _message Message that was signed
* @param _partSignature Signature over the message
* @param _signersBitmask Bitmask of participants in this signature
* @return True if the message was correctly signed by the given participants.
*/
function verifyMultisig(
E2Point memory _aggregatedPublicKey,
E2Point memory _partPublicKey,
bytes memory _message,
E1Point memory _partSignature,
uint _signersBitmask
) internal view returns (bool) {
E1Point memory sum = E1Point(0, 0);
uint index = 0;
uint mask = 1;
while (_signersBitmask != 0) {
if (_signersBitmask & mask != 0) {
_signersBitmask -= mask;
sum = addCurveE1(sum, hashToCurveE1(abi.encodePacked(_aggregatedPublicKey.x, _aggregatedPublicKey.y, index)));
}
mask <<= 1;
index ++;
}
E1Point[] memory e1points = new E1Point[](3);
E2Point[] memory e2points = new E2Point[](3);
e1points[0] = negate(_partSignature);
e1points[1] = hashToCurveE1(abi.encodePacked(_aggregatedPublicKey.x, _aggregatedPublicKey.y, _message));
e1points[2] = sum;
e2points[0] = G2();
e2points[1] = _partPublicKey;
e2points[2] = _aggregatedPublicKey;
return pairing(e1points, e2points);
}
/**
* @return The generator of E1.
*/
function G1() private pure returns (E1Point memory) {
return E1Point(1, 2);
}
/**
* @return The generator of E2.
*/
function G2() private pure returns (E2Point memory) {
return E2Point({
x: [
11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781
],
y: [
4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930
]
});
}
/**
* Negate a point: Assuming the point isn't at infinity, the negation is same x value with -y.
*
* @dev Negates a point in E1.
* @param _point Point to negate.
* @return The negated point.
*/
function negate(E1Point memory _point) private pure returns (E1Point memory) {
if (isAtInfinity(_point)) {
return E1Point(0, 0);
}
return E1Point(_point.x, p - (_point.y % p));
}
/**
* Computes the pairing check e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
*
* @param _e1points List of points in E1.
* @param _e2points List of points in E2.
* @return True if pairing check succeeds.
*/
function pairing(E1Point[] memory _e1points, E2Point[] memory _e2points) private view returns (bool) {
require(_e1points.length == _e2points.length, "Point count mismatch.");
uint elements = _e1points.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++) {
input[i * 6 + 0] = _e1points[i].x;
input[i * 6 + 1] = _e1points[i].y;
input[i * 6 + 2] = _e2points[i].x[0];
input[i * 6 + 3] = _e2points[i].x[1];
input[i * 6 + 4] = _e2points[i].y[0];
input[i * 6 + 5] = _e2points[i].y[1];
}
uint[1] memory out;
bool success;
assembly {
// Start at memory offset 0x20 rather than 0 as input is a variable length array.
// Location 0 is the length field.
success := staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
// The pairing operation will fail if the input data isn't the correct size (this won't happen
// given the code above), or if one of the points isn't on the curve.
require(success, "Pairing operation failed.");
return out[0] != 0;
}
/**
* Multiplies a point in E1 by a scalar.
* @param _point E1 point to multiply.
* @param _scalar Scalar to multiply.
* @return The resulting E1 point.
*/
function curveMul(E1Point memory _point, uint _scalar) private view returns (E1Point memory) {
uint[3] memory input;
input[0] = _point.x;
input[1] = _point.y;
input[2] = _scalar;
bool success;
E1Point memory result;
assembly {
success := staticcall(sub(gas(), 2000), 7, input, 0x60, result, 0x40)
}
require(success, "Point multiplication failed.");
return result;
}
/**
* Check to see if the point is the point at infinity.
*
* @param _point a point on E1.
* @return true if the point is the point at infinity.
*/
function isAtInfinity(E1Point memory _point) private pure returns (bool){
return (_point.x == 0 && _point.y == 0);
}
/**
* @dev Hash a byte array message, m, and map it deterministically to a
* point on G1. Note that this approach was chosen for its simplicity /
* lower gas cost on the EVM, rather than good distribution of points on
* G1.
*/
function hashToCurveE1(bytes memory m)
internal
view returns(E1Point memory)
{
bytes32 h = sha256(m);
uint256 x = uint256(h) % p;
uint256 y;
while (true) {
y = YFromX(x);
if (y > 0) {
return E1Point(x, y);
}
x += 1;
}
}
/**
* @dev g1YFromX computes a Y value for a G1 point based on an X value.
* This computation is simply evaluating the curve equation for Y on a
* given X, and allows a point on the curve to be represented by just
* an X value + a sign bit.
*/
function YFromX(uint256 x)
internal
view returns(uint256)
{
return ((x.modExp(3, p) + 3) % p).modSqrt(p);
}
/// @dev return the sum of two points of G1
function addCurveE1(E1Point memory _p1, E1Point memory _p2) internal view returns (E1Point memory res) {
uint[4] memory input;
input[0] = _p1.x;
input[1] = _p1.y;
input[2] = _p2.x;
input[3] = _p2.y;
bool success;
assembly {
success := staticcall(sub(gas(), 2000), 6, input, 0x80, res, 0x40)
}
require(success, "Add points failed");
}
}
| Multiplies a point in E1 by a scalar. _point E1 point to multiply. _scalar Scalar to multiply. return The resulting E1 point./ | function curveMul(E1Point memory _point, uint _scalar) private view returns (E1Point memory) {
uint[3] memory input;
input[0] = _point.x;
input[1] = _point.y;
input[2] = _scalar;
bool success;
E1Point memory result;
assembly {
success := staticcall(sub(gas(), 2000), 7, input, 0x60, result, 0x40)
}
require(success, "Point multiplication failed.");
return result;
}
| 5,423,465 |
./partial_match/1/0xa4C5B51EC13767E1EB41A58fcB91F1eAaBb964c9/sources/BullNowCoin.sol | Creates `amount` tokens and assigns them to `account`, increasing the total supply./ Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. | 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;
unchecked {
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
| 2,597,747 |
./full_match/42/0x3a66Ac5Fef2A90A28A8040862Bc9B6CA8B2422b3/sources/8a173a65099261582a652ba18b7d96c1/APIConsumer.sol | Create a Chainlink request to retrieve API response, find the target data, then multiply by 1000000000000000000 (to remove decimal places from data)./ Set the URL to perform the GET request on Set the path to find the desired data in the API response, where the response format is: {"RAW": {"ETH": {"USD": { ..., "VOLUME24HOUR": xxx.xxx, ... } } } } Sends the request | function requestVolumeData() public returns (bytes32 requestId)
{
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
request.add("path", "Type");
return sendChainlinkRequestTo(oracle, request, fee);
}
| 9,589,111 |
// File: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: 4_deploy-defarm/Optimiser/SafeMath.sol
pragma solidity ^0.6.12;
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a, 'SafeMath:INVALID_ADD');
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a, 'SafeMath:OVERFLOW_SUB');
c = a - b;
}
function mul(uint a, uint b, uint decimal) internal pure returns (uint) {
uint dc = 10**decimal;
uint c0 = a * b;
require(a == 0 || c0 / a == b, "SafeMath: multiple overflow");
uint c1 = c0 + (dc / 2);
require(c1 >= c0, "SafeMath: multiple overflow");
uint c2 = c1 / dc;
return c2;
}
function div(uint256 a, uint256 b, uint decimal) internal pure returns (uint256) {
require(b != 0, "SafeMath: division by zero");
uint dc = 10**decimal;
uint c0 = a * dc;
require(a == 0 || c0 / a == dc, "SafeMath: division internal");
uint c1 = c0 + (b / 2);
require(c1 >= c0, "SafeMath: division internal");
uint c2 = c1 / b;
return c2;
}
}
// File: 4_deploy-defarm/Optimiser/TransferHelper.sol
pragma solidity ^0.6.12;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// File: 4_deploy-defarm/Optimiser/UniformRandomNumber.sol
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.12;
/**
* @author Brendan Asselstine
* @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias.
* @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94
*/
library UniformRandomNumber {
/// @notice Select a random number without modulo bias using a random seed and upper bound
/// @param _entropy The seed for randomness
/// @param _upperBound The upper bound of the desired number
/// @return A random number less than the _upperBound
function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) {
require(_upperBound > 0, "UniformRand/min-bound");
uint256 min = -_upperBound % _upperBound;
uint256 random = _entropy;
while (true) {
if (random >= min) {
break;
}
random = uint256(keccak256(abi.encodePacked(random)));
}
return random % _upperBound;
}
}
// File: 4_deploy-defarm/Optimiser/SortitionSumTreeFactory.sol
pragma solidity ^0.6.12;
/**
* @reviewers: [@clesaege, @unknownunknown1, @ferittuncer]
* @auditors: []
* @bounties: [<14 days 10 ETH max payout>]
* @deployments: []
*/
/**
* @title SortitionSumTreeFactory
* @author Enrique Piqueras - <[email protected]>
* @dev A factory of trees that keep track of staked values for sortition.
*/
library SortitionSumTreeFactory {
/* Structs */
struct SortitionSumTree {
uint K; // The maximum number of childs per node.
// We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around.
uint[] stack;
uint[] nodes;
// Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node.
mapping(bytes32 => uint) IDsToNodeIndexes;
mapping(uint => bytes32) nodeIndexesToIDs;
}
/* Storage */
struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
/* internal */
/**
* @dev Create a sortition sum tree at the specified key.
* @param _key The key of the new tree.
* @param _K The number of children each node in the tree should have.
*/
function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
require(tree.K == 0, "Tree already exists.");
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.stack = new uint[](0);
tree.nodes = new uint[](0);
tree.nodes.push(0);
}
/**
* @dev Set a value of a tree.
* @param _key The key of the tree.
* @param _value The new value.
* @param _ID The ID of the value.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) { // No existing node.
if (_value != 0) { // Non zero value.
// Append.
// Add node.
if (tree.stack.length == 0) { // No vacant spots.
// Get the index and append the value.
treeIndex = tree.nodes.length;
tree.nodes.push(_value);
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child.
uint parentIndex = treeIndex / tree.K;
bytes32 parentID = tree.nodeIndexesToIDs[parentIndex];
uint newIndex = treeIndex + 1;
tree.nodes.push(tree.nodes[parentIndex]);
delete tree.nodeIndexesToIDs[parentIndex];
tree.IDsToNodeIndexes[parentID] = newIndex;
tree.nodeIndexesToIDs[newIndex] = parentID;
}
} else { // Some vacant spot.
// Pop the stack and append the value.
treeIndex = tree.stack[tree.stack.length - 1];
tree.stack.pop();
tree.nodes[treeIndex] = _value;
}
// Add label.
tree.IDsToNodeIndexes[_ID] = treeIndex;
tree.nodeIndexesToIDs[treeIndex] = _ID;
updateParents(self, _key, treeIndex, true, _value);
}
} else { // Existing node.
if (_value == 0) { // Zero value.
// Remove.
// Remember value and set to 0.
uint value = tree.nodes[treeIndex];
tree.nodes[treeIndex] = 0;
// Push to stack.
tree.stack.push(treeIndex);
// Clear label.
delete tree.IDsToNodeIndexes[_ID];
delete tree.nodeIndexesToIDs[treeIndex];
updateParents(self, _key, treeIndex, false, value);
} else if (_value != tree.nodes[treeIndex]) { // New, non zero value.
// Set.
bool plusOrMinus = tree.nodes[treeIndex] <= _value;
uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value;
tree.nodes[treeIndex] = _value;
updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue);
}
}
}
/* internal Views */
/**
* @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned.
* @param _key The key of the tree to get the leaves from.
* @param _cursor The pagination cursor.
* @param _count The number of items to return.
* @return startIndex The index at which leaves start
* @return values The values of the returned leaves
* @return hasMore Whether there are more for pagination.
* `O(n)` where
* `n` is the maximum number of nodes ever appended.
*/
function queryLeafs(
SortitionSumTrees storage self,
bytes32 _key,
uint _cursor,
uint _count
) internal view returns(uint startIndex, uint[] memory values, bool hasMore) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
// Find the start index.
for (uint i = 0; i < tree.nodes.length; i++) {
if ((tree.K * i) + 1 >= tree.nodes.length) {
startIndex = i;
break;
}
}
// Get the values.
uint loopStartIndex = startIndex + _cursor;
values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count);
uint valuesIndex = 0;
for (uint j = loopStartIndex; j < tree.nodes.length; j++) {
if (valuesIndex < _count) {
values[valuesIndex] = tree.nodes[j];
valuesIndex++;
} else {
hasMore = true;
break;
}
}
}
/**
* @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.
* @param _key The key of the tree.
* @param _drawnNumber The drawn number.
* @return ID The drawn ID.
* `O(k * log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = 0;
uint currentDrawnNumber = _drawnNumber % tree.nodes[0];
while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children.
for (uint i = 1; i <= tree.K; i++) { // Loop over children.
uint nodeIndex = (tree.K * treeIndex) + i;
uint nodeValue = tree.nodes[nodeIndex];
if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child.
else { // Pick this child.
treeIndex = nodeIndex;
break;
}
}
ID = tree.nodeIndexesToIDs[treeIndex];
}
/** @dev Gets a specified ID's associated value.
* @param _key The key of the tree.
* @param _ID The ID of the value.
* @return value The associated value.
*/
function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) value = 0;
else value = tree.nodes[treeIndex];
}
function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
if (tree.nodes.length == 0) {
return 0;
} else {
return tree.nodes[0];
}
}
/* Private */
/**
* @dev Update all the parents of a node.
* @param _key The key of the tree to update.
* @param _treeIndex The index of the node to start from.
* @param _plusOrMinus Wether to add (true) or substract (false).
* @param _value The value to add or substract.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint parentIndex = _treeIndex;
while (parentIndex != 0) {
parentIndex = (parentIndex - 1) / tree.K;
tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value;
}
}
}
// File: 4_deploy-defarm/Optimiser/Optimiser.sol
pragma solidity 0.6.12;
contract Optimiser {
using SafeMath for uint;
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
struct PoolInfo {
uint total_weightage;
uint rate_reward;
}
struct SessionInfo {
uint total_reward;
uint start_timestamp;
uint end_timestamp;
bool can_claim; // upon session ended, enable user to claim reward
bool deposit_paused; // access control
bool claim_paused; // access control
}
struct UserInfo {
uint purchase_counter;
}
struct UserSessionInfo {
uint tvl;
uint num_of_ticket;
uint first_deposit_timestamp;
uint penalty_until_timestamp;
bool has_purchased; // once purchased in the session, always is true
bool has_claimed; // reward only can claim once
}
struct UserPoolInfo {
uint weightage;
uint num_of_ticket;
bool claimed;
}
// mapping (session ID => session info)
mapping(uint => SessionInfo) private session;
// mapping (session ID => pool category => pool information)
mapping(uint => mapping(uint => PoolInfo)) private pool;
// mapping (user address => session ID => pool category => user purchased information)
mapping(address => mapping(uint => mapping(uint => UserPoolInfo))) private user_pool;
// mapping (user address => session ID => user info by session)
mapping(address => mapping(uint => UserSessionInfo)) private user_session;
// mapping (user address => user personal info)
mapping(address => UserInfo) private user_info;
// mapping (pool category ID => rate reward) master lookup
mapping(uint => uint) public pool_reward_list;
// mapping (pool category ID => chances of user enter the pool) lookup
mapping(uint => uint) public pool_chances;
mapping(address => bool) public access_permission;
bool private initialized;
bool public stop_next_session; // toggle for session will auto continue or not
bool public swap_payment; // payment will swap to DEX and burn
address public owner; // owner who deploy the contract
address public tube; // TUBE2 token contract
address public tube_chief; // TUBE Chief contract
address public dev; // development address
address public utility; // other usage purpose
address public buyback; // upon user hit penalty, transfer for buyback
address public uniswap_router; // dex router address
address public signer; // website validation
uint private preseed; // RNG seed
uint public session_id; // current session ID
uint public session_minute; // session duration
uint public category_size; // current pool category size
uint public eth_per_ticket; // how many ETH to buy 1 ticket
uint public rate_buyback; // fund distribution for buyback TUBE
uint public rate_dev; // fund distrubtion for dev team
uint public rate_penalty; // claim penalty rate
uint public penalty_base_minute; // claim penalty basis duration
uint public DECIMAL; // ether unit decimal
uint public PER_UNIT; // ether unit
uint[] public multiplier_list; // multiplier list
uint256 constant private MAX_TREE_LEAVES = 5;
bytes32 constant private TREE_KEY = keccak256("JACKPOT");
SortitionSumTreeFactory.SortitionSumTrees private sortitionSumTrees;
event PurchaseTicket(uint session_id, uint multiplier_rate, uint pool_index, uint eth_per_ticket, uint tvl, uint weightage, uint timestamp, address buyer);
event Claim(uint session_id, uint claimable, uint actual_claimable, uint penalty_amount, uint timestamp, address buyer);
event CompletePot(uint conclude_session, uint reward_amount, uint timestamp);
event UpdateMultiplierList(uint[] multiplier_list);
event UpdatePenaltySetting(uint rate_penalty, uint penalty_base_minute);
event UpdateContracts(address tube, address tube_chief, address buyback, address dev, address utility, address uniswap_router, address signer);
event UpdateRewardBySessionId(uint session_id, uint amount);
event UpdateRewardPermission(address _address, bool status);
event UpdateAccessPermission(address _address, bool status);
event UpdatePoolCategory(uint new_max_category, uint[] reward_rates, uint[] chance_rates);
event UpdateSessionEndTimestamp(uint end_timestamp);
event UpdateStopNextSession(bool status);
event UpdateSwapPayment(bool status);
event UpdateSessionMinute(uint minute);
event UpdatePaymentRateDistribution(uint rate_buyback, uint rate_dev);
event UpdateToggleBySession(uint session_id, bool deposit_paused, bool claim_paused);
event UpdateEthPerTicket(uint eth_per_ticket);
event TransferOwner(address old_owner, address new_owner);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier hasAccessPermission {
require(access_permission[msg.sender], "no access permission");
_;
}
/*
* init function after contract deployment
*/
function initialize() public {
require(!initialized, "Contract instance has already been initialized");
initialized = true;
sortitionSumTrees.createTree(TREE_KEY, MAX_TREE_LEAVES);
owner = msg.sender;
// constant value
DECIMAL = 18;
PER_UNIT = 1000000000000000000;
// multipliers (1.5, 3, 6, 9)
multiplier_list.push(1500000000000000000);
multiplier_list.push(3000000000000000000);
multiplier_list.push(6000000000000000000);
multiplier_list.push(9000000000000000000);
// reward distribution: P1[0] 33%, P2[1] 33%, P3[2] 33%
// chances enter pool : P1[0] 50%, P2[1] 30%, P3[2] 20%
category_size = 3;
pool_reward_list[0] = 333333333333333333;
pool_reward_list[1] = 333333333333333333;
pool_reward_list[2] = 333333333333333333;
_updatePoolChances(0, 500000000000000000);
_updatePoolChances(1, 300000000000000000);
_updatePoolChances(2, 200000000000000000);
// per session duration 7 day
session_minute = 10080;
session_id = 2;
// ticket price (0.2 ETH)
eth_per_ticket = 200000000000000000;
// payment received distribution (remaining 10% will for utility)
rate_buyback = 700000000000000000;
rate_dev = 200000000000000000;
// penalty setting (30%, base lock up to 30 day)
rate_penalty = 300000000000000000;
penalty_base_minute = 43200;
// contract linking
tube = 0xdA86006036540822e0cd2861dBd2fD7FF9CAA0e8;
tube_chief = 0x5fe65B1172E148d1Ac4F44fFc4777c2D4731ee8f;
dev = 0xAd451FBEaee85D370ca953D2020bb0480c2Cfc45;
buyback = 0x702b11a838429Edca4Ea0e80c596501F1a4F4c28;
utility = 0x4679025788c92187d44BdA852e9fF97229e3109b;
uniswap_router = 0x37D7f26405103C9Bc9D8F9352Cf32C5b655CBe02;
signer = 0xd916731C0063E0c8D93552bE0a021c9Ae15ff183;
// permission
access_permission[msg.sender] = true;
}
/*
* user purchase ticket and join current session jackpot
* @params tvl - input from front end with signature validation
*/
function purchaseTicket(uint _tvl, uint counter, bytes memory signature) public payable {
require(!session[session_id].deposit_paused, "deposit paused");
require(session[session_id].end_timestamp > block.timestamp, "jackpot ended");
require(msg.value == eth_per_ticket, "invalid payment");
require(counter > user_info[msg.sender].purchase_counter, 'EXPIRED COUNTER'); // prevent replay attack
require(_verifySign(signer, msg.sender, _tvl, counter, signature), "invalid signature");
// replace user purchase counter number
user_info[msg.sender].purchase_counter = counter;
// uniform lowest bound number is 0
// result format is in array index so max upper bound number need to minus 1
uint mul_index = UniformRandomNumber.uniform(_rngSeed(), multiplier_list.length);
uint pool_index = _pickPoolIndex();
// tvl should source from maximizer pool. (LP staked value * weightage)
uint actual_weightage = _tvl.mul(multiplier_list[mul_index], DECIMAL);
pool[session_id][pool_index].total_weightage = pool[session_id][pool_index].total_weightage.add(actual_weightage);
user_pool[msg.sender][session_id][pool_index].weightage = user_pool[msg.sender][session_id][pool_index].weightage.add(actual_weightage);
user_pool[msg.sender][session_id][pool_index].num_of_ticket = user_pool[msg.sender][session_id][pool_index].num_of_ticket.add(1);
user_session[msg.sender][session_id].tvl = user_session[msg.sender][session_id].tvl.add(_tvl);
user_session[msg.sender][session_id].num_of_ticket = user_session[msg.sender][session_id].num_of_ticket.add(1);
user_session[msg.sender][session_id].has_purchased = true;
if (swap_payment) {
_paymentDistributionDex(msg.value);
} else {
_paymentDistributionBuyback(msg.value);
}
// withdrawal penalty set once
// -> block.timestamp + 30 day + session(end - now)
if (user_session[msg.sender][session_id].penalty_until_timestamp <= 0) {
user_session[msg.sender][session_id].first_deposit_timestamp = block.timestamp;
user_session[msg.sender][session_id].penalty_until_timestamp = session[session_id].end_timestamp.add(penalty_base_minute * 60);
}
emit PurchaseTicket(session_id, multiplier_list[mul_index], pool_index, eth_per_ticket, _tvl, actual_weightage, block.timestamp, msg.sender);
}
/*
* user claim reward by session
*/
function claimReward(uint _session_id) public {
require(session[_session_id].can_claim, "claim not enable");
require(!session[_session_id].claim_paused, "claim paused");
require(!user_session[msg.sender][_session_id].has_claimed, "reward claimed");
uint claimable = 0;
for (uint pcategory = 0; pcategory < category_size; pcategory++) {
claimable = claimable.add(_userReward(msg.sender, _session_id, pcategory, session[_session_id].total_reward));
}
uint actual_claimable = _rewardAfterPenalty(msg.sender, claimable, _session_id);
uint penalty_amount = claimable.sub(actual_claimable);
// gas saving. transfer penalty amount for buyback
if (claimable != actual_claimable) {
TransferHelper.safeTransfer(tube, buyback, penalty_amount);
}
TransferHelper.safeTransfer(tube, msg.sender, actual_claimable);
user_session[msg.sender][_session_id].has_claimed = true;
emit Claim(_session_id, claimable, actual_claimable, penalty_amount, block.timestamp, msg.sender);
}
/*
* get current session ended
*/
function getCurrentSessionEnded() public view returns(bool) {
return (session[session_id].end_timestamp <= block.timestamp);
}
/*
* get user in pool detail via pool category
*/
function getUserPoolInfo(address _address, uint _session_id, uint _pool_category) public view returns(uint, uint, bool) {
return (
user_pool[_address][_session_id][_pool_category].weightage,
user_pool[_address][_session_id][_pool_category].num_of_ticket,
user_pool[_address][_session_id][_pool_category].claimed
);
}
/*
* get user information
*/
function getUserInfo(address _address) public view returns(uint) {
return (user_info[_address].purchase_counter);
}
/*
* get user in the session
*/
function getUserSessionInfo(address _address, uint _session_id) public view returns(uint, uint, bool, bool, uint, uint) {
return (
user_session[_address][_session_id].tvl,
user_session[_address][_session_id].num_of_ticket,
user_session[_address][_session_id].has_purchased,
user_session[_address][_session_id].has_claimed,
user_session[_address][_session_id].first_deposit_timestamp,
user_session[_address][_session_id].penalty_until_timestamp
);
}
/*
* get user has participant on current jackpot session or not
*/
function getCurrentSessionJoined(address _address) public view returns (bool) {
return user_session[_address][session_id].has_purchased;
}
/*
* get pool info
*/
function getPool(uint _session_id, uint _pool_category) public view returns(uint, uint) {
return (
pool[_session_id][_pool_category].total_weightage,
pool[_session_id][_pool_category].rate_reward
);
}
/*
* get session info
*/
function getSession(uint _session_id) public view returns(uint, uint, uint, bool, bool, bool) {
return (
session[_session_id].total_reward,
session[_session_id].start_timestamp,
session[_session_id].end_timestamp,
session[_session_id].deposit_paused,
session[_session_id].can_claim,
session[_session_id].claim_paused
);
}
/*
* get all pool reward by session ID
*/
function getPoolRewardBySession(uint _session_id) public view returns(uint, uint[] memory) {
uint reward_tube = 0;
if (_session_id == session_id) {
reward_tube = reward_tube.add(ITubeChief(tube_chief).getJackpotReward());
}
// local reward + pending tube chief reward
uint reward_atm = reward_tube.add(session[_session_id].total_reward);
uint[] memory pool_rewards = new uint[](category_size);
for (uint pcategory = 0; pcategory < category_size; pcategory++) {
pool_rewards[pcategory] = reward_atm.mul(pool[_session_id][pcategory].rate_reward, DECIMAL);
}
return (category_size, pool_rewards);
}
/*
* get user reward by session ID
*/
function getUserRewardBySession(address _address, uint _session_id) public view returns (uint, uint) {
uint reward_atm = session[_session_id].total_reward;
if (_session_id == session_id) {
reward_atm = reward_atm.add(ITubeChief(tube_chief).getJackpotReward());
}
uint claimable = 0;
for (uint pcategory = 0; pcategory < category_size; pcategory++) {
claimable = claimable.add(_userReward(_address, _session_id, pcategory, reward_atm));
}
uint max_claimable = claimable;
claimable = _rewardAfterPenalty(_address, claimable, _session_id);
return (max_claimable, claimable);
}
/*
* start jackpot new session
*/
function initPot() public hasAccessPermission {
_startPot();
}
/*
* update ticket prcing
*/
function updateEthPerTicket(uint _eth_per_ticket) public hasAccessPermission {
eth_per_ticket = _eth_per_ticket;
emit UpdateEthPerTicket(eth_per_ticket);
}
/*
* update jackpot control toggle by session ID
*/
function updateToggleBySession(uint _session_id, bool _deposit_paused, bool _claim_paused) public hasAccessPermission {
session[_session_id].deposit_paused = _deposit_paused;
session[_session_id].claim_paused = _claim_paused;
emit UpdateToggleBySession(_session_id, _deposit_paused, _claim_paused);
}
/*
* update current session end timestamp
*/
function updateSessionEndTimestamp(uint end_timestamp) public hasAccessPermission {
session[session_id].end_timestamp = end_timestamp;
emit UpdateSessionEndTimestamp(end_timestamp);
}
/*
* resetup pool category size and reward distribution
* XX update will reflect immediately
*/
function updateMultiplierList(uint[] memory _multiplier_list) public hasAccessPermission {
multiplier_list = _multiplier_list;
emit UpdateMultiplierList(multiplier_list);
}
/*
* update penatly setting
*/
function updatePenaltySetting(uint _rate_penalty, uint _penalty_base_minute) public hasAccessPermission {
rate_penalty = _rate_penalty;
penalty_base_minute = _penalty_base_minute;
emit UpdatePenaltySetting(rate_penalty, penalty_base_minute);
}
/*
* update payment rate distribution to each sectors
* (!) rate utility will auto result in (1 - rate_buyback - rate_dev)
*/
function updatePaymentRateDistribution(uint _rate_buyback, uint _rate_dev) public hasAccessPermission {
rate_buyback = _rate_buyback;
rate_dev = _rate_dev;
emit UpdatePaymentRateDistribution(rate_buyback, rate_dev);
}
/*
* update contract addresses
*/
function updateContracts(
address _tube,
address _tube_chief,
address _buyback,
address _dev,
address _utility,
address _uniswap_router,
address _signer
) public hasAccessPermission {
tube = _tube;
tube_chief = _tube_chief;
buyback = _buyback;
dev = _dev;
utility = _utility;
uniswap_router = _uniswap_router;
signer = _signer;
emit UpdateContracts(tube, tube_chief, buyback, dev, utility, uniswap_router, signer);
}
/*
* resetup pool category size and reward distribution
* @param new_max_category - total pool size
* @param reward_rates - each pool reward distribution rate
* @param chance_rates - change rate of user will enter the pool
* XX pool reward rate update will reflect on next session
* XX pool chance rate update will reflect now
* XX may incur high gas fee
*/
function updatePoolCategory(uint new_max_category, uint[] memory reward_rates, uint[] memory chance_rates) public hasAccessPermission {
require(reward_rates.length == category_size, "invalid input size");
// remove old setting
for (uint i = 0; i < category_size; i++) {
delete pool_reward_list[i];
delete pool_chances[i];
_updatePoolChances(i, 0);
}
// add new setting
for (uint i = 0; i < new_max_category; i++) {
pool_reward_list[i] = reward_rates[i];
_updatePoolChances(i, chance_rates[i]);
}
category_size = new_max_category;
emit UpdatePoolCategory(new_max_category, reward_rates, chance_rates);
}
/*
* update stop next session status
*/
function updateStopNextSession(bool status) public hasAccessPermission {
stop_next_session = status;
emit UpdateStopNextSession(status);
}
/*
* update jackpot duration
* XX update reflect on next session
*/
function updateSessionMinute(uint minute) public hasAccessPermission {
session_minute = minute;
emit UpdateSessionMinute(minute);
}
/*
* update swap payment method
*/
function updateSwapPayment(bool status) public hasAccessPermission {
swap_payment = status;
emit UpdateSwapPayment(status);
}
/*
* update access permission
*/
function updateAccessPermission(address _address, bool status) public onlyOwner {
access_permission[_address] = status;
emit UpdateAccessPermission(_address, status);
}
/*
* conclude current session and start new session
* - transferJackpot
* - completePot
*/
function completePot() public hasAccessPermission {
require(session[session_id].end_timestamp <= block.timestamp, "session not end");
/*
* 1. main contract will transfer TUBE to this contract
* 2. update the total reward amount for current session
*/
uint conclude_session = session_id;
uint reward_amount = ITubeChief(tube_chief).transferJackpotReward();
session[conclude_session].total_reward = session[conclude_session].total_reward.add(reward_amount);
session[conclude_session].can_claim = true;
session_id = session_id.add(1);
if (!stop_next_session) {
_startPot();
}
// if pool weightage is empty, transfer pool reward to buyback
for (uint pcategory = 0; pcategory < category_size; pcategory++) {
if (pool[conclude_session][pcategory].total_weightage > 0) {
continue;
}
uint amount = session[conclude_session].total_reward.mul(pool[conclude_session][pcategory].rate_reward, DECIMAL);
TransferHelper.safeTransfer(tube, buyback, amount);
}
emit CompletePot(conclude_session, reward_amount, block.timestamp);
}
/*
* transfer ownership. proceed wisely. only owner executable
*/
function transferOwner(address new_owner) public onlyOwner {
emit TransferOwner(owner, new_owner);
owner = new_owner;
}
/*
* emergency collect token from the contract. only owner executable
*/
function emergencyCollectToken(address token, uint amount) public onlyOwner {
TransferHelper.safeTransfer(token, owner, amount);
}
/*
* emergency collect eth from the contract. only owner executable
*/
function emergencyCollectEth(uint amount) public onlyOwner {
address payable owner_address = payable(owner);
TransferHelper.safeTransferETH(owner_address, amount);
}
function _userReward(address _address, uint _session_id, uint _pool_category, uint _total_reward) internal view returns (uint) {
// (Z / Total Z of all users) x P1 / P2 / P3 TUBE2 = X amount of reward
uint total_weight = pool[_session_id][_pool_category].total_weightage;
if (total_weight <= 0 || user_pool[_address][_session_id][_pool_category].claimed) {
return 0;
}
uint user_weight = user_pool[_address][_session_id][_pool_category].weightage;
uint rate = pool[_session_id][_pool_category].rate_reward;
return user_weight.div(total_weight, DECIMAL).mul(_total_reward, DECIMAL).mul(rate, DECIMAL);
}
function _startPot() internal {
session[session_id].start_timestamp = block.timestamp;
session[session_id].end_timestamp = block.timestamp.add(session_minute * 60);
// init P1, P2, P3
for (uint i = 0; i < category_size; i++) {
pool[session_id][i].rate_reward = pool_reward_list[i];
}
}
function _paymentDistributionDex(uint amount) internal {
uint buyback_amount = amount.mul(rate_buyback, DECIMAL);
uint dev_amount = amount.mul(rate_dev, DECIMAL);
uint utility_amount = amount.sub(buyback_amount).sub(dev_amount);
uint tube_swapped = _swapEthToTUBE(buyback_amount);
TransferHelper.safeTransfer(tube, address(0), tube_swapped);
TransferHelper.safeTransferETH(dev, dev_amount);
TransferHelper.safeTransferETH(utility, utility_amount);
}
function _paymentDistributionBuyback(uint amount) internal {
/*
* distribution plan (initial)
* buyback - 70% (buyback)
* masternode - 20% (dev)
* leaderboard - 10% (utility)
*/
uint buyback_amount = amount.mul(rate_buyback, DECIMAL);
uint dev_amount = amount.mul(rate_dev, DECIMAL);
uint utility_amount = amount.sub(buyback_amount).sub(dev_amount);
TransferHelper.safeTransferETH(buyback, buyback_amount);
TransferHelper.safeTransferETH(dev, dev_amount);
TransferHelper.safeTransferETH(utility, utility_amount);
}
function _rngSeed() internal returns (uint) {
uint seed = uint256(keccak256(abi.encode(block.number, msg.sender, preseed)));
preseed = seed;
return seed;
}
function _swapEthToTUBE(uint amount) internal returns (uint) {
require(amount > 0, "empty swap amount");
TransferHelper.safeApprove(tube, uniswap_router, amount);
address[] memory path = new address[](2);
path[0] = IUniswapV2Router02(uniswap_router).WETH();
path[1] = tube;
// lower down the receive expectation to prevent high failure
uint buffer_rate = 980000000000000000;
uint deadline = block.timestamp.add(60);
uint[] memory amount_out_min = new uint[](2);
amount_out_min = IUniswapV2Router02(uniswap_router).getAmountsOut(amount, path);
amount_out_min[1] = amount_out_min[1].mul(buffer_rate, DECIMAL);
uint[] memory swapped = IUniswapV2Router02(uniswap_router).swapExactETHForTokens{ value: amount }(amount_out_min[1], path, address(this), deadline);
return swapped[1];
}
function _rewardAfterPenalty(address _address, uint reward_amount, uint _session_id) internal view returns (uint) {
/*
* calculate the reward amount after penalty condition
*
* 1. get the withdrawable amount
* 2. get the withdraw penalty rate
* 3. get time ratio: (userPenaltyEndTime - now) / (penalty_base_minute * 60)
* 4. result = [full reward] x [penalty rate] x [time ratio]
*/
if (user_session[_address][_session_id].penalty_until_timestamp >= block.timestamp) {
uint end = user_session[_address][_session_id].penalty_until_timestamp;
uint diff_now = end.sub(block.timestamp);
uint time_ratio = diff_now.div(penalty_base_minute * 60, DECIMAL);
uint penalty_amount = reward_amount.mul(rate_penalty, DECIMAL).mul(time_ratio, DECIMAL);
reward_amount = reward_amount.sub(penalty_amount);
}
return reward_amount;
}
function _updatePoolChances(uint pool_index, uint chance_rate) internal {
pool_chances[pool_index] = chance_rate;
sortitionSumTrees.set(TREE_KEY, chance_rate, bytes32(uint256(pool_index)));
}
function _pickPoolIndex() internal returns (uint) {
return uint256(sortitionSumTrees.draw(TREE_KEY, _rngSeed()));
}
/*
* VerifySignature
*/
function _getMessageHash(address buyer, uint tvl, uint counter) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(buyer, tvl, counter));
}
function _getEthSignedMessageHash(bytes32 _messageHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash));
}
function _verifySign(address _signer, address buyer, uint tvl, uint counter, bytes memory signature) internal pure returns (bool) {
bytes32 messageHash = _getMessageHash(buyer, tvl, counter);
bytes32 ethSignedMessageHash = _getEthSignedMessageHash(messageHash);
return _recoverSigner(ethSignedMessageHash, signature) == _signer;
}
function _recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) internal pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function _splitSignature(bytes memory sig) internal pure returns (bytes32 r, bytes32 s, uint8 v) {
require(sig.length == 65, "invalid signature length");
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
}
}
interface ITubeChief {
function getJackpotReward() external view returns (uint);
function transferJackpotReward() external returns (uint);
} | get user in the session/ | function getUserSessionInfo(address _address, uint _session_id) public view returns(uint, uint, bool, bool, uint, uint) {
return (
user_session[_address][_session_id].tvl,
user_session[_address][_session_id].num_of_ticket,
user_session[_address][_session_id].has_purchased,
user_session[_address][_session_id].has_claimed,
user_session[_address][_session_id].first_deposit_timestamp,
user_session[_address][_session_id].penalty_until_timestamp
);
}
| 12,986,286 |
pragma solidity ^0.5.0;
library SafeMath{
/**
* Returns the addition of two unsigned integers, reverting on
* overflow.
*
* - 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;
}
/**
* Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* - 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;
}
}
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner,"ERC20: Required Owner !");
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require (newOwner != address(0),"ERC20 New Owner cannot be zero address");
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external ; }
contract TOKENERC20 {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
/* This generates a public event on the blockchain that will notify clients */
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) private _allowance;
mapping (address => bool) public LockList;
mapping (address => uint256) public LockedTokens;
// 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);
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint256 _value) internal {
uint256 stage;
require(_from != address(0), "ERC20: transfer from the zero address");
require(_to != address(0), "ERC20: transfer to the zero address"); // Prevent transfer to 0x0 address. Use burn() instead
require (LockList[msg.sender] == false,"ERC20: Caller Locked !"); // Check if msg.sender is locked or not
require (LockList[_from] == false, "ERC20: Sender Locked !");
require (LockList[_to] == false,"ERC20: Receipient Locked !");
// Check if sender balance is locked
stage=balanceOf[_from].sub(_value, "ERC20: transfer amount exceeds balance");
require (stage >= LockedTokens[_from],"ERC20: transfer amount exceeds Senders Locked Amount");
//Deduct and add balance
balanceOf[_from]=stage;
balanceOf[_to]=balanceOf[_to].add(_value,"ERC20: Addition overflow");
//emit Transfer event
emit Transfer(_from, _to, _value);
}
/**
* Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address _spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
_allowance[owner][_spender] = amount;
emit Approval(owner, _spender, amount);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns(bool){
_transfer(msg.sender, _to, _value);
return true;
}
function burn(uint256 _value) public returns(bool){
require (LockList[msg.sender] == false,"ERC20: User Locked !");
uint256 stage;
stage=balanceOf[msg.sender].sub(_value, "ERC20: transfer amount exceeds balance");
require (stage >= LockedTokens[msg.sender],"ERC20: transfer amount exceeds Senders Locked Amount");
balanceOf[msg.sender]=balanceOf[msg.sender].sub(_value,"ERC20: Burn amount exceeds balance.");
totalSupply=totalSupply.sub(_value,"ERC20: Burn amount exceeds total supply");
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
return true;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param Account address
*
* @param _value the amount of money to burn
*
* Safely check if total supply is not overdrawn
*/
function burnFrom(address Account, uint256 _value) public returns (bool success) {
require (LockList[msg.sender] == false,"ERC20: User Locked !");
require (LockList[Account] == false,"ERC20: Owner Locked !");
uint256 stage;
require(Account != address(0), "ERC20: Burn from the zero address");
//Safely substract amount to be burned from callers allowance
_approve(Account, msg.sender, _allowance[Account][msg.sender].sub(_value,"ERC20: burn amount exceeds allowance"));
//Do not allow burn if Accounts tokens are locked.
stage=balanceOf[Account].sub(_value,"ERC20: Transfer amount exceeds allowance");
require(stage>=LockedTokens[Account],"ERC20: Burn amount exceeds accounts locked amount");
balanceOf[Account] =stage ; // Subtract from the sender
//Deduct burn amount from totalSupply
totalSupply=totalSupply.sub(_value,"ERC20: Burn Amount exceeds totalSupply");
emit Burn(Account, _value);
emit Transfer(Account, address(0), _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
_transfer(_from, _to, _value);
_approve(_from,msg.sender,_allowance[_from][msg.sender].sub(_value,"ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
* Emits Approval Event
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
uint256 unapprovbal;
// Do not allow approval if amount exceeds locked amount
unapprovbal=balanceOf[msg.sender].sub(_value,"ERC20: Allowance exceeds balance of approver");
require(unapprovbal>=LockedTokens[msg.sender],"ERC20: Approval amount exceeds locked amount ");
_allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function allowance(address _owner,address _spender) public view returns(uint256){
return _allowance[_owner][_spender];
}
}
contract StreamCoin is owned, TOKENERC20 {
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor () TOKENERC20(
100000000000 * 1 ** uint256(decimals),
"Stream Coin",
"STRM") public {
}
/**
* User Lock
*
* @param Account the address of account to lock for transaction
*
* @param mode true or false for lock mode
*
*/
function UserLock(address Account, bool mode) onlyOwner public {
LockList[Account] = mode;
}
/**
* Lock tokens
*
* @param Account the address of account to lock
*
* @param amount the amount of money to lock
*
*
*/
function LockTokens(address Account, uint256 amount) onlyOwner public{
LockedTokens[Account]=amount;
}
function UnLockTokens(address Account) onlyOwner public{
LockedTokens[Account]=0;
}
} | Transfer tokens from other address Send `_value` tokens to `_to` on behalf of `_from` _from The address of the sender _to The address of the recipient _value the amount to send/ | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
_transfer(_from, _to, _value);
_approve(_from,msg.sender,_allowance[_from][msg.sender].sub(_value,"ERC20: transfer amount exceeds allowance"));
return true;
}
| 1,290,592 |
/**
*Submitted for verification at Etherscan.io on 2019-09-27
*/
pragma solidity >=0.5.1;
contract owned {
function bug_intou24(uint8 p_intou24) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou24; // overflow bug
}
address public owner;
constructor() public {
owner = msg.sender;
}
function bug_intou11() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
mapping(address => uint) public lockTime_intou1;
function increaseLockTime_intou1(uint _secondsToIncrease) public {
lockTime_intou1[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_ovrflow1() public {
require(now > lockTime_intou1[msg.sender]);
uint transferValue_intou1 = 10;
msg.sender.transfer(transferValue_intou1);
}
}
contract tokenRecipient {
function bug_intou39() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
event receivedEther(address sender, uint amount);
function bug_intou36(uint8 p_intou36) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou36; // overflow bug
}
event receivedTokens(address _from, uint256 _value, address _token, bytes _extraData);
function receiveApproval(address _from, uint256 _value, address _token, bytes memory _extraData) public {
Token t = Token(_token);
require(t.transferFrom(_from, address(this), _value));
emit receivedTokens(_from, _value, _token, _extraData);
}
mapping(address => uint) balances_intou2;
function transfer_undrflow2(address _to, uint _value) public returns (bool) {
require(balances_intou2[msg.sender] - _value >= 0); //bug
balances_intou2[msg.sender] -= _value; //bug
balances_intou2[_to] += _value; //bug
return true;
}
function () payable external {
emit receivedEther(msg.sender, msg.value);
}
mapping(address => uint) public lockTime_intou17;
function increaseLockTime_intou17(uint _secondsToIncrease) public {
lockTime_intou17[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou17() public {
require(now > lockTime_intou17[msg.sender]);
uint transferValue_intou17 = 10;
msg.sender.transfer(transferValue_intou17);
}
}
contract Token {
function totalSupply() public view returns (uint256);
mapping(address => uint) public lockTime_intou37;
function increaseLockTime_intou37(uint _secondsToIncrease) public {
lockTime_intou37[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou37() public {
require(now > lockTime_intou37[msg.sender]);
uint transferValue_intou37 = 10;
msg.sender.transfer(transferValue_intou37);
}
function actualBalanceOf(address _owner) public view returns (uint256 balance);
function bug_intou3() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
mapping(address => uint) public lockTime_intou9;
function increaseLockTime_intou9(uint _secondsToIncrease) public {
lockTime_intou9[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou9() public {
require(now > lockTime_intou9[msg.sender]);
uint transferValue_intou9 = 10;
msg.sender.transfer(transferValue_intou9);
}
function renounceOwnership() public;
mapping(address => uint) public lockTime_intou25;
function increaseLockTime_intou25(uint _secondsToIncrease) public {
lockTime_intou25[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou25() public {
require(now > lockTime_intou25[msg.sender]);
uint transferValue_intou25 = 10;
msg.sender.transfer(transferValue_intou25);
}
function transferOwnership(address _newOwner) public;
function bug_intou19() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function pause() public;
mapping(address => uint) balances_intou26;
function transfer_intou26(address _to, uint _value) public returns (bool) {
require(balances_intou26[msg.sender] - _value >= 0); //bug
balances_intou26[msg.sender] -= _value; //bug
balances_intou26[_to] += _value; //bug
return true;
}
function unpause() public;
function bug_intou20(uint8 p_intou20) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou20; // overflow bug
}
}
/**
* @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, "Safe mul error");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "Safe div error");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "Safe sub error");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "Safe add error");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Safe mod error");
return a % b;
}
}
/**
* The Mindsync Platform contract
*/
contract MindsyncPlatform is owned, tokenRecipient {
using SafeMath for uint256;
mapping(address => uint) public lockTime_intou5;
function increaseLockTime_intou5(uint _secondsToIncrease) public {
lockTime_intou5[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou5() public {
require(now > lockTime_intou5[msg.sender]);
uint transferValue_intou5 = 10;
msg.sender.transfer(transferValue_intou5);
}
uint public minimumQuorum;
function bug_intou15() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
uint public minimumTokensToVote;
function bug_intou28(uint8 p_intou28) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou28; // overflow bug
}
uint public debatingPeriodInMinutes;
mapping(address => uint) balances_intou34;
function transfer_intou34(address _to, uint _value) public returns (bool) {
require(balances_intou34[msg.sender] - _value >= 0); //bug
balances_intou34[msg.sender] -= _value; //bug
balances_intou34[_to] += _value; //bug
return true;
}
Proposal[] public proposals;
mapping(address => uint) public lockTime_intou21;
function increaseLockTime_intou21(uint _secondsToIncrease) public {
lockTime_intou21[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou21() public {
require(now > lockTime_intou21[msg.sender]);
uint transferValue_intou21 = 10;
msg.sender.transfer(transferValue_intou21);
}
uint public numProposals;
mapping(address => uint) balances_intou10;
function transfer_intou10(address _to, uint _value) public returns (bool) {
require(balances_intou10[msg.sender] - _value >= 0); //bug
balances_intou10[msg.sender] -= _value; //bug
balances_intou10[_to] += _value; //bug
return true;
}
Token public tokenAddress;
mapping(address => uint) balances_intou22;
function transfer_intou22(address _to, uint _value) public returns (bool) {
require(balances_intou22[msg.sender] - _value >= 0); //bug
balances_intou22[msg.sender] -= _value; //bug
balances_intou22[_to] += _value; //bug
return true;
}
address chairmanAddress;
function bug_intou12(uint8 p_intou12) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou12; // overflow bug
}
bool public initialized = false;
function bug_intou35() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
event Initialized();
function bug_intou40(uint8 p_intou40) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou40; // overflow bug
}
event ProposalAdded(uint proposalID, address recipient, uint amount, string description);
mapping(address => uint) public lockTime_intou33;
function increaseLockTime_intou33(uint _secondsToIncrease) public {
lockTime_intou33[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou33() public {
require(now > lockTime_intou33[msg.sender]);
uint transferValue_intou33 = 10;
msg.sender.transfer(transferValue_intou33);
}
event Voted(uint proposalID, bool position, address voter);
function bug_intou27() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
event ProposalTallied(uint proposalID, uint result, uint quorum, bool active);
function bug_intou31() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
event ChangeOfRules(uint newMinimumTokensToVote, uint newMinimumQuorum, uint newDebatingPeriodInMinutes, address newTokenAddress, address newChairmanAddress);
mapping(address => uint) public lockTime_intou13;
function increaseLockTime_intou13(uint _secondsToIncrease) public {
lockTime_intou13[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou13() public {
require(now > lockTime_intou13[msg.sender]);
uint transferValue_intou13 = 10;
msg.sender.transfer(transferValue_intou13);
}
event ProposalSignedByChairman(uint proposalNumber, bool sign, address chairman);
struct Proposal {
address recipient;
uint amount;
string description;
bool signedByChairman;
uint minExecutionDate;
bool executed;
bool proposalPassed;
uint numberOfVotes;
bytes32 proposalHash;
Vote[] votes;
mapping (address => bool) voted;
}
struct Vote {
bool inSupport;
address voter;
}
// Modifier that allows only tokenholders with at least minimumTokensToVote tokens to vote and create new proposals
modifier onlyTokenholders {
require(tokenAddress.actualBalanceOf(msg.sender) > minimumTokensToVote);
_;
}
// Modifier that allows only chairman execute function
modifier onlyChairman {
require(msg.sender == chairmanAddress);
_;
}
/**
* Constructor
*
* First time rules setup
*/
constructor() payable public {
}
function bug_intou32(uint8 p_intou32) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou32; // overflow bug
}
/**
* Initialize contract
*
* @param _tokenAddress token address
* @param _minimumTokensToVote address can vote only if the number of tokens held by address exceed this number
* @param _minimumPercentToPassAVote proposal can vote only if the sum of tokens held by all voters exceed this number divided by 100 and muliplied by token total supply
* @param _minutesForDebate the minimum amount of delay between when a proposal is made and when it can be executed
*/
function init(Token _tokenAddress, address _chairmanAddress, uint _minimumTokensToVote, uint _minimumPercentToPassAVote, uint _minutesForDebate) onlyOwner public {
require(!initialized);
initialized = true;
changeVotingRules(_tokenAddress, _chairmanAddress, _minimumTokensToVote, _minimumPercentToPassAVote, _minutesForDebate);
emit Initialized();
}
mapping(address => uint) balances_intou38;
function transfer_intou38(address _to, uint _value) public returns (bool) {
require(balances_intou38[msg.sender] - _value >= 0); //bug
balances_intou38[msg.sender] -= _value; //bug
balances_intou38[_to] += _value; //bug
return true;
}
/**
* Change voting rules
*
* Make so that proposals need to be discussed for at least `minutesForDebate/60` hours
* and all voters combined must own more than `minimumPercentToPassAVote` multiplied by total supply tokens of `tokenAddress` to be executed
*
* @param _tokenAddress token address
* @param _minimumTokensToVote address can vote only if the number of tokens held by address exceed this number
* @param _minimumPercentToPassAVote proposal can vote only if the sum of tokens held by all voters exceed this number divided by 100 and muliplied by token total supply
* @param _minutesForDebate the minimum amount of delay between when a proposal is made and when it can be executed
*/
function changeVotingRules(Token _tokenAddress, address _chairmanAddress, uint _minimumTokensToVote, uint _minimumPercentToPassAVote, uint _minutesForDebate) onlyOwner public {
require(_chairmanAddress != address(0));
require(_minimumPercentToPassAVote <= 51);
tokenAddress = Token(_tokenAddress);
chairmanAddress = _chairmanAddress;
if (_minimumTokensToVote == 0 ) _minimumTokensToVote = 1;
minimumTokensToVote = _minimumTokensToVote;
if (_minimumPercentToPassAVote == 0 ) _minimumPercentToPassAVote = 51;
minimumQuorum = _minimumPercentToPassAVote;
debatingPeriodInMinutes = _minutesForDebate;
emit ChangeOfRules(_minimumTokensToVote, minimumQuorum, debatingPeriodInMinutes, address(tokenAddress), chairmanAddress);
}
function bug_intou4(uint8 p_intou4) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou4; // overflow bug
}
/**
* Add Proposal
*
* Propose to execute transaction
*
* @param destination is a transaction destination address
* @param weiAmount amount of wei
* @param transactionDescription Description of transaction
* @param transactionBytecode bytecode of transaction
*/
function newProposal(
address destination,
uint weiAmount,
string memory transactionDescription,
bytes memory transactionBytecode
)
onlyTokenholders public
returns (uint proposalID)
{
proposalID = proposals.length++;
Proposal storage p = proposals[proposalID];
p.recipient = destination;
p.signedByChairman = false;
p.amount = weiAmount;
p.description = transactionDescription;
p.proposalHash = keccak256(abi.encodePacked(destination, weiAmount, transactionBytecode));
p.minExecutionDate = now + debatingPeriodInMinutes * 1 minutes;
p.executed = false;
p.proposalPassed = false;
p.numberOfVotes = 0;
emit ProposalAdded(proposalID, destination, weiAmount, transactionDescription);
numProposals = proposalID+1;
return proposalID;
}
function bug_intou7() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
/**
* Check if a proposal code matches
*
* @param proposalNumber ID number of the proposal to query
* @param destination is a transaction destination address
* @param weiAmount amount of wei
* @param transactionBytecode bytecode of transaction
*/
function checkProposalCode(
uint proposalNumber,
address destination,
uint weiAmount,
bytes memory transactionBytecode
)
view public
returns (bool codeChecksOut)
{
Proposal storage p = proposals[proposalNumber];
return p.proposalHash == keccak256(abi.encodePacked(destination, weiAmount, transactionBytecode));
}
function bug_intou23() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
/**
* Sign a proposal
*
* Vote `supportsProposal? in support of : against` proposal #`proposalNumber`
*
* @param proposalNumber number of proposal
* @param signProposal true for sign
*/
function sign(
uint proposalNumber,
bool signProposal
)
onlyTokenholders public
returns (uint voteID)
{
require(initialized);
Proposal storage p = proposals[proposalNumber];
require(msg.sender == chairmanAddress);
require(signProposal == true);
p.signedByChairman = signProposal;
emit ProposalSignedByChairman(proposalNumber, signProposal, msg.sender);
return proposalNumber;
}
mapping(address => uint) balances_intou14;
function transfer_intou14(address _to, uint _value) public returns (bool) {
require(balances_intou14[msg.sender] - _value >= 0); //bug
balances_intou14[msg.sender] -= _value; //bug
balances_intou14[_to] += _value; //bug
return true;
}
/**
* Log a vote for a proposal
*
* Vote `supportsProposal? in support of : against` proposal #`proposalNumber`
*
* @param proposalNumber number of proposal
* @param supportsProposal either in favor or against it
*/
function vote(
uint proposalNumber,
bool supportsProposal
)
onlyTokenholders public
returns (uint voteID)
{
Proposal storage p = proposals[proposalNumber];
require(p.voted[msg.sender] != true);
voteID = p.votes.length++;
p.votes[voteID] = Vote({inSupport: supportsProposal, voter: msg.sender});
p.voted[msg.sender] = true;
p.numberOfVotes = voteID +1;
emit Voted(proposalNumber, supportsProposal, msg.sender);
return voteID;
}
mapping(address => uint) balances_intou30;
function transfer_intou30(address _to, uint _value) public returns (bool) {
require(balances_intou30[msg.sender] - _value >= 0); //bug
balances_intou30[msg.sender] -= _value; //bug
balances_intou30[_to] += _value; //bug
return true;
}
/**
* Finish vote
*
* Count the votes proposal #`proposalNumber` and execute it if approved
*
* @param proposalNumber proposal number
* @param transactionBytecode optional: if the transaction contained a bytecode, you need to send it
*/
function executeProposal(uint proposalNumber, bytes memory transactionBytecode) public {
Proposal storage p = proposals[proposalNumber];
require(initialized);
require(now > p.minExecutionDate // If it is past the voting deadline
&& !p.executed // and it has not already been executed
&& p.proposalHash == keccak256(abi.encodePacked(p.recipient, p.amount, transactionBytecode))); // and the supplied code matches the proposal...
// ...then tally the results
uint quorum = 0;
uint yea = 0;
uint nay = 0;
for (uint i = 0; i < p.votes.length; ++i) {
Vote storage v = p.votes[i];
uint voteWeight = tokenAddress.actualBalanceOf(v.voter);
quorum += voteWeight;
if (v.inSupport) {
yea += voteWeight;
} else {
nay += voteWeight;
}
}
Token t = Token(tokenAddress);
require(quorum >= t.totalSupply().mul(minimumQuorum).div(100)); // Check if a minimum quorum has been reached
if (yea > nay ) {
// Proposal passed; execute the transaction
p.executed = true;
(bool success, ) = p.recipient.call.value(p.amount)(transactionBytecode);
require(success);
p.proposalPassed = true;
} else {
// Proposal failed
p.proposalPassed = false;
}
// Fire Events
emit ProposalTallied(proposalNumber, yea - nay, quorum, p.proposalPassed);
}
function bug_intou8(uint8 p_intou8) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou8; // overflow bug
}
}
| Check if a proposal code matches proposalNumber ID number of the proposal to query destination is a transaction destination address weiAmount amount of wei transactionBytecode bytecode of transaction/ | function checkProposalCode(
uint proposalNumber,
address destination,
uint weiAmount,
bytes memory transactionBytecode
)
view public
returns (bool codeChecksOut)
{
Proposal storage p = proposals[proposalNumber];
return p.proposalHash == keccak256(abi.encodePacked(destination, weiAmount, transactionBytecode));
}
| 13,111,748 |
/**
*Submitted for verification at Etherscan.io on 2022-02-19
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
// File: soulswap-core/contracts/interfaces/IERC20.sol
interface IERC20 {
// events
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed owner, address indexed spender, uint value);
// token details
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
// address details
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function getOwner() external view returns (address);
// token actions
function approve(address spender, uint value) external returns (bool);
function transfer(address recipient, uint value) external returns (bool);
function transferFrom(address sender, address recipient, uint value) external returns (bool);
}
// File: contracts/interfaces/ISoulSwapRouter01.sol
pragma solidity >=0.6.2;
interface ISoulSwapRouter01 {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external payable returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external payable returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: contracts/interfaces/ISoulSwapRouter02.sol
pragma solidity >=0.6.2;
interface ISoulSwapRouter02 is ISoulSwapRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: contracts/interfaces/ISoulSwapFactory.sol
pragma solidity >=0.5.0;
interface ISoulSwapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
event SetFeeTo(address indexed user, address indexed _feeTo);
event SetMigrator(address indexed user, address indexed _migrator);
event FeeToSetter(address indexed user, address indexed _feeToSetter);
function feeTo() external view returns (address _feeTo);
function feeToSetter() external view returns (address _feeToSetter);
function migrator() external view returns (address _migrator);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setMigrator(address) external;
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/interfaces/IWETH.sol
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// File: soulswap-lib/contracts/libraries/TransferHelper.sol
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// File: soulswap-core/contracts/interfaces/ISoulSwapPair.sol
pragma solidity >=0.5.0;
interface ISoulSwapPair {
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;
}
// File: soulswap-core/contracts/libraries/SafeMath.sol
pragma solidity >=0.5.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, 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;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/libraries/SoulSwapLibrary.sol
pragma solidity >=0.5.0;
library SoulSwapLibrary {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'SoulSwapLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'SoulSwapLibrary: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'2d2a1a6740caa0c2e9da78939c9ca5c8ff259bf16e2b9dcbbec714720587df90' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
pairFor(factory, tokenA, tokenB);
(uint reserve0, uint reserve1,) = ISoulSwapPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'SoulSwapLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'SoulSwapLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(998);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'SoulSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SoulSwapLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(998);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SoulSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(
path.length >= 2, 'SoulSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File: contracts/SoulSwapRouter.sol
pragma solidity >=0.6.6;
contract SoulSwapRouter is ISoulSwapRouter02 {
using SafeMath for uint256;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "SoulSwapRouter: EXPIRED");
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
) internal virtual returns (uint256 amountA, uint256 amountB) {
// create the pair if it doesn't exist yet
if (ISoulSwapFactory(factory).getPair(tokenA, tokenB) == address(0)) {
ISoulSwapFactory(factory).createPair(tokenA, tokenB);
}
(uint256 reserveA, uint256 reserveB) =
SoulSwapLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal =
SoulSwapLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(
amountBOptimal >= amountBMin,
"SoulSwapRouter: INSUFFICIENT_B_AMOUNT"
);
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal =
SoulSwapLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(
amountAOptimal >= amountAMin,
"SoulSwapRouter: INSUFFICIENT_A_AMOUNT"
);
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
(amountA, amountB) = _addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin
);
address pair = SoulSwapLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = ISoulSwapPair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = SoulSwapLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = ISoulSwapPair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH)
TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountA, uint256 amountB) {
address pair = SoulSwapLibrary.pairFor(factory, tokenA, tokenB);
ISoulSwapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint256 amount0, uint256 amount1) = ISoulSwapPair(pair).burn(to);
(address token0, ) = SoulSwapLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0
? (amount0, amount1)
: (amount1, amount0);
require(amountA >= amountAMin, "SoulSwapRouter: INSUFFICIENT_A_AMOUNT");
require(amountB >= amountBMin, "SoulSwapRouter: INSUFFICIENT_B_AMOUNT");
}
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountToken, uint256 amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountA, uint256 amountB) {
address pair = SoulSwapLibrary.pairFor(factory, tokenA, tokenB);
uint256 value = approveMax ? uint256(-1) : liquidity;
ISoulSwapPair(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
(amountA, amountB) = removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
}
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
)
external virtual override returns (uint256 amountToken, uint256 amountETH) {
address pair = SoulSwapLibrary.pairFor(factory, token, WETH);
uint256 value = approveMax ? uint256(-1) : liquidity;
ISoulSwapPair(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
(amountToken, amountETH) = removeLiquidityETH(
token,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(
token,
to,
IERC20(token).balanceOf(address(this))
);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountETH) {
address pair = SoulSwapLibrary.pairFor(factory, token, WETH);
uint256 value = approveMax ? uint256(-1) : liquidity;
ISoulSwapPair(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = SoulSwapLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to =
i < path.length - 2
? SoulSwapLibrary.pairFor(factory, output, path[i + 2])
: _to;
ISoulSwapPair(SoulSwapLibrary.pairFor(factory, input, output)).swap(
amount0Out,
amount1Out,
to,
new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
amounts = SoulSwapLibrary.getAmountsOut(factory, amountIn, path);
require( amounts[amounts.length - 1] >= amountOutMin,
"SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
amounts = SoulSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, "SoulSwapRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == WETH, "SoulSwapRouter: INVALID_PATH");
amounts = SoulSwapLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == WETH, "SoulSwapRouter: INVALID_PATH");
amounts = SoulSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, "SoulSwapRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == WETH, "SoulSwapRouter: INVALID_PATH");
amounts = SoulSwapLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == WETH, "SoulSwapRouter: INVALID_PATH");
amounts = SoulSwapLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, "SoulSwapRouter: EXCESSIVE_INPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(SoulSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0])
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = SoulSwapLibrary.sortTokens(input, output);
ISoulSwapPair pair = ISoulSwapPair(SoulSwapLibrary.pairFor(factory, input, output));
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) =
input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(
reserveInput
);
amountOutput = SoulSwapLibrary.getAmountOut(
amountInput,
reserveInput,
reserveOutput
);
}
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to =
i < path.length - 2
? SoulSwapLibrary.pairFor(factory, output, path[i + 2])
: _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amountIn
);
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
"SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) {
require(path[0] == WETH, "SoulSwapRouter: INVALID_PATH");
uint256 amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(SoulSwapLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint256 balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
"SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
require(path[path.length - 1] == WETH, "SoulSwapRouter: INVALID_PATH");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SoulSwapLibrary.pairFor(factory, path[0], path[1]),
amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint256 amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, "SoulSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) public pure virtual override returns (uint256 amountB) {
return SoulSwapLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountOut) {
return SoulSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountIn) {
return SoulSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint256 amountIn, address[] memory path) public view virtual override
returns (uint256[] memory amounts) {
return SoulSwapLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint256 amountOut, address[] memory path)
public view virtual override returns (uint256[] memory amounts) {
return SoulSwapLibrary.getAmountsIn(factory, amountOut, path);
}
} | performs chained getAmountOut calculations on any number of pairs | function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SoulSwapLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
| 15,255,332 |
./full_match/43114/0x712F9Eeb2f3E77AF28CD8137c4D0C7557e5fFC39/sources/avax.sol | only to supress warning msg | function swapBack() internal swapping {
uint256 dynamicLiquidityFee = isOverLiquified(targetLiquidity, targetLiquidityDenominator) ? 0 : liquidityFee;
uint256 amountToLiquify = swapThreshold.mul(dynamicLiquidityFee).div(totalFee).div(2);
uint256 amountToSwap = swapThreshold.sub(amountToLiquify);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WBNB;
uint256 balanceBefore = address(this).balance;
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
uint256 amountBNB = address(this).balance.sub(balanceBefore);
uint256 totalBNBFee = totalFee.sub(dynamicLiquidityFee.div(2));
uint256 amountBNBLiquidity = amountBNB.mul(dynamicLiquidityFee).div(totalBNBFee).div(2);
uint256 amountBNBReflection = amountBNB.mul(reflectionFee).div(totalBNBFee);
uint256 amountBNBMarketing = amountBNB.mul(marketingFee).div(totalBNBFee);
tmpSuccess = false;
if(amountToLiquify > 0){
address(this),
amountToLiquify,
0,
0,
autoLiquidityReceiver,
block.timestamp
);
emit AutoLiquify(amountBNBLiquidity, amountToLiquify);
}
}
| 4,514,311 |
./full_match/42220/0x893Bf1159213B3E412f058631fb239C43b394976/sources/contracts/lib/GradualValueChange.sol | If the start time is in the past, "fast forward" to start now This avoids discontinuities in the value curve. Otherwise, if you set the start/end times with only 10% of the period in the future, the value would immediately jump 90% | function resolveStartTime(uint256 startTime, uint256 endTime) internal view returns (uint256 resolvedStartTime) {
resolvedStartTime = Math.max(block.timestamp, startTime);
_require(resolvedStartTime <= endTime, Errors.GRADUAL_UPDATE_TIME_TRAVEL);
}
| 16,314,336 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
interface IOracle {
//returns address of pool && 1 if no dai pool and 0 if dai pool
function getPoolForTWAP(address tokenA, uint24 fee) external view returns (address, uint8);
//returns latest price in 18 decimals
function latestPrice(address pool) external view returns (uint price);
}
| returns address of pool && 1 if no dai pool and 0 if dai poolreturns latest price in 18 decimals | interface IOracle {
function getPoolForTWAP(address tokenA, uint24 fee) external view returns (address, uint8);
function latestPrice(address pool) external view returns (uint price);
pragma solidity ^0.8.0;
}
| 12,814,418 |
/**
Telegram: https://t.me/pootokenerc
Website: https://pootoken.co
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
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;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow. (easter egg from the genius dev @nomessages9.)
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract Poo is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public buyBackWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool private gasLimitActive = true;
uint256 private gasPriceLimit = 561 * 1 gwei; // do not allow over x gwei for launch
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyBuyBackFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellBuyBackFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForBuyBack;
uint256 public tokensForDev;
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event BuyBackTriggered(uint256 amount);
event OwnerForcedSwapBack(uint256 timestamp);
constructor() ERC20("Poo", "Poo") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 2;
uint256 _buyBuyBackFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee =22;
uint256 _sellLiquidityFee = 2;
uint256 _sellBuyBackFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e9 * 1e18;
maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn
maxWallet = totalSupply * 2 / 100; // 2% maxWallet
swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyBuyBackFee = _buyBuyBackFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellBuyBackFee = _sellBuyBackFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromFees(buyBackWallet, true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(buyBackWallet, true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
gasLimitActive = false;
transferDelayEnabled = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%");
maxTransactionAmount = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyBuyBackFee = _buyBackFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee;
require(buyTotalFees <= 99, "Must keep fees at 99% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellBuyBackFee = _buyBackFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee;
require(sellTotalFees <= 99, "Must keep fees at 99% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// only use to prevent sniper buys in the first blocks.
if (gasLimitActive && automatedMarketMakerPairs[from]) {
require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else {
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForBuyBack += fees * sellBuyBackFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForBuyBack += fees * buyBuyBackFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForBuyBack + tokensForDev;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForBuyBack = ethBalance.mul(tokensForBuyBack).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBuyBack;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForBuyBack = 0;
tokensForDev = 0;
(bool success,) = address(marketingWallet).call{value: ethForMarketing}("");
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
// keep leftover ETH for buyback only if there is a buyback fee, if not, send the remaining ETH to the marketing wallet if it accumulates
if(buyBuyBackFee == 0 && sellBuyBackFee == 0 && address(this).balance >= 1 ether){
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
}
// force Swap back if slippage above 49% for launch.
function forceSwapBack() external onlyOwner {
uint256 contractBalance = balanceOf(address(this));
require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract");
swapBack();
emit OwnerForcedSwapBack(block.timestamp);
}
// useful for buybacks or to reclaim any ETH on the contract in a way that helps holders.
function buyBackTokens(uint256 ethAmountInWei) external onlyOwner {
// generate the uniswap pair path of weth -> eth
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = address(this);
// make the swap
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}(
0, // accept any amount of Ethereum
path,
address(0xdead),
block.timestamp
);
emit BuyBackTriggered(ethAmountInWei);
}
} | 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;
}
| 1,792 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author @DaniPopes
/// @notice Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721) Non-Fungible Token Standard,
/// including the Metadata and Enumerable extension. Built to optimize for lowest gas possible during mints.
/// @dev Mix of ERC721 implementations by openzeppelin/openzeppelin-contracts, rari-capital/solmate
/// and chiru-labs/ERC721A with many additional optimizations.
/// Assumes serials are sequentially minted starting at 1 (e.g. 1, 2, 3, 4...).
/// Does not support burning tokens to address(0).
/// Missing function implementations:
/// - {tokenURI}.
abstract contract ERC721A {
/* -------------------------------------------------------------------------- */
/* EVENTS */
/* -------------------------------------------------------------------------- */
/// @dev Emitted when `id` token is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 indexed id);
/// @dev Emitted when `owner` enables `approved` to manage the `id` token.
event Approval(address indexed owner, address indexed spender, uint256 indexed id);
/// @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);
/* -------------------------------------------------------------------------- */
/* METADATA STORAGE */
/* -------------------------------------------------------------------------- */
/// @dev The collection name.
string internal _name;
/// @dev The collection symbol.
string internal _symbol;
/* -------------------------------------------------------------------------- */
/* ERC721 STORAGE */
/* -------------------------------------------------------------------------- */
/// @dev ID => spender
mapping(uint256 => address) internal _getApproved;
/// @dev owner => operator => approved
mapping(address => mapping(address => bool)) internal _isApprovedForAll;
/* -------------------------------------------------------------------------- */
/* ERC721A STORAGE */
/* -------------------------------------------------------------------------- */
/// @dev Values are packed in a 256 bits word.
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
/// @dev Values are packed in a 256 bits word.
struct TokenOwnership {
address owner;
uint64 timestamp;
}
/// @dev A counter that increments for each minted token.
/// Initialized to 1 to make all token ids (1 : `maxSupply`) instead of (0 : (`maxSupply` - 1)).
/// Although `maxSupply` is not implemented, it is recommended in all contracts using this implementation.
/// Initializing to 0 requires modifying {totalSupply}, {_exists} and {_idsOfOwner}.
uint256 internal currentIndex = 1;
/// @dev ID => {TokenOwnership}
mapping(uint256 => TokenOwnership) internal _ownerships;
/// @dev owner => {AddressData}
mapping(address => AddressData) internal _addressData;
/* -------------------------------------------------------------------------- */
/* CONSTRUCTOR */
/* -------------------------------------------------------------------------- */
/// @param name_ The collection name.
/// @param symbol_ The collection symbol.
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/* -------------------------------------------------------------------------- */
/* METADATA LOGIC */
/* -------------------------------------------------------------------------- */
/// @notice Returns the collection name.
/// @return The collection name.
function name() public view virtual returns (string memory) {
return _name;
}
/// @notice Returns the collection symbol.
/// @return The collection symbol.
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/// @notice Returns the Uniform Resource Identifier (URI) for `id` token.
/// @dev Not implemented in {ERC721A}.
/// @param id The token ID.
/// @return The URI.
function tokenURI(uint256 id) public view virtual returns (string memory);
/* -------------------------------------------------------------------------- */
/* ENUMERABLE LOGIC */
/* -------------------------------------------------------------------------- */
/// @notice Returns the total amount of tokens stored by the contract.
/// @return The token supply.
function totalSupply() public view virtual returns (uint256) {
// currentIndex is initialized to 1 so it cannot underflow.
unchecked {
return currentIndex - 1;
}
}
/// @notice Returns a token ID owned by `owner` at a given `index` of its token list.
/// @dev Use along with {balanceOf} to enumerate all of `owner`'s tokens.
/// 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.
/// @param owner The address to query.
/// @param index The index to query.
/// @return The token ID.
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
require(index < balanceOf(owner), "INVALID_INDEX");
uint256 minted = currentIndex;
uint256 ownerIndex;
address currOwner;
// Counter overflow is incredibly unrealistic.
unchecked {
for (uint256 i = 0; i < minted; i++) {
address _owner = _ownerships[i].owner;
if (_owner != address(0)) {
currOwner = _owner;
}
if (currOwner == owner) {
if (ownerIndex == index) {
return i;
}
ownerIndex++;
}
}
}
revert("NOT_FOUND");
}
/// @notice Returns a token ID at a given `index` of all the tokens stored by the contract.
/// @dev Use along with {totalSupply} to enumerate all tokens.
/// @param index The index to query.
/// @return The token ID.
function tokenByIndex(uint256 index) public view virtual returns (uint256) {
require(_exists(index), "NONEXISTENT_TOKEN");
return index;
}
/* -------------------------------------------------------------------------- */
/* ERC721 LOGIC */
/* -------------------------------------------------------------------------- */
/// @notice Gives permission to `to` to transfer `id` token to another account.
/// @dev 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.
/// - `id` must exist.
/// Emits an {Approval} event.
/// @param spender The address of the spender to approve to.
/// @param id The token ID to approve.
function approve(address spender, uint256 id) public virtual {
address owner = ownerOf(id);
require(isApprovedForAll(owner, msg.sender) || msg.sender == owner, "NOT_AUTHORIZED");
_getApproved[id] = spender;
emit Approval(owner, spender, id);
}
/// @notice Approve or remove `operator` as an operator for the caller.
/// @dev Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
/// Emits an {ApprovalForAll} event.
/// @param operator The address of the operator to approve.
/// @param approved The status to set.
function setApprovalForAll(address operator, bool approved) public virtual {
_isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/// @notice Returns the account approved for a token ID.
/// @dev Requirements:
/// - `id` must exist.
/// @param id Token ID to query.
/// @return The account approved for `id` token.
function getApproved(uint256 id) public virtual returns (address) {
require(_exists(id), "NONEXISTENT_TOKEN");
return _getApproved[id];
}
/// @notice Returns if the `operator` is allowed to manage all of the assets of `owner`.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return True if `operator` was approved by `owner`.
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
return _isApprovedForAll[owner][operator];
}
/// @notice Transfers `id` token from `from` to `to`.
/// WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
/// @dev Requirements:
/// - `to` cannot be the zero address.
/// - `id` 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.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param id The token ID to transfer.
function transferFrom(
address from,
address to,
uint256 id
) public virtual {
_transfer(from, to, id);
}
/// @notice Safely transfers `id` token from `from` to `to`.
/// @dev Requirements:
/// - `to` cannot be the zero address.
/// - `id` 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 {ERC721TokenReceiver-onERC721Received}, which is called upon a safe transfer.
/// Emits a {Transfer} event.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param id The token ID to transfer.
function safeTransferFrom(
address from,
address to,
uint256 id
) public virtual {
_transfer(from, to, id);
require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT");
}
/// @notice Safely transfers `id` token from `from` to `to`.
/// @dev Requirements:
/// - `to` cannot be the zero address.
/// - `id` 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 {ERC721TokenReceiver-onERC721Received}, which is called upon a safe transfer.
/// Emits a {Transfer} event.
/// Additionally passes `data` in the callback.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param id The token ID to transfer.
/// @param data The calldata to pass in the {ERC721TokenReceiver-onERC721Received} callback.
function safeTransferFrom(
address from,
address to,
uint256 id,
bytes memory data
) public virtual {
_transfer(from, to, id);
require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT");
}
/// @notice Returns the number of tokens in an account.
/// @param owner The address to query.
/// @return The balance.
function balanceOf(address owner) public view virtual returns (uint256) {
require(owner != address(0), "INVALID_OWNER");
return uint256(_addressData[owner].balance);
}
/// @notice Returns the owner of a token ID.
/// @dev Requirements:
/// - `id` must exist.
/// @param id The token ID.
function ownerOf(uint256 id) public view virtual returns (address) {
return _ownershipOf(id).owner;
}
/* -------------------------------------------------------------------------- */
/* ERC165 LOGIC */
/* -------------------------------------------------------------------------- */
/// @notice Returns true if this contract implements an interface from its ID.
/// @dev See the corresponding
/// [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
/// to learn more about how these IDs are created.
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) {
return
interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
interfaceId == 0x5b5e139f || // ERC165 Interface ID for ERC721Metadata
interfaceId == 0x780e9d63; // ERC165 Interface ID for ERC721Enumerable
}
/* -------------------------------------------------------------------------- */
/* INTERNAL GENERAL LOGIC */
/* -------------------------------------------------------------------------- */
/// @dev Returns whether a token ID exists.
/// Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
/// Tokens start existing when they are minted.
/// @param id Token ID to query.
function _exists(uint256 id) internal view virtual returns (bool) {
return id != 0 && id < currentIndex;
}
/// @notice Returns all token IDs owned by an address.
/// 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.
/// @param owner Address to query.
/// @return ids An array of the ID's owned by `owner`.
function _idsOfOwner(address owner) internal view virtual returns (uint256[] memory ids) {
uint256 bal = uint256(_addressData[owner].balance);
if (bal == 0) return ids;
ids = new uint256[](bal);
uint256 minted = currentIndex;
address currOwner;
uint256 index;
unchecked {
for (uint256 i = 1; i < minted; i++) {
address _owner = _ownerships[i].owner;
if (_owner != address(0)) {
currOwner = _owner;
}
if (currOwner == owner) {
ids[index++] = i;
if (index == bal) return ids;
}
}
}
}
/// @dev Returns the total number of tokens minted by and address.
/// @param owner Address to query.
/// @return Number of tokens minted by `owner`.
function _numberMinted(address owner) public view virtual returns (uint256) {
require(owner != address(0), "INVALID_OWNER");
return uint256(_addressData[owner].numberMinted);
}
/// @dev Returns the ownership values for a token ID.
/// @param id Token ID to query.
/// @return {TokenOwnership} of `id`.
function _ownershipOf(uint256 id) internal view virtual returns (TokenOwnership memory) {
require(_exists(id), "NONEXISTENT_TOKEN");
unchecked {
for (uint256 curr = id; curr >= 0; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.owner != address(0)) {
return ownership;
}
}
}
revert("NOT_FOUND");
}
/* -------------------------------------------------------------------------- */
/* INTERNAL TRANSFER/MINT LOGIC */
/* -------------------------------------------------------------------------- */
/// @dev Transfers `id` from `from` to `to`.
/// Requirements:
/// - `to` cannot be the zero address.
/// - `id` token must be owned by `from`.
/// Emits a {Transfer} event.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param id The token ID to transfer.
function _transfer(
address from,
address to,
uint256 id
) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(id);
require((msg.sender == prevOwnership.owner || getApproved(id) == msg.sender || isApprovedForAll(prevOwnership.owner, msg.sender)), "NOT_AUTHORIZED");
require(prevOwnership.owner == from, "WRONG_FROM");
require(to != address(0), "INVALID_RECIPIENT");
// Clear approvals
delete _getApproved[id];
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
// Set new owner
_ownerships[id].owner = to;
uint256 nextId = id + 1;
// If the ownership slot of id + 1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of id + 1 explicitly in storage to maintain correctness for ownerOf(id + 1) calls.
if (_ownerships[nextId].owner == address(0)) {
if (_exists(nextId)) {
_ownerships[nextId].owner = prevOwnership.owner;
}
}
}
emit Transfer(from, to, id);
}
/// @dev Mints `amount` tokens to `to`.
/// Requirements:
/// - there must be `amount` tokens remaining unminted in the total collection.
/// - `to` cannot be the zero address.
/// Emits `amount` {Transfer} events.
/// @param to The address to mint to.
/// @param amount The amount of tokens to mint.
function _mint(address to, uint256 amount) internal virtual {
require(to != address(0), "INVALID_RECIPIENT");
require(amount != 0, "INVALID_AMOUNT");
// Counter or mint amount overflow is incredibly unrealistic.
unchecked {
uint256 startId = currentIndex;
_addressData[to].balance += uint128(amount);
_addressData[to].numberMinted += uint128(amount);
_ownerships[startId].owner = to;
_ownerships[startId].timestamp = uint64(block.timestamp);
for (uint256 i; i < amount; i++) {
emit Transfer(address(0), to, startId);
startId++;
}
currentIndex = startId;
}
}
/// @dev Safely mints `amount` of tokens and transfers them to `to`.
/// If `to` is a contract it must implement {ERC721TokenReceiver.onERC721Received}
/// that returns {ERC721TokenReceiver.onERC721Received.selector}.
/// @param to The address to mint to.
/// @param amount The amount of tokens to mint.
function _safeMint(address to, uint256 amount) internal virtual {
_mint(to, amount);
require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(address(0), to, currentIndex - amount, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT");
}
/// @dev Safely mints `amount` of tokens and transfers them to `to`.
/// Requirements:
/// - `id` must not exist.
/// - If `to` refers to a smart contract, it must implement {ERC721TokenReceiver.onERC721Received}, which is called upon a safe transfer.
/// Additionally passes `data` in the callback.
/// @param to The address to mint to.
/// @param amount The amount of tokens to mint.
/// @param data The calldata to pass in the {ERC721TokenReceiver.onERC721Received} callback.
function _safeMint(
address to,
uint256 amount,
bytes memory data
) internal virtual {
_mint(to, amount);
require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(address(0), to, currentIndex - amount, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT");
}
/* -------------------------------------------------------------------------- */
/* UTILS */
/* -------------------------------------------------------------------------- */
/// @notice Converts a `uint256` to its ASCII `string` decimal representation.
/// @dev https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
function toString(uint256 value) internal pure virtual 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);
}
}
/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
interface ERC721TokenReceiver {
function onERC721Received(
address operator,
address from,
uint256 id,
bytes calldata data
) external returns (bytes4);
}
| Safely mints `amount` of tokens and transfers them to `to`. If `to` is a contract it must implement {ERC721TokenReceiver.onERC721Received} that returns {ERC721TokenReceiver.onERC721Received.selector}. to The address to mint to. amount The amount of tokens to mint. | function _safeMint(address to, uint256 amount) internal virtual {
_mint(to, amount);
require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(address(0), to, currentIndex - amount, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT");
}
| 5,358,605 |
// File: contracts/DkargoPrefix.sol
pragma solidity ^0.4.23;
/// @title DkargoPrefix
/// @notice 디카르고 컨트랙트 여부 식별용 prefix 컨트랙트 정의
/// @author jhhong
contract DkargoPrefix {
string internal _dkargoPrefix; // 디카르고-프리픽스
/// @author jhhong
/// @notice 디카르고 프리픽스를 반환한다.
/// @return 디카르고 프리픽스 (string)
function getDkargoPrefix() public view returns(string memory) {
return _dkargoPrefix;
}
/// @author jhhong
/// @notice 디카르고 프리픽스를 설정한다.
/// @param prefix 설정할 프리픽스
function _setDkargoPrefix(string memory prefix) internal {
_dkargoPrefix = prefix;
}
}
// File: contracts/authority/Ownership.sol
pragma solidity ^0.4.23;
/// @title Onwership
/// @dev 오너 확인 및 소유권 이전 처리
/// @author jhhong
contract Ownership {
address private _owner;
event OwnershipTransferred(address indexed old, address indexed expected);
/// @author jhhong
/// @notice 소유자만 접근할 수 있음을 명시한다.
modifier onlyOwner() {
require(isOwner() == true, "Ownership: only the owner can call");
_;
}
/// @author jhhong
/// @notice 컨트랙트 생성자이다.
constructor() internal {
emit OwnershipTransferred(_owner, msg.sender);
_owner = msg.sender;
}
/// @author jhhong
/// @notice 소유권을 넘겨준다.
/// @param expected 새로운 오너 계정
function transferOwnership(address expected) public onlyOwner {
require(expected != address(0), "Ownership: new owner is the zero address");
emit OwnershipTransferred(_owner, expected);
_owner = expected;
}
/// @author jhhong
/// @notice 오너 주소를 반환한다.
/// @return 오너 주소
function owner() public view returns (address) {
return _owner;
}
/// @author jhhong
/// @notice 소유자인지 확인한다.
/// @return 확인 결과 (boolean)
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
}
// File: contracts/libs/refs/SafeMath.sol
pragma solidity ^0.4.23;
/**
* @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.
*/
/**
* @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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/chain/AddressChain.sol
pragma solidity ^0.4.23;
/// @title AddressChain
/// @notice 주소 체인 정의 및 관리
/// @dev 토큰홀더, 회원정보 등과 같은 유저 리스트 관리에 쓰인다.
/// @author jhhong
contract AddressChain {
using SafeMath for uint256;
// 구조체 : 노드 정보
struct NodeInfo {
address prev; // 이전 노드
address next; // 다음 노드
}
// 구조체 : 노드 체인
struct NodeList {
uint256 count; // 노드의 총 개수
address head; // 체인의 머리
address tail; // 체인의 꼬리
mapping(address => NodeInfo) map; // 계정에 대한 노드 정보 매핑
}
// 변수 선언
NodeList private _slist; // 노드 체인 (싱글리스트)
// 이벤트 선언
event AddressChainLinked(address indexed node); // 이벤트: 체인에 추가됨
event AddressChainUnlinked(address indexed node); // 이벤트: 체인에서 빠짐
/// @author jhhong
/// @notice 체인에 연결된 원소의 개수를 반환한다.
/// @return 체인에 연결된 원소의 개수
function count() public view returns(uint256) {
return _slist.count;
}
/// @author jhhong
/// @notice 체인 헤드 정보를 반환한다.
/// @return 체인 헤드 정보
function head() public view returns(address) {
return _slist.head;
}
/// @author jhhong
/// @notice 체인 꼬리 정보를 반환한다.
/// @return 체인 꼬리 정보
function tail() public view returns(address) {
return _slist.tail;
}
/// @author jhhong
/// @notice node의 다음 노드 정보를 반환한다.
/// @param node 노드 정보 (체인에 연결되어 있을 수도 있고 아닐 수도 있음)
/// @return node의 다음 노드 정보
function nextOf(address node) public view returns(address) {
return _slist.map[node].next;
}
/// @author jhhong
/// @notice node의 이전 노드 정보를 반환한다.
/// @param node 노드 정보 (체인에 연결되어 있을 수도 있고 아닐 수도 있음)
/// @return node의 이전 노드 정보
function prevOf(address node) public view returns(address) {
return _slist.map[node].prev;
}
/// @author jhhong
/// @notice node가 체인에 연결된 상태인지를 확인한다.
/// @param node 체인 연결 여부를 확인할 노드 주소
/// @return 연결 여부 (boolean), true: 연결됨(linked), false: 연결되지 않음(unlinked)
function isLinked(address node) public view returns (bool) {
if(_slist.count == 1 && _slist.head == node && _slist.tail == node) {
return true;
} else {
return (_slist.map[node].prev == address(0) && _slist.map[node].next == address(0))? (false) :(true);
}
}
/// @author jhhong
/// @notice 새로운 노드 정보를 노드 체인에 연결한다.
/// @param node 노드 체인에 연결할 노드 주소
function _linkChain(address node) internal {
require(node != address(0), "AddressChain: try to link to the zero address");
require(!isLinked(node), "AddressChain: the node is aleady linked");
if(_slist.count == 0) {
_slist.head = _slist.tail = node;
} else {
_slist.map[node].prev = _slist.tail;
_slist.map[_slist.tail].next = node;
_slist.tail = node;
}
_slist.count = _slist.count.add(1);
emit AddressChainLinked(node);
}
/// @author jhhong
/// @notice node 노드를 체인에서 연결 해제한다.
/// @param node 노드 체인에서 연결 해제할 노드 주소
function _unlinkChain(address node) internal {
require(node != address(0), "AddressChain: try to unlink to the zero address");
require(isLinked(node), "AddressChain: the node is aleady unlinked");
address tempPrev = _slist.map[node].prev;
address tempNext = _slist.map[node].next;
if (_slist.head == node) {
_slist.head = tempNext;
}
if (_slist.tail == node) {
_slist.tail = tempPrev;
}
if (tempPrev != address(0)) {
_slist.map[tempPrev].next = tempNext;
_slist.map[node].prev = address(0);
}
if (tempNext != address(0)) {
_slist.map[tempNext].prev = tempPrev;
_slist.map[node].next = address(0);
}
_slist.count = _slist.count.sub(1, "");
emit AddressChainUnlinked(node);
}
}
// File: contracts/introspection/ERC165/IERC165.sol
pragma solidity ^0.4.23;
/// @title IERC165
/// @dev EIP165 interface 선언
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
/// @author jhhong
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/introspection/ERC165/ERC165.sol
pragma solidity ^0.4.23;
/// @title ERC165
/// @dev EIP165 interface 구현
/// @author jhhong
contract ERC165 is IERC165 {
mapping(bytes4 => bool) private _infcs; // INTERFACE ID별 지원여부를 저장하기 위한 매핑 변수
/// @author jhhong
/// @notice 컨트랙트 생성자이다.
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
constructor() internal {
_registerInterface(bytes4(0x01ffc9a7)); // supportsInterface()의 INTERFACE ID 등록
}
/// @author jhhong
/// @notice 컨트랙트가 INTERFACE ID를 지원하는지의 여부를 반환한다.
/// @param infcid 지원여부를 확인할 INTERFACE ID (Function Selector)
/// @return 지원여부 (boolean)
function supportsInterface(bytes4 infcid) external view returns (bool) {
return _infcs[infcid];
}
/// @author jhhong
/// @notice INTERFACE ID를 등록한다.
/// @param infcid 등록할 INTERFACE ID (Function Selector)
function _registerInterface(bytes4 infcid) internal {
require(infcid != 0xffffffff, "ERC165: invalid interface id");
_infcs[infcid] = true;
}
}
// File: contracts/token/ERC20/IERC20.sol
pragma solidity ^0.4.23;
/// @title IERC20
/// @notice EIP20 interface 선언
/// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
/// @author jhhong
interface IERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address account) 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: contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.23;
/// @title ERC20
/// @notice EIP20 interface 정의 및 mint/burn (internal) 함수 구현
/// @author jhhong
contract ERC20 is IERC20 {
using SafeMath for uint256;
uint256 private _supply; // 총 통화량
mapping(address => uint256) private _balances; // 계정별 통화량 저장소
mapping(address => mapping(address => uint256)) private _allowances; // 각 계정에 대해 "계정별 위임량"을 저장
/// @author jhhong
/// @notice 컨트랙트 생성자이다.
/// @param supply 초기 발행량
constructor(uint256 supply) internal {
uint256 pebs = supply;
_mint(msg.sender, pebs);
}
/// @author jhhong
/// @notice 계정(spender)에게 통화량(value)을 위임한다.
/// @param spender 위임받을 계정
/// @param amount 위임할 통화량
/// @return 정상처리 시 true
function approve(address spender, uint256 amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/// @author jhhong
/// @notice 계정(recipient)에게 통화량(amount)을 전송한다.
/// @param recipient 전송받을 계정
/// @param amount 금액
/// @return 정상처리 시 true
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/// @author jhhong
/// @notice 계정(sender)이 계정(recipient)에게 통화량(amount)을 전송한다.
/// @param sender 전송할 계정
/// @param recipient 전송받을 계정
/// @param amount 금액
/// @return 정상처리 시 true
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/// @author jhhong
/// @notice 발행된 총 통화량을 반환한다.
/// @return 총 통화량
function totalSupply() public view returns (uint256) {
return _supply;
}
/// @author jhhong
/// @notice 계정(account)이 보유한 통화량을 반환한다.
/// @param account 계정
/// @return 계정(account)이 보유한 통화량
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/// @author jhhong
/// @notice 계정(approver)이 계정(spender)에게 위임한 통화량을 반환한다.
/// @param approver 위임할 계정
/// @param spender 위임받을 계정
/// @return 계정(approver)이 계정(spender)에게 위임한 통화량
function allowance(address approver, address spender) public view returns (uint256) {
return _allowances[approver][spender];
}
/// @author jhhong
/// @notice 계정(approver)이 계정(spender)에게 통화량(value)을 위임한다.
/// @param approver 위임할 계정
/// @param spender 위임받을 계정
/// @param value 위임할 통화량
function _approve(address approver, address spender, uint256 value) internal {
require(approver != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[approver][spender] = value;
emit Approval(approver, spender, value);
}
/// @author jhhong
/// @notice 계정(sender)이 계정(recipient)에게 통화량(amount)을 전송한다.
/// @param sender 위임할 계정
/// @param recipient 위임받을 계정
/// @param amount 금액
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/// @author jhhong
/// @notice 통화량(amount)만큼 주조하여 계정(account)의 통화량에 더해준다.
/// @dev ERC20Mint에 정의하면 private 속성인 supply와 balances에 access할 수 없어서 ERC20에 internal로 정의함.
/// @param account 주조된 통화량을 받을 계정
/// @param amount 주조할 통화량
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_supply = _supply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/// @author jhhong
/// @notice 통화량(value)만큼 소각하여 계정(account)의 통화량에서 뺀다.
/// @dev ERC20Mint에 정의하면 private 속성인 supply와 balances에 access할 수 없어서 ERC20에 internal로 정의함.
/// @param account 통화량을 소각시킬 계정
/// @param value 소각시킬 통화량
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(value, "ERC20: burn amount exceeds balance");
_supply = _supply.sub(value, "");
emit Transfer(account, address(0), value);
}
}
// File: contracts/token/ERC20/ERC20Safe.sol
pragma solidity ^0.4.23;
/// @title ERC20Safe
/// @notice Approve Bug Fix 버전 (중복 위임 방지)
/// @author jhhong
contract ERC20Safe is ERC20 {
using SafeMath for uint256;
/// @author jhhong
/// @notice 계정(spender)에게 통화량(amount)을 위임한다.
/// @dev 값이 덮어써짐을 방지하기 위해 기존에 위임받은 통화량이 0인 경우에만 호출을 허용한다.
/// @param spender 위임받을 계정
/// @param amount 위임할 통화량
/// @return 정상처리 시 true
function approve(address spender, uint256 amount) public returns (bool) {
require((amount == 0) || (allowance(msg.sender, spender) == 0), "ERC20Safe: approve from non-zero to non-zero allowance");
return super.approve(spender, amount);
}
/// @author jhhong
/// @notice 계정(spender)에 위임된 통화량에 통화량(addedValue)를 더한값을 위임한다.
/// @dev 위임된 통화량이 있을 경우, 통화량 증가는 상기 함수로 수행할 것
/// @param spender 위임받을 계정
/// @param addedValue 더해질 통화량
/// @return 정상처리 시 true
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
uint256 amount = allowance(msg.sender, spender).add(addedValue);
return super.approve(spender, amount);
}
/// @author jhhong
/// @notice 계정(spender)에 위임된 통화량에 통화량(subtractedValue)를 뺀값을 위임한다.
/// @dev 위임된 통화량이 있을 경우, 통화량 감소는 상기 함수로 수행할 것
/// @param spender 위임받을 계정
/// @param subtractedValue 빼질 통화량
/// @return 정상처리 시 true
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
uint256 amount = allowance(msg.sender, spender).sub(subtractedValue, "ERC20: decreased allowance below zero");
return super.approve(spender, amount);
}
}
// File: contracts/DkargoToken.sol
pragma solidity ^0.4.23;
/// @title DkargoToken
/// @notice 디카르고 토큰 컨트랙트 정의 (메인넷 deploy용)
/// @dev burn 기능 추가 (public)
/// @author jhhong
contract DkargoToken is Ownership, ERC20Safe, AddressChain, ERC165, DkargoPrefix {
string private _name; // 토큰 이름
string private _symbol; // 토큰 심볼
/// @author jhhong
/// @notice 컨트랙트 생성자이다.
/// @dev 초기 발행량이 있을 경우, msg.sender를 홀더 리스트에 추가한다.
/// @param name 토큰 이름
/// @param symbol 토큰 심볼
/// @param supply 초기 발행량
constructor(string memory name, string memory symbol, uint256 supply) ERC20(supply) public {
_setDkargoPrefix("token"); // 프리픽스 설정 (token)
_registerInterface(bytes4(0x946edbed)); // INTERFACE ID 등록 (getDkargoPrefix)
_name = name;
_symbol = symbol;
_linkChain(msg.sender);
}
/// @author jhhong
/// @notice 본인의 보유금액 중 지정된 금액만큼 소각한다.
/// @param amount 소각시킬 통화량
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
/// @author jhhong
/// @notice 토큰을 전송한다. (전송주체: msg.sender)
/// @dev 전송 후 변경된 토큰 홀더 상태를 체인에 기록한다.
/// @param to 토큰을 받을 주소
/// @param value 전송 금액 (토큰량)
function transfer(address to, uint256 value) public returns (bool) {
bool ret = super.transfer(to, value);
if(isLinked(msg.sender) && balanceOf(msg.sender) == 0) {
_unlinkChain(msg.sender);
}
if(!isLinked(to) && balanceOf(to) > 0) {
_linkChain(to);
}
return ret;
}
/// @author jhhong
/// @notice 토큰을 전송한다. (전송주체: from)
/// @dev 전송 후 변경된 토큰 홀더 상태를 체인에 기록한다.
/// @param from 토큰을 보낼 계정
/// @param to 토큰을 받을 계정
/// @param value 전송 금액 (토큰량)
function transferFrom(address from, address to, uint256 value) public returns (bool) {
bool ret = super.transferFrom(from, to, value);
if(isLinked(from) && balanceOf(from) == 0) {
_unlinkChain(from);
}
if(!isLinked(to) && balanceOf(to) > 0) {
_linkChain(to);
}
return ret;
}
/// @author jhhong
/// @notice 토큰의 이름을 반환한다.
/// @return 토큰 이름
function name() public view returns(string memory) {
return _name;
}
/// @author jhhong
/// @notice 토큰의 심볼을 반환한다.
/// @return 토큰 심볼
function symbol() public view returns(string memory) {
return _symbol;
}
/// @author jhhong
/// @notice 토큰 데시멀을 반환한다.
/// @dev 데시멀 값은 18 (peb) 로 고정이다.
/// @return 토큰 데시멀
function decimals() public pure returns(uint256) {
return 18;
}
}
| jhhong 컨트랙트가 INTERFACE ID를 지원하는지의 여부를 반환한다. infcid 지원여부를 확인할 INTERFACE ID (Function Selector) return 지원여부 (boolean) | function supportsInterface(bytes4 infcid) external view returns (bool) {
return _infcs[infcid];
}
| 12,622,141 |
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity 0.6.12;
contract MiraqleDefi is ERC20("Miraqle Defi", "QFI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (0x).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
pragma solidity 0.6.12;
interface IMigratorPool {
function migrate(IERC20 token) external returns (IERC20);
}
contract QFIPool is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken;
uint256 allocPoint;
uint256 lastRewardBlock;
uint256 accTokenPerShare;
}
MiraqleDefi public token;
address public teamAddr;
uint256 public bonusEndBlock;
uint256 public tokenPerBlock;
uint256 public constant BONUS_MULTIPLIER = 2;
IMigratorPool public migrator;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint;
uint256 public startBlock;
uint256 public endBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
MiraqleDefi _token,
address _teamAddr,
uint256 _tokenPerBlock,
uint256 _startBlock,
uint256 _endBlock,
uint256 _bonusEndBlock
) public {
token = _token;
teamAddr = _teamAddr;
tokenPerBlock = _tokenPerBlock;
startBlock = _startBlock;
endBlock = _endBlock;
bonusEndBlock = _bonusEndBlock;
}
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,
accTokenPerShare: 0
}));
}
// Update the given pool's Token allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorPool _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
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 Tokens on frontend.
function pendingToken(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = 0;
if(block.number > endBlock)
blockNumber = endBlock;
else
blockNumber = block.number;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, blockNumber);
uint256 tokenReward = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accTokenPerShare = accTokenPerShare.add(tokenReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accTokenPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
if (block.number > endBlock)
pool.lastRewardBlock = endBlock;
else
pool.lastRewardBlock = block.number;
return;
}
if (pool.lastRewardBlock == endBlock){
return;
}
if (block.number > endBlock){
uint256 multiplier = getMultiplier(pool.lastRewardBlock, endBlock);
uint256 tokenReward = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
//token.mint(teamAddr, tokenReward.div(10));
//token.mint(address(this), tokenReward);
pool.accTokenPerShare = pool.accTokenPerShare.add(tokenReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = endBlock;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tokenReward = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
//token.mint(teamAddr, tokenReward.div(10));
//token.mint(address(this), tokenReward);
pool.accTokenPerShare = pool.accTokenPerShare.add(tokenReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit tokens to Pool for Token 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.accTokenPerShare).div(1e12).sub(user.rewardDebt);
safeTokenTransfer(msg.sender, pending);
}
if(_amount > 0) { //kevin
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// DepositFor tokens to Pool for Token allocation.
function depositFor(address _beneficiary, uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_beneficiary];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);
safeTokenTransfer(_beneficiary, pending);
}
if(_amount > 0) { //kevin
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
emit Deposit(_beneficiary, _pid, _amount);
}
// Withdraw tokens from Pool.
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.accTokenPerShare).div(1e12).sub(user.rewardDebt);
safeTokenTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe token transfer function, just in case if rounding error causes pool to not have enough Tokens.
function safeTokenTransfer(address _to, uint256 _amount) internal {
uint256 tokenBal = token.balanceOf(address(this));
if (_amount > tokenBal) {
token.transfer(_to, tokenBal);
} else {
token.transfer(_to, _amount);
}
}
// Update team address by the previous team.
function team(address _teamAddr) public {
require(msg.sender == teamAddr, "dev: wut?");
teamAddr = _teamAddr;
}
} | Deposit tokens to Pool for Token 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.accTokenPerShare).div(1e12).sub(user.rewardDebt);
safeTokenTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
| 1,554,705 |
./full_match/1/0x733015E8606F4f079828f0bf71A2FC7135F9d119/sources/src/StakingManager.sol | Sets the max number of deposits allowed at a time _newMaxBatchDepositSize the max number of deposits allowed | function setMaxBatchDepositSize(
uint128 _newMaxBatchDepositSize
) public onlyOwner {
maxBatchDepositSize = _newMaxBatchDepositSize;
}
| 17,041,742 |
pragma solidity ^0.4.21;
// Open Zeppelin library for preventing overflows and underflows.
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;
}
}
// ERC20 Token interface.
interface IERC20 {
function totalSupply() public constant returns (uint256 totalSupply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
// Contract onwer restrictions.
contract Owned {
address public owner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
}
contract FidelityPoints is IERC20, Owned {
// Overlay of the Safemath library on uint256 datatype
using SafeMath for uint256;
// Restrinct the usage of a function to a user
modifier onlyUser {
require(!containsShop(msg.sender));
_;
}
// Restrinct the usage of a function to a shop
modifier onlyShop {
require(containsShop(msg.sender));
_;
}
// Structure of a payment request done by a shop asking money from the ISP.
struct EthereumPaymentRequest {
address shop; // Ethereum address of the shop, sender of the request.
string note; // Additional notes for the admin
uint value; // Amount of ethereum to be transfered
string shopId; // Id of the shop who is making the request in order to get its data from the database
bool completed; // Flag regarding the admin execution of the payment
bool rejected; // Flag regarding the approvation status of the request
}
// Structure of a buy request done by a user for buying a product from a shop.
struct BuyingRequest {
address user; // Ethereum address of the user, sender of the request.
address shop; // Ethereum address of the shop, receiver of the request.
string product; // Id of the product object to be bought.
string shopEmail; // Email of the shop, used for diplaying the request to its belonging shops.
string userId; // Id of the user, used for showing him every request he has performed.
uint value; // Tokens used for buying the product, they are sent with the request
bool shipped; // Flag regarding the shipment status of the request
bool rejected; // Flag regarding the approvation status of the request
}
// Contract variables.
uint public constant INITIAL_SUPPLY = 1000000000000; // Initial supply of tokens: 1.000.000.000.000
uint public _totalSupply = 0; // Total amount of tokens
address public owner; // Address of the contract owner
address[] public shops; // Array of shop addresses
EthereumPaymentRequest[] public ethereumPaymentRequests; // Array of shop payment requests
BuyingRequest[] public buyingRequests; // Array of user buy requests
// Cryptocurrency characteristics.
string public constant symbol = "FID"; // Cryprocurrency symbol
string public constant name = "Fido Coin"; // Cryptocurrency name
uint8 public constant decimals = 18; // Standard number for Eth Token
uint256 public constant RATE = 1000000000000000000; // 1 ETH = 10^18 FID;
// Map definions.
mapping (address => uint256) public balances; // Map [User,Amount]
mapping (address => bool) public shopsMap; // Map [Shop,Official]
mapping (address => mapping (address => uint256)) public allowed; // Map [User,[OtherUser,Amount]]
// Events definition.
// This notify clients about the transfer.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// Constructor, set the contract sender/deployer as owner.
function FidelityPoints() public {
// Check for the null address.
require(msg.sender != 0x00);
// Update total supply with decimals.
_totalSupply = INITIAL_SUPPLY * 10 ** uint256(decimals);
// Give an initial supply to the contract creator.
balances[msg.sender] = _totalSupply;
// Who deploys the contract is the owner.
owner = msg.sender;
// Add owner in shops Array.
shops.push(owner);
// add owner in shopsMap.
shopsMap[owner] = true;
}
/******************************************************************************
* Fallback function, a function with no name that gets called. *
* whenever you do not actually pass a function name. *
* This allow people to just send money directly to the contract address. *
******************************************************************************/
function () public payable {
// People will send money directly to the contract address.
}
/*****************************************************************************
* Check if a shop exists. *
******************************************************************************/
function containsShop(address _shop) public view returns (bool) {
return shopsMap[_shop];
}
/*****************************************************************************
* Perform a FIDO token generation. *
******************************************************************************/
function createTokens() public payable onlyOwner {
// Check if the amount trasfered is greather than 0.
require(msg.value > 0);
// Check if the sender address is 0.
require(msg.sender != 0x00);
// Create tokens from Ether multiplying for 10^18
uint256 tokens = msg.value.mul(RATE);
// Add tokens to the buyer account.
balances[msg.sender] = balances[msg.sender].add(tokens);
// Total supply number increased by the new token creation.
_totalSupply = _totalSupply.add(tokens);
// Transfer the amount to the owner, auto rollback if the transaction fails.
owner.transfer(msg.value);
}
/*****************************************************************************
* Perform a payment with the ETH cryptocurrency. *
* *
* Return true if success. *
* *
* @param _to the address of the receiver. *
* @param _value amount of ETH transfered. *
******************************************************************************/
function payWithEthereum(address _to, uint256 _value) public payable onlyOwner returns (bool success) {
// Check if the amount trasfered is greather than 0.
require(msg.value > 0);
// Check if the sender is differrent from 0x00.
require(msg.sender != 0x00);
// Transfer Operation.
_to.transfer(_value);
return true;
}
/*****************************************************************************
* Return the total supply of the token. *
* *
* *
* Return the value of the variable `_totalSupply`. *
******************************************************************************/
function totalSupply() public constant returns (uint256 totalSupply) {
// Value of the contract variable
return _totalSupply;
}
/*****************************************************************************
* Return the balance of an account. *
* *
* Return the amount of money of the `_account`. *
* *
* @param _account the address of the account of which I want the balance. *
******************************************************************************/
function balanceOf(address _account) public constant returns (uint256 balance) {
return balances[_account];
}
/*****************************************************************************
* Transfer tokens from sender to receiver. *
* *
* Send `_value` tokens from the msg.sender to the `_to` address. *
* *
* @param _to the address of the receiver. *
* @param _value the amount of points to send. *
******************************************************************************/
function transfer(address _to, uint256 _value) public returns (bool success) {
_value = _value * 10 ** uint256(decimals);
// Check if the sender has enough.
require(balances[msg.sender] >= _value);
// Check if the amount trasfered is greather than 0.
require(_value > 0);
// Prevent transfer to 0x0 address.
require(_to != 0x0);
// Check for overflows.
require(balances[_to] + _value > balances[_to]);
// Check for underflows.
require(balances[msg.sender] - _value < balances[msg.sender]);
// Save for the future assertion.
uint previousBalances = balances[msg.sender].add(balances[_to]);
// Subtract the token amount from the sender.
balances[msg.sender] = balances[msg.sender].sub(_value);
// Add the token amount to the recipient.
balances[_to] = balances[_to].add(_value);
// Emit the Transfer event.
emit Transfer(msg.sender, _to, _value);
// Asserts are used to use static analysis to find bugs in code. They should never fail.
assert(balances[msg.sender].add(balances[_to]) == previousBalances);
return true;
}
/*****************************************************************************
* Get the most important token informations *
******************************************************************************/
function getSummary() public view returns (uint, address, string, string, uint8, uint256) {
uint exponent = 10 ** uint(decimals);
uint256 tokenUnits = _totalSupply / exponent;
return(
tokenUnits,
owner,
symbol,
name,
decimals,
RATE
);
}
/*****************************************************************************
* Add a new shop to the collection of official shops *
******************************************************************************/
function addShop(address _newShop) public onlyOwner returns (bool) {
// Add shop in shops Array
shops.push(_newShop);
// Add shop in shopsMap
shopsMap[_newShop] = true;
return true;
}
/*****************************************************************************
* Returns the number of the official shops *
******************************************************************************/
function getShopsCount() public view returns (uint) {
return shops.length;
}
/*****************************************************************************
* Shop create a request to be payed and pay the ISP. *
* *
* *
* @param _value *
* @param _note *
* @param _shopId *
******************************************************************************/
function createEthereumPaymentRequest(uint _value, string _note, string _shopId)
public onlyShop returns (bool) {
// Check if the shop has enough token.
require(balances[msg.sender] >= _value);
// Check if the amount trasfered is greather than 0.
require(_value > 0);
// Prevent transfer to 0x0 address.
require(owner != 0x0);
// Check for overflows.
require(balances[owner] + _value > balances[owner]);
// Check for underflows.
require(balances[msg.sender] - _value < balances[msg.sender]);
// Create the new EthereumPaymentRequest.
EthereumPaymentRequest memory ethereumPaymentRequest = EthereumPaymentRequest({
shop: msg.sender,
note: _note,
value: _value,
shopId: _shopId,
completed: false,
rejected: false
});
// Adding a new ethereum payment request.
ethereumPaymentRequests.push(ethereumPaymentRequest);
// Value convertion.
_value = _value * 10 ** uint256(decimals);
// Save for the future assertion.
uint previousBalances = balances[msg.sender].add(balances[owner]);
// Subtract the token amount from the shop.
balances[msg.sender] = balances[msg.sender].sub(_value);
// Add the token amount to the contract owner.
balances[owner] = balances[owner].add(_value);
// Emit the Transfer event.
emit Transfer(msg.sender, owner, _value);
// Asserts are used to use static analysis to find bugs in code. They should never fail.
assert(balances[msg.sender].add(balances[owner]) == previousBalances);
return true;
}
/*****************************************************************************
* User create a request to buy a product from a shop. *
* *
* *
* @param _product *
* @param _shopEmail *
* @param _receiver *
* @param _value *
* @param _userId *
******************************************************************************/
function createBuyingRequest(string _product, string _shopEmail, address _receiver, uint _value, string _userId)
public onlyUser returns (bool) {
// Check if the sender has enough.
require(balances[msg.sender] >= _value);
// Check if the amount trasfered is greather than 0.
require(_value > 0);
// Prevent transfer to 0x0 address.
require(_receiver != 0x0);
// Check for overflows.
require(balances[_receiver] + _value > balances[_receiver]);
// Check for underflows.
require(balances[msg.sender] - _value < balances[msg.sender]);
// Receiver should be an official shop.
require(containsShop(_receiver));
// Create the new BuyingRequest.
BuyingRequest memory buyingRequest = BuyingRequest({
user: msg.sender,
shop: _receiver,
product: _product,
shopEmail: _shopEmail,
value: _value,
userId: _userId,
shipped: false,
rejected: false
});
// Adding a new buy request.
buyingRequests.push(buyingRequest);
// Value convertion.
_value = _value * 10 ** uint256(decimals);
// Save for the future assertion.
uint previousBalances = balances[msg.sender].add(balances[_receiver]);
// Subtract the token amount from the user sender.
balances[msg.sender] = balances[msg.sender].sub(_value);
// Add the token amount to the shop receiver
balances[_receiver] = balances[_receiver].add(_value);
// Emit the Transfer event.
emit Transfer(msg.sender, _receiver, _value);
// Asserts are used to use static analysis to find bugs in code. They should never fail.
assert(balances[msg.sender].add(balances[_receiver]) == previousBalances);
return true;
}
/*****************************************************************************
* Used for returning ethereum payment requests done by shop one by one. *
******************************************************************************/
function getRequestsCount() public view returns (uint256) {
return ethereumPaymentRequests.length;
}
/*****************************************************************************
* Used for returning user buy requests one by one. *
******************************************************************************/
function getUserRequestsBuyCount() public view returns (uint256) {
return buyingRequests.length;
}
/****************************************************************************
* Shop accepts the request and user is notified. *
* *
* shop ship the product if phisical. *
* *
* @param _index *
*****************************************************************************/
function finalizeUserRequestBuy(uint _index) public onlyShop {
BuyingRequest storage buyingRequest = buyingRequests[_index];
// Check if the product of the request is not reject.
require(!buyingRequests[_index].rejected);
// Check if the product of the request is still not shipped.
require(!buyingRequests[_index].shipped);
// Set the request to shipped, this must be done after the product is shipped phisically by the shop.
buyingRequest.shipped = true;
}
/****************************************************************************
* Shop rejected the request and user is refunded with tokens *
* *
* If the product has been shipped it can still be rejected *
* tokens should be given back later *
* *
* @param _index *
*****************************************************************************/
function rejectUserRequestBuy(uint _index) public onlyShop {
BuyingRequest storage buyingRequest = buyingRequests[_index];
// Check if the product of the request is still not rejected.
require(!buyingRequests[_index].rejected);
// Check if the product of the request is still not shipped.
require(!buyingRequests[_index].shipped);
// Value convertion
uint value = buyingRequest.value * 10 ** uint256(decimals);
// Save for the future assertion.
uint previousBalances = balances[buyingRequest.shop].add(balances[buyingRequest.user]);
// Subtract the token amount from the shop.
balances[buyingRequest.shop] = balances[buyingRequest.shop].sub(value);
// Give back the token amount to the user.
balances[buyingRequest.user] = balances[buyingRequest.user].add(value);
// Emit the Transfer event.
emit Transfer(buyingRequest.shop, buyingRequest.user, value);
// Asserts are used to use static analysis to find bugs in code. They should never fail.
assert(balances[buyingRequest.shop].add(balances[buyingRequest.user]) == previousBalances);
// Set the request as rejected.
buyingRequest.rejected = true;
}
/****************************************************************************
* Owner accepts the request and shop is payed in eth. *
* *
* Owner finalize the request manually. *
* *
* @param _index *
*****************************************************************************/
function finalizeRequestEthereum(uint _index) public onlyOwner payable {
EthereumPaymentRequest storage ethereumPaymentRequest = ethereumPaymentRequests[_index];
// Check if not rejected.
require(!ethereumPaymentRequests[_index].rejected);
// Check if still not finalized.
require(!ethereumPaymentRequests[_index].completed);
// Convert Token to ethereum.
uint256 ethValue = ethereumPaymentRequest.value.div(RATE);
// Trasfer ethereum amount to the shop.
ethereumPaymentRequest.shop.transfer(ethValue);
// Set shop request status to completed.
ethereumPaymentRequest.completed = true;
}
/****************************************************************************
* Owner reject the request and shop is refunded with tokens *
* *
* @param _index *
*****************************************************************************/
function rejectRequestEthereum(uint _index) public onlyOwner {
EthereumPaymentRequest storage ethereumPaymentRequest = ethereumPaymentRequests[_index];
// Check if already finalized.
require(!ethereumPaymentRequests[_index].completed);
// Check if the product of the request is still not rejected.
require(!ethereumPaymentRequests[_index].rejected);
// Value convertion.
uint value = ethereumPaymentRequest.value * 10 ** uint256(decimals);
// Save for the future assertion.
uint previousBalances = balances[owner].add(balances[ethereumPaymentRequest.shop]);
// Subtract the token amount from the owner.
balances[owner] = balances[owner].sub(value);
// Give bacje the token amount to the shop.
balances[ethereumPaymentRequest.shop] = balances[ethereumPaymentRequest.shop].add(value);
// Emit the Transfer event.
emit Transfer(owner, ethereumPaymentRequest.shop, value);
// Asserts are used to use static analysis to find bugs in code. They should never fail.
assert(balances[owner].add(balances[ethereumPaymentRequest.shop]) == previousBalances);
// Set the shop payment request as rejected.
ethereumPaymentRequest.rejected = true;
}
}
| Owner reject the request and shop is refunded with tokens _index / Check if already finalized. Check if the product of the request is still not rejected. Value convertion. Save for the future assertion. Subtract the token amount from the owner. Give bacje the token amount to the shop. Emit the Transfer event. Asserts are used to use static analysis to find bugs in code. They should never fail. Set the shop payment request as rejected. | function rejectRequestEthereum(uint _index) public onlyOwner {
EthereumPaymentRequest storage ethereumPaymentRequest = ethereumPaymentRequests[_index];
require(!ethereumPaymentRequests[_index].completed);
require(!ethereumPaymentRequests[_index].rejected);
uint value = ethereumPaymentRequest.value * 10 ** uint256(decimals);
uint previousBalances = balances[owner].add(balances[ethereumPaymentRequest.shop]);
balances[owner] = balances[owner].sub(value);
balances[ethereumPaymentRequest.shop] = balances[ethereumPaymentRequest.shop].add(value);
emit Transfer(owner, ethereumPaymentRequest.shop, value);
assert(balances[owner].add(balances[ethereumPaymentRequest.shop]) == previousBalances);
ethereumPaymentRequest.rejected = true;
}
| 12,744,831 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.0;
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
/**
* @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: node_modules\@openzeppelin\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 in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin\contracts\math\SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: node_modules\@openzeppelin\contracts\GSN\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 msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin\contracts\access\Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\interfaces\IUniswapV2Pair.sol
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts\interfaces\IUniswapV2Factory.sol
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() 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;
function setMigrator(address) external;
}
// File: contracts\libraries\SafeMath.sol
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts\libraries\UniswapV2Library.sol
library UniswapV2Library {
using SafeMathUniswap for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File: contracts\Timelock.sol
contract Timelock {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
uint public constant GRACE_PERIOD = 14 days;
uint public constant MINIMUM_DELAY = 24 hours;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
bool public admin_initialized;
mapping (bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint delay_) {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
admin_initialized = false;
}
receive() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
// allows one time setting of admin for deployment purposes
if (admin_initialized) {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
} else {
require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin.");
admin_initialized = true;
}
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(address target, uint _value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, _value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value:_value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, _value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
// File: contracts\VampireAdapter.sol
contract Victim{}
library VampireAdapter {
// Victim info
function rewardToken(Victim victim) external view returns (IERC20) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("rewardToken()"));
require(success, "rewardToken() staticcall failed.");
return abi.decode(result, (IERC20));
}
function poolCount(Victim victim) external view returns (uint256) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("poolCount()"));
require(success, "poolCount() staticcall failed.");
return abi.decode(result, (uint256));
}
function sellableRewardAmount(Victim victim) external view returns (uint256) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("sellableRewardAmount()"));
require(success, "sellableRewardAmount() staticcall failed.");
return abi.decode(result, (uint256));
}
// Victim actions
function sellRewardForWeth(Victim victim, uint256 rewardAmount, address to) external returns(uint256) {
(bool success, bytes memory result) = address(victim).delegatecall(abi.encodeWithSignature("sellRewardForWeth(address,uint256,address)", address(victim), rewardAmount, to));
require(success, "sellRewardForWeth(uint256 rewardAmount, address to) delegatecall failed.");
return abi.decode(result, (uint256));
}
// Pool info
function lockableToken(Victim victim, uint256 poolId) external view returns (IERC20) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("lockableToken(uint256)", poolId));
require(success, "lockableToken(uint256 poolId) staticcall failed.");
return abi.decode(result, (IERC20));
}
function lockedAmount(Victim victim, uint256 poolId) external view returns (uint256) {
// note the impersonation
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("lockedAmount(address,uint256)", address(this), poolId));
require(success, "lockedAmount(uint256 poolId) staticcall failed.");
return abi.decode(result, (uint256));
}
// Pool actions
function deposit(Victim victim, uint256 poolId, uint256 amount) external {
(bool success,) = address(victim).delegatecall(abi.encodeWithSignature("deposit(address,uint256,uint256)", address(victim), poolId, amount));
require(success, "deposit(uint256 poolId, uint256 amount) delegatecall failed.");
}
function withdraw(Victim victim, uint256 poolId, uint256 amount) external {
(bool success,) = address(victim).delegatecall(abi.encodeWithSignature("withdraw(address,uint256,uint256)", address(victim), poolId, amount));
require(success, "withdraw(uint256 poolId, uint256 amount) delegatecall failed.");
}
function claimReward(Victim victim, uint256 poolId) external {
(bool success,) = address(victim).delegatecall(abi.encodeWithSignature("claimReward(address,uint256)", address(victim), poolId));
require(success, "claimReward(uint256 poolId) delegatecall failed.");
}
function emergencyWithdraw(Victim victim, uint256 poolId) external {
(bool success,) = address(victim).delegatecall(abi.encodeWithSignature("emergencyWithdraw(address,uint256)", address(victim), poolId));
require(success, "emergencyWithdraw(uint256 poolId) delegatecall failed.");
}
// Service methods
function poolAddress(Victim victim, uint256 poolId) external view returns (address) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("poolAddress(uint256)", poolId));
require(success, "poolAddress(uint256 poolId) staticcall failed.");
return abi.decode(result, (address));
}
function rewardToWethPool(Victim victim) external view returns (address) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("rewardToWethPool()"));
require(success, "rewardToWethPool() staticcall failed.");
return abi.decode(result, (address));
}
}
// File: @openzeppelin\contracts\token\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 {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) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts\NerdlingToken.sol
contract NerdlingToken is ERC20("Nerdling Token", "NERDLING"), Ownable {
using SafeMath for uint256;
event Minted(address indexed minter, address indexed receiver, uint mintAmount);
event Burned(address indexed burner, uint burnAmount);
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
emit Minted(owner(), _to, _amount);
}
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
emit Burned(msg.sender, _amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override virtual {
_moveDelegates(_delegates[from], _delegates[to], amount);
}
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "NERDLING::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "NERDLING::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "NERDLING::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "NERDLING::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying NERDLINGs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "NERDLING::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts\MasterVampire.sol
contract MasterVampire is Ownable, Timelock {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using VampireAdapter for Victim;
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
struct PoolInfo {
Victim victim;
uint256 victimPoolId;
uint256 rewardPerBlock;
uint256 lastRewardBlock;
uint256 accNerdlingPerShare;
uint256 rewardDrainModifier;
uint256 wethDrainModifier;
}
NerdlingToken public nerdling;
IERC20 weth;
IUniswapV2Pair nerdlingWethPair;
address public drainAddress;
address public fundAddress = address(0x289026a9018D5AA8CB05f228dd9460C1229aaf81);
address public poolRewardUpdater;
address public devAddress;
uint256 public constant DEV_FEE = 1;
uint256 public constant REWARD_START_BLOCK = 11180000; // Mon Nov 02 2020 09:30:00 PM UTC
uint256 public constant DURATION_BLOCK = 174545; // Blocks for 30 days
uint256 public constant DAILY_BLOCK = 5818; // 24 * 3600 / 14.85(seconds per block)
mapping(uint256 => uint256) private _drainQueue;
uint256 poolRewardLimiter;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 private _randomSeed;
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);
modifier onlyDev() {
require(devAddress == _msgSender(), "not dev");
_;
}
modifier onlyRewardUpdater() {
require(poolRewardUpdater == _msgSender(), "not reward updater");
_;
}
constructor(
NerdlingToken _nerdling,
address _drainAddress
) Timelock(msg.sender, 24 hours) {
poolRewardLimiter = 300 ether;
nerdling = _nerdling;
drainAddress = _drainAddress;
devAddress = msg.sender;
weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IUniswapV2Factory uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
nerdlingWethPair = IUniswapV2Pair(uniswapFactory.getPair(address(weth), address(nerdling)));
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(Victim _victim, uint256 _victimPoolId, uint256 _rewardPerBlock, uint256 _rewardDrainModifier, uint256 _wethDrainModifier) public onlyOwner {
require(_rewardPerBlock <= poolRewardLimiter, "Pool reward per block is too high");
poolInfo.push(PoolInfo({
victim: _victim,
victimPoolId: _victimPoolId,
rewardPerBlock: _rewardPerBlock,
rewardDrainModifier: _rewardDrainModifier,
wethDrainModifier: _wethDrainModifier,
lastRewardBlock: block.number < REWARD_START_BLOCK ? REWARD_START_BLOCK : block.number,
accNerdlingPerShare: 0
}));
}
function updatePoolRewardLimiter(uint256 _poolRewardLimiter) public onlyOwner {
poolRewardLimiter = _poolRewardLimiter;
}
function updateRewardPerBlock(uint256 _pid, uint256 _rewardPerBlock) public onlyRewardUpdater {
require(_rewardPerBlock <= poolRewardLimiter, "Pool reward per block is too high");
updatePool(_pid);
poolInfo[_pid].rewardPerBlock = _rewardPerBlock;
}
function updateRewardPerBlockMassive(uint256[] memory pids, uint256[] memory rewards) public onlyRewardUpdater {
require(pids.length == rewards.length, "-__-");
for (uint i = 0; i < pids.length; i++) {
uint256 pid = pids[i];
uint256 rewardPerBlock = rewards[i];
require(rewardPerBlock <= poolRewardLimiter, "Pool reward per block is too high");
updatePool(pid);
poolInfo[pid].rewardPerBlock = rewardPerBlock;
}
}
function updateVictimInfo(uint256 _pid, address _victim, uint256 _victimPoolId) public onlyOwner {
poolInfo[_pid].victim = Victim(_victim);
poolInfo[_pid].victimPoolId = _victimPoolId;
}
function updatePoolDrain(uint256 _pid, uint256 _rewardDrainModifier, uint256 _wethDrainModifier) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
pool.rewardDrainModifier = _rewardDrainModifier;
pool.wethDrainModifier = _wethDrainModifier;
}
function updateDevAddress(address _devAddress) public onlyDev {
devAddress = _devAddress;
}
function updateDrainAddress(address _drainAddress) public onlyOwner {
drainAddress = _drainAddress;
}
function updateRewardUpdaterAddress(address _poolRewardUpdater) public onlyOwner {
poolRewardUpdater = _poolRewardUpdater;
}
function pendingNerdling(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accNerdlingPerShare = pool.accNerdlingPerShare;
uint256 lpSupply = _pid == 0 ? nerdlingWethPair.balanceOf(address(this)) : pool.victim.lockedAmount(pool.victimPoolId);
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocksToReward = block.number.sub(pool.lastRewardBlock);
uint256 nerdlingReward = blocksToReward.mul(pool.rewardPerBlock);
accNerdlingPerShare = accNerdlingPerShare.add(nerdlingReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accNerdlingPerShare).div(1e12).sub(user.rewardDebt);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = _pid == 0 ? nerdlingWethPair.balanceOf(address(this)) : pool.victim.lockedAmount(pool.victimPoolId);
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 blocksToReward = block.number.sub(pool.lastRewardBlock);
uint256 rewardPerBlock = pool.rewardPerBlock;
uint256 passedBlock = block.number.sub(REWARD_START_BLOCK);
uint256 decreasedRewardPerBlock = rewardPerBlock.mul(DURATION_BLOCK).mul(DURATION_BLOCK).div(DURATION_BLOCK.mul(DURATION_BLOCK).add(passedBlock.mul(passedBlock)));
uint256 nerdlingReward = blocksToReward.mul(decreasedRewardPerBlock);
nerdling.mint(devAddress, nerdlingReward.mul(DEV_FEE).div(100));
nerdling.mint(address(this), nerdlingReward);
pool.accNerdlingPerShare = pool.accNerdlingPerShare.add(nerdlingReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
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.accNerdlingPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeNerdlingTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
if(_pid == 0) {
IERC20(address(nerdlingWethPair)).safeTransferFrom(address(msg.sender), address(this), _amount);
} else {
pool.victim.lockableToken(pool.victimPoolId).safeTransferFrom(address(msg.sender), address(this), _amount);
pool.victim.deposit(pool.victimPoolId, _amount);
}
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accNerdlingPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
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.accNerdlingPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeNerdlingTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
if(_pid == 0) {
IERC20(address(nerdlingWethPair)).safeTransfer(address(msg.sender), _amount);
} else {
pool.victim.withdraw(pool.victimPoolId, _amount);
pool.victim.lockableToken(pool.victimPoolId).safeTransfer(address(msg.sender), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accNerdlingPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if(_pid == 0) {
IERC20(address(nerdlingWethPair)).safeTransfer(address(msg.sender), user.amount);
} else {
pool.victim.withdraw(pool.victimPoolId, user.amount);
pool.victim.lockableToken(pool.victimPoolId).safeTransfer(address(msg.sender), user.amount);
}
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
function safeNerdlingTransfer(address _to, uint256 _amount) internal {
uint256 balance = nerdling.balanceOf(address(this));
if (_amount > balance) {
nerdling.transfer(_to, balance);
} else {
nerdling.transfer(_to, _amount);
}
}
function drain(uint256 _pid) public {
require(_pid != 0, "Can't drain from myself");
if (_drainQueue[_pid] == 0) {
_drainQueue[_pid] = block.number;
} else {
if (_drainQueue[_pid] + random(DAILY_BLOCK) < block.number) {
_drainQueue[_pid] = block.number;
_drain(_pid);
}
}
}
function random(uint256 _range) private returns (uint256) {
_randomSeed++;
return uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, _randomSeed))) % _range;
}
function _drain(uint256 _pid) private {
PoolInfo storage pool = poolInfo[_pid];
Victim victim = pool.victim;
uint256 victimPoolId = pool.victimPoolId;
uint256 rewardDrainModifier = pool.rewardDrainModifier;
victim.claimReward(victimPoolId);
IERC20 rewardToken = victim.rewardToken();
uint256 claimedReward = rewardToken.balanceOf(address(this));
uint256 rewardDrainAmount = claimedReward.mul(rewardDrainModifier).div(1000);
if(rewardDrainAmount > 0) {
rewardToken.transfer(drainAddress, rewardDrainAmount);
claimedReward = claimedReward.sub(rewardDrainAmount);
}
uint256 sellableAmount = victim.sellableRewardAmount();
if(sellableAmount < claimedReward) { // victim is drained empty
claimedReward = sellableAmount;
}
if(claimedReward == 0) {
return;
}
uint256 wethDrainModifier = pool.wethDrainModifier;
uint256 wethReward = victim.sellRewardForWeth(claimedReward, address(this));
uint256 wethDrainAmount = wethReward.mul(wethDrainModifier).div(1000);
if(wethDrainAmount > 0) {
weth.transfer(drainAddress, wethDrainAmount);
wethReward = wethReward.sub(wethDrainAmount);
}
address token0 = nerdlingWethPair.token0();
(uint reserve0, uint reserve1,) = nerdlingWethPair.getReserves();
(uint reserveInput, uint reserveOutput) = address(weth) == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
uint amountOutput = UniswapV2Library.getAmountOut(wethReward, reserveInput, reserveOutput);
(uint amount0Out, uint amount1Out) = address(weth) == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
weth.transfer(address(nerdlingWethPair), wethReward);
nerdlingWethPair.swap(amount0Out, amount1Out, address(this), new bytes(0));
amountOutput = amountOutput.div(2);
nerdling.transfer(fundAddress, amountOutput);
nerdling.burn(amountOutput);
}
} | Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/ | function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "NERDLING::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "NERDLING::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "NERDLING::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 5,843,460 |
./partial_match/1313161554/0xca9511B610bA5fc7E311FDeF9cE16050eE4449E9/sources/AuETH.sol | Retrieve the totalSupply & auTokenBalance of two accounts account1 The address whose data to be retrieved account2 The address whose data to be retrieved return (totalSupply, auTokenBalance of account1, auTokenBalance of account2)/ | function getSupplyDataOfTwoAccount(address account1, address account2) public view override returns (uint, uint, uint) {
return (totalSupply, accountTokens[account1], accountTokens[account2]);
}
| 16,916,138 |
pragma solidity ^0.4.18;
import './SafeMath.sol';
import './AssetRegistryStorage.sol';
import './IERC721Base.sol';
import './IERC721Receiver.sol';
import './ERC165.sol';
contract ERC721Base is AssetRegistryStorage, IERC721Base, ERC165 {
using SafeMath for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
bytes4 private constant InterfaceId_ERC165 = 0x01ffc9a7;
/*
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
bytes4 private constant Old_InterfaceId_ERC721 = 0x7c0633c6;
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
//
// Global Getters
//
/**
* @dev Gets the total amount of assets stored by the contract
* @return uint256 representing the total amount of assets
*/
function totalSupply() external view returns (uint256) {
return _totalSupply();
}
function _totalSupply() internal view returns (uint256) {
return _count;
}
//
// Asset-centric getter functions
//
/**
* @dev Queries what address owns an asset. This method does not throw.
* In order to check if the asset exists, use the `exists` function or check if the
* return value of this call is `0`.
* @return uint256 the assetId
*/
function ownerOf(uint256 assetId) external view returns (address) {
return _ownerOf(assetId);
}
function _ownerOf(uint256 assetId) internal view returns (address) {
return _holderOf[assetId];
}
//
// Holder-centric getter functions
//
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) external view returns (uint256) {
return _balanceOf(owner);
}
function _balanceOf(address owner) internal view returns (uint256) {
return _assetsOf[owner].length;
}
//
// Authorization getters
//
/**
* @dev Query whether an address has been authorized to move any assets on behalf of someone else
* @param operator the address that might be authorized
* @param assetHolder the address that provided the authorization
* @return bool true if the operator has been authorized to move any assets
*/
function isApprovedForAll(address assetHolder, address operator)
external view returns (bool)
{
return _isApprovedForAll(assetHolder, operator);
}
function _isApprovedForAll(address assetHolder, address operator)
internal view returns (bool)
{
return _operators[assetHolder][operator];
}
/**
* @dev Query what address has been particularly authorized to move an asset
* @param assetId the asset to be queried for
* @return bool true if the asset has been approved by the holder
*/
function getApproved(uint256 assetId) external view returns (address) {
return _getApprovedAddress(assetId);
}
function getApprovedAddress(uint256 assetId) external view returns (address) {
return _getApprovedAddress(assetId);
}
function _getApprovedAddress(uint256 assetId) internal view returns (address) {
return _approval[assetId];
}
/**
* @dev Query if an operator can move an asset.
* @param operator the address that might be authorized
* @param assetId the asset that has been `approved` for transfer
* @return bool true if the asset has been approved by the holder
*/
function isAuthorized(address operator, uint256 assetId) external view returns (bool) {
return _isAuthorized(operator, assetId);
}
function _isAuthorized(address operator, uint256 assetId) internal view returns (bool)
{
require(operator != 0);
address owner = _ownerOf(assetId);
if (operator == owner) {
return true;
}
return _isApprovedForAll(owner, operator) || _getApprovedAddress(assetId) == operator;
}
//
// Authorization
//
/**
* @dev Authorize a third party operator to manage (send) msg.sender's asset
* @param operator address to be approved
* @param authorized bool set to true to authorize, false to withdraw authorization
*/
function setApprovalForAll(address operator, bool authorized) external {
return _setApprovalForAll(operator, authorized);
}
function _setApprovalForAll(address operator, bool authorized) internal {
if (authorized) {
require(!_isApprovedForAll(msg.sender, operator));
_addAuthorization(operator, msg.sender);
} else {
require(_isApprovedForAll(msg.sender, operator));
_clearAuthorization(operator, msg.sender);
}
emit ApprovalForAll(msg.sender, operator, authorized);
}
/**
* @dev Authorize a third party operator to manage one particular asset
* @param operator address to be approved
* @param assetId asset to approve
*/
function approve(address operator, uint256 assetId) external {
address holder = _ownerOf(assetId);
require(msg.sender == holder || _isApprovedForAll(msg.sender, holder));
require(operator != holder);
if (_getApprovedAddress(assetId) != operator) {
_approval[assetId] = operator;
emit Approval(holder, operator, assetId);
}
}
function _addAuthorization(address operator, address holder) private {
_operators[holder][operator] = true;
}
function _clearAuthorization(address operator, address holder) private {
_operators[holder][operator] = false;
}
//
// Internal Operations
//
function _addAssetTo(address to, uint256 assetId) internal {
_holderOf[assetId] = to;
uint256 length = _balanceOf(to);
_assetsOf[to].push(assetId);
_indexOfAsset[assetId] = length;
_count = _count.add(1);
}
function _removeAssetFrom(address from, uint256 assetId) internal {
uint256 assetIndex = _indexOfAsset[assetId];
uint256 lastAssetIndex = _balanceOf(from).sub(1);
uint256 lastAssetId = _assetsOf[from][lastAssetIndex];
_holderOf[assetId] = 0;
// Insert the last asset into the position previously occupied by the asset to be removed
_assetsOf[from][assetIndex] = lastAssetId;
// Resize the array
_assetsOf[from][lastAssetIndex] = 0;
_assetsOf[from].length--;
// Remove the array if no more assets are owned to prevent pollution
if (_assetsOf[from].length == 0) {
delete _assetsOf[from];
}
// Update the index of positions for the asset
_indexOfAsset[assetId] = 0;
_indexOfAsset[lastAssetId] = assetIndex;
_count = _count.sub(1);
}
function _clearApproval(address holder, uint256 assetId) internal {
if (_ownerOf(assetId) == holder && _approval[assetId] != 0) {
_approval[assetId] = 0;
emit Approval(holder, 0, assetId);
}
}
//
// Supply-altering functions
//
function _generate(uint256 assetId, address beneficiary) internal {
require(_holderOf[assetId] == 0);
_addAssetTo(beneficiary, assetId);
emit Transfer(0, beneficiary, assetId);
}
function _destroy(uint256 assetId) internal {
address holder = _holderOf[assetId];
require(holder != 0);
_removeAssetFrom(holder, assetId);
emit Transfer(holder, 0, assetId);
}
//
// Transaction related operations
//
modifier onlyHolder(uint256 assetId) {
require(_ownerOf(assetId) == msg.sender);
_;
}
modifier onlyAuthorized(uint256 assetId) {
require(_isAuthorized(msg.sender, assetId));
_;
}
modifier isCurrentOwner(address from, uint256 assetId) {
require(_ownerOf(assetId) == from);
_;
}
modifier isDestinataryDefined(address destinatary) {
require(destinatary != 0);
_;
}
modifier destinataryIsNotHolder(uint256 assetId, address to) {
require(_ownerOf(assetId) != to);
_;
}
/**
* @dev Alias of `safeTransferFrom(from, to, assetId, '')`
*
* @param from address that currently owns an asset
* @param to address to receive the ownership of the asset
* @param assetId uint256 ID of the asset to be transferred
*/
function safeTransferFrom(address from, address to, uint256 assetId) external {
return _doTransferFrom(from, to, assetId, '', true);
}
/**
* @dev Securely transfers the ownership of a given asset from one address to
* another address, calling the method `onNFTReceived` on the target address if
* there's code associated with it
*
* @param from address that currently owns an asset
* @param to address to receive the ownership of the asset
* @param assetId uint256 ID of the asset to be transferred
* @param userData bytes arbitrary user information to attach to this transfer
*/
function safeTransferFrom(address from, address to, uint256 assetId, bytes userData) external {
return _doTransferFrom(from, to, assetId, userData, true);
}
/**
* @dev Transfers the ownership of a given asset from one address to another address
* Warning! This function does not attempt to verify that the target address can send
* tokens.
*
* @param from address sending the asset
* @param to address to receive the ownership of the asset
* @param assetId uint256 ID of the asset to be transferred
*/
function transferFrom(address from, address to, uint256 assetId) external {
return _doTransferFrom(from, to, assetId, '', false);
}
function _doTransferFrom(
address from,
address to,
uint256 assetId,
bytes userData,
bool doCheck
)
onlyAuthorized(assetId)
internal
{
_moveToken(from, to, assetId, userData, doCheck);
}
function _moveToken(
address from,
address to,
uint256 assetId,
bytes userData,
bool doCheck
)
isDestinataryDefined(to)
destinataryIsNotHolder(assetId, to)
isCurrentOwner(from, assetId)
private
{
address holder = _holderOf[assetId];
_clearApproval(holder, assetId);
_removeAssetFrom(holder, assetId);
_addAssetTo(to, assetId);
emit Transfer(holder, to, assetId);
if (doCheck && _isContract(to)) {
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
require(
IERC721Receiver(to).onERC721Received(
msg.sender, holder, assetId, userData
) == ERC721_RECEIVED
);
}
}
/**
* Internal function that moves an asset from one holder to another
*/
/**
* @dev Returns `true` if the contract implements `interfaceID` and `interfaceID` is not 0xffffffff, `false` otherwise
* @param _interfaceID The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == 0xffffffff) {
return false;
}
return _interfaceID == InterfaceId_ERC165 || _interfaceID == Old_InterfaceId_ERC721 || _interfaceID == InterfaceId_ERC721;
}
//
// Utilities
//
function _isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
| Returns `true` if the contract implements `interfaceID` and `interfaceID` is not 0xffffffff, `false` otherwise _interfaceID The interface identifier, as specified in ERC-165/ | function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == 0xffffffff) {
return false;
}
return _interfaceID == InterfaceId_ERC165 || _interfaceID == Old_InterfaceId_ERC721 || _interfaceID == InterfaceId_ERC721;
}
| 1,819,717 |
// 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);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/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 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/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @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/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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;
}
}
// File erc721a/contracts/[email protected]
// Creator: Chiru Labs
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error AuxQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_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)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), 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[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.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);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.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();
}
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/Ownable.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);
}
}
// File @openzeppelin/contracts/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File @openzeppelin/contracts/utils/cryptography/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.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 = 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));
}
}
// File @openzeppelin/contracts/utils/cryptography/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.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);
}
}
// File contracts/NFT.sol
// import "hardhat/console.sol";
contract SecretDriverClub2 is EIP712, ERC721A, Ownable {
using Strings for uint256;
string private constant SIGNING_DOMAIN = "NFT";
string private constant SIGNATURE_VERSION = "1";
uint256 public constant MAX_SUPPLY = 500;
uint256 public constant MAX_PUBLIC_MINT_PER_TRANSACTION = 100;
address private whiteListeSigner =
0x5000Af2DE4F3737C1e0853BC5CdD3AC5F0fEE152;
bool public whitelistSaleIsActive = false;
mapping(address => uint256) public whitelistAmountMintedPerWallet;
bool public saleIsActive = false;
uint256 public tokenPrice = 0.1 ether;
struct FeesWallets {
address wallet;
uint256 fees; // Percentage X 100
}
FeesWallets[] public feesWallets;
struct Reveal {
uint256 index;
uint256 amount;
uint256 endIndex;
uint256 rand;
}
Reveal[] private reveals;
string public unrevealedTokenUri =
"ipfs://QmXmoYbKJuZBu4H4Tkzvi8gwbJANQJjqcFqqaNnjHXDgCF";
bool public isRevealed = false;
bool public isBaseUrlFrozen = false;
uint256 public startingIndex = 0;
string public baseUri;
constructor()
ERC721A("Secret Driver Club #2", "SDC2")
EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION)
{
// Smartcontract Dev fees
feesWallets.push(
FeesWallets(0xffe6788BE411C4353B3b2c546D0401D4d8B2b3eD, 800)
);
}
function buyTokens(uint256 numberOfTokens) public payable {
require(saleIsActive, "sale not open");
applyBuyToken(numberOfTokens, tokenPrice);
}
function applyBuyToken(uint256 numberOfTokens, uint256 price) private {
uint256 ts = totalSupply();
require(msg.sender == tx.origin);
require(ts + numberOfTokens <= MAX_SUPPLY, "not enough supply");
require(price * numberOfTokens <= msg.value, "invalid ethers sent");
require(
numberOfTokens <= MAX_PUBLIC_MINT_PER_TRANSACTION,
"too many token per transaction"
);
_safeMint(msg.sender, numberOfTokens);
}
function buyTokenWithWhiteList(
uint256 numberOfTokens,
uint256 price,
uint256 maxPerWallet,
bytes calldata signature
) public payable {
require(whitelistSaleIsActive, "whitelist sale not open");
verifyWhitelistSignature(signature, msg.sender, price, maxPerWallet);
whitelistAmountMintedPerWallet[msg.sender] += numberOfTokens;
require(
whitelistAmountMintedPerWallet[msg.sender] <= maxPerWallet,
"Max minted with whitelist"
);
applyBuyToken(numberOfTokens, price);
}
function verifyWhitelistSignature(
bytes calldata signature,
address targetWallet,
uint256 price,
uint256 maxPerWallet
) internal view {
bytes32 digest = hashWhitelisteSignature(targetWallet, price, maxPerWallet);
address result = ECDSA.recover(digest, signature);
require(result == whiteListeSigner, "bad signature");
}
function hashWhitelisteSignature(address targetWallet, uint256 price, uint256 maxPerWallet)
internal
view
returns (bytes32)
{
return
_hashTypedDataV4(
keccak256(
abi.encode(
keccak256("Ticket(address wallet,uint256 price,uint256 maxPerWallet)"),
targetWallet,
price,
maxPerWallet
)
)
);
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
if (reveals.length == 0) {
return unrevealedTokenUri;
}
uint256 baseReveal = reveals[0].rand % MAX_SUPPLY;
for (uint256 i = 0; i < reveals.length; i++) {
Reveal memory currentReveal = reveals[i];
if (
tokenId >= currentReveal.index &&
tokenId <= currentReveal.endIndex
) {
uint256 localStart = (currentReveal.rand %
currentReveal.amount);
uint256 localId = currentReveal.index +
((localStart + tokenId) % currentReveal.amount);
uint256 baseTokenId = (localId + (baseReveal * 7)) % MAX_SUPPLY;
return
bytes(baseUri).length > 0
? string(
abi.encodePacked(baseUri, baseTokenId.toString())
)
: "";
}
}
return unrevealedTokenUri;
}
// Admins functions ############################################################################################
function reveal() external onlyOwner {
Reveal memory newReveal;
uint256 supply = totalSupply();
uint256 rand = uint256(
keccak256(abi.encodePacked(block.difficulty, block.timestamp))
) % block.timestamp;
if (reveals.length == 0) {
newReveal.index = 0;
newReveal.amount = supply;
newReveal.endIndex = supply - 1;
newReveal.rand = rand;
} else {
uint256 index = reveals[reveals.length - 1].endIndex + 1;
uint256 amount = supply - index;
uint256 endIndex = supply - 1;
newReveal.index = index;
newReveal.amount = amount;
newReveal.endIndex = endIndex;
newReveal.rand = rand;
}
reveals.push(newReveal);
}
function setBaseURI(string memory newBaseUri) external onlyOwner {
require(!isBaseUrlFrozen, "Base URI is frozen");
baseUri = newBaseUri;
}
function freezeBaseUrl() external onlyOwner {
isBaseUrlFrozen = true;
}
function setUnrevealedURI(string memory unrevealedTokenUri_)
external
onlyOwner
{
unrevealedTokenUri = unrevealedTokenUri_;
}
function setSaleState(bool newState) public onlyOwner {
saleIsActive = newState;
}
function setWhitelisteSaleState(bool newState) public onlyOwner {
whitelistSaleIsActive = newState;
}
function setWhiteListSigner(address signer) external onlyOwner {
whiteListeSigner = signer;
}
function setTokenPrice(uint256 priceInWei) external onlyOwner {
tokenPrice = priceInWei;
}
function addFeesWallet(address wallet, uint256 feesPercentageX100)
public
onlyOwner
{
uint256 totalFees = 0;
for (uint256 i = 0; i < feesWallets.length; i++) {
totalFees += feesWallets[i].fees;
}
require(
totalFees + feesPercentageX100 < 10000,
"Total percent over 100"
);
feesWallets.push(FeesWallets(wallet, feesPercentageX100));
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
for (uint256 i = 0; i < feesWallets.length; i++) {
uint256 fee = (balance * feesWallets[i].fees) / 10000;
payable(feesWallets[i].wallet).call{value: fee}("");
}
payable(msg.sender).call{value: address(this).balance}("");
}
} | Transfers `tokenId` from `from` to `to`. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./ Clear approvals from the previous owner 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 2256. 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. This will suffice for checking _exists(nextTokenId), as a burned slot cannot contain the zero address. | function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
| 22,019 |
./full_match/4/0x66A9e129cEa9D102CDD518C142C412C3CE4E9165/sources/contracts/PyscheArt.sol | if there exists 5st generation holders, the bonus has 50% probability to be stolen by 5st gen holders. | function stealBonus(uint256 bredBonus, uint256 seed) internal returns(bool) {
uint256 len = tokensOf5thGen.length;
if (len > 0 && random(seed, 0) % 2 == 0) {
uint256 bonusSteal = bredBonus / len;
for (uint256 i; i < len; i ++) {
address holder = ownerOf(tokensOf5thGen[i]);
if (holder != address(0)) {
payable(holder).transfer(bonusSteal);
}
}
return true;
}
return false;
}
| 12,379,797 |
./partial_match/42161/0xe068a01e11aCfA03A4c8de63dAd451E77a22CFfF/sources/contracts/SmartContractWallet.sol | approve spender to spend this contract's erc20 token | function approve(address tokenAddress, address spender, uint256 value) public onlyOwner returns (bool){
return IERC20(tokenAddress).approve(spender, value);
}
| 3,493,306 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import {DSTest} from "ds-test/test.sol";
import {Caller} from "../test/utils/Caller.sol";
import {Guarded} from "./Guarded.sol";
contract GuardedInstance is Guarded {
constructor() Guarded() {
this;
}
function guardedMethod() external view checkCaller {
this;
}
function guardedMethodRoot() external view checkCaller {
this;
}
}
contract GuardedTest is DSTest {
GuardedInstance internal guarded;
function setUp() public {
guarded = new GuardedInstance();
}
function test_custom_role() public {
Caller user = new Caller();
bool ok;
bool canCall;
// Should not be able to call method
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethod.selector)
);
assertTrue(
ok == false,
"Cannot call guarded method before adding permissions"
);
// Adding permission should allow user to call method
guarded.allowCaller(guarded.guardedMethod.selector, address(user));
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethod.selector)
);
assertTrue(ok, "Can call method after adding permissions");
// User has custom permission to call method
canCall = guarded.canCall(
guarded.guardedMethod.selector,
address(user)
);
assertTrue(canCall, "User has permission");
// Removing role disables permission
guarded.blockCaller(guarded.guardedMethod.selector, address(user));
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethod.selector)
);
assertTrue(
ok == false,
"Cannot call method after removing permissions"
);
// User does not have custom role
canCall = guarded.canCall(
guarded.guardedMethod.selector,
address(user)
);
assertTrue(canCall == false, "User does not have permission");
}
function test_root_role() public {
Caller user = new Caller();
bool ok;
// Should not be able to call method
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethodRoot.selector)
);
assertTrue(ok == false, "Root can call method");
// Adding ANY_SIG should allow user to call method
guarded.allowCaller(guarded.ANY_SIG(), address(user));
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethodRoot.selector)
);
assertTrue(ok, "User can call method after adding root permissions");
// User has senatus role
bool canCall = guarded.canCall(guarded.ANY_SIG(), address(user));
assertTrue(canCall, "User has permission");
// Removing senatus role disables permission
guarded.blockCaller(guarded.ANY_SIG(), address(user));
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethodRoot.selector)
);
assertTrue(
ok == false,
"Senatus cannot call method after removing permissions"
);
// User does not have senatus role
canCall = guarded.canCall(guarded.ANY_SIG(), address(user));
assertTrue(canCall == false, "User does not have role");
}
function test_root_has_god_mode_access() public {
Caller user = new Caller();
bool ok;
// Should not be able to call method
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethod.selector)
);
assertTrue(
ok == false,
"Cannot call guarded method before adding permissions"
);
// Adding senatus role should allow user to call method
guarded.allowCaller(guarded.ANY_SIG(), address(user));
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethod.selector)
);
assertTrue(ok, "Can call method after adding senatus role");
}
}
| Should not be able to call method Adding ANY_SIG should allow user to call method User has senatus role Removing senatus role disables permission User does not have senatus role | function test_root_role() public {
Caller user = new Caller();
bool ok;
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethodRoot.selector)
);
assertTrue(ok == false, "Root can call method");
guarded.allowCaller(guarded.ANY_SIG(), address(user));
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethodRoot.selector)
);
assertTrue(ok, "User can call method after adding root permissions");
bool canCall = guarded.canCall(guarded.ANY_SIG(), address(user));
assertTrue(canCall, "User has permission");
guarded.blockCaller(guarded.ANY_SIG(), address(user));
(ok, ) = user.externalCall(
address(guarded),
abi.encodeWithSelector(guarded.guardedMethodRoot.selector)
);
assertTrue(
ok == false,
"Senatus cannot call method after removing permissions"
);
canCall = guarded.canCall(guarded.ANY_SIG(), address(user));
assertTrue(canCall == false, "User does not have role");
}
| 14,075,428 |
pragma solidity 0.4.25;
import "../Network.sol";
////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @title Network main contract that takes some fee but returns actual dest amount as if FEE wasn't taken.
contract MaliciousNetwork2 is Network {
address public myWallet = 0x1234;
uint public myFeeWei = 10;
constructor(address _admin) public Network(_admin) { }
function setMyFeeWei(uint fee) public {
myFeeWei = fee;
}
/// @notice use token address TOMO_TOKEN_ADDRESS for tomo
/// @dev do one trade with a reserve
/// @param src Src token
/// @param amount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param reserve Reserve to use
/// @param validate If true, additional validations are applicable
/// @return true if trade is successful
function doReserveTrade(
TRC20 src,
uint amount,
TRC20 dest,
address destAddress,
uint expectedDestAmount,
ReserveInterface reserve,
uint conversionRate,
bool validate,
address walletId
)
internal
returns(bool)
{
uint callValue = 0;
if (src == dest) {
//this is for a "fake" trade when both src and dest are tomos.
if (destAddress != (address(this))) {
destAddress.transfer(amount - myFeeWei);
myWallet.transfer(myFeeWei);
}
return true;
}
if (src == TOMO_TOKEN_ADDRESS) {
callValue = amount;
}
// calculate expected fee for this transaction based on amount of Tomo
uint tomoValue = src == TOMO_TOKEN_ADDRESS ? callValue : expectedDestAmount;
uint feeInWei = tomoValue * feeForReserve[reserve] / 10000; // feePercent = 25 -> fee = 25/10000 = 0.25%
// reserve sends tokens/tomo to network. network sends it to destination
require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, feeInWei, validate));
if (destAddress != address(this)) {
//for token to token dest address is network. and Tomo / token already here...
if (dest == TOMO_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
} else {
require(dest.transfer(destAddress, (expectedDestAmount - myFeeWei)));
dest.transfer(myWallet, myFeeWei);
}
}
if (feeSharing != address(0)) {
require(address(this).balance >= feeInWei);
// transfer fee to feeSharing
require(feeSharing.handleFees.value(feeInWei)(walletId));
}
return true;
}
}
| use token address TOMO_TOKEN_ADDRESS for tomo do one trade with a reserve src Src token amount amount of src tokens dest Destination token destAddress Address to send tokens to reserve Reserve to use validate If true, additional validations are applicable return true if trade is successfulthis is for a "fake" trade when both src and dest are tomos.for token to token dest address is network. and Tomo / token already here... transfer fee to feeSharing | function doReserveTrade(
TRC20 src,
uint amount,
TRC20 dest,
address destAddress,
uint expectedDestAmount,
ReserveInterface reserve,
uint conversionRate,
bool validate,
address walletId
)
internal
returns(bool)
{
uint callValue = 0;
if (src == dest) {
if (destAddress != (address(this))) {
destAddress.transfer(amount - myFeeWei);
myWallet.transfer(myFeeWei);
}
return true;
}
if (src == TOMO_TOKEN_ADDRESS) {
callValue = amount;
}
if (destAddress != address(this)) {
if (dest == TOMO_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
require(dest.transfer(destAddress, (expectedDestAmount - myFeeWei)));
dest.transfer(myWallet, myFeeWei);
}
}
if (feeSharing != address(0)) {
require(address(this).balance >= feeInWei);
require(feeSharing.handleFees.value(feeInWei)(walletId));
}
return true;
}
| 12,720,451 |
pragma solidity ^0.4.25;
import "./Sequence.sol";
import "./lib/SignLib.sol";
/** term of project */
contract Term {
using SignLib for bytes32[4];
Sequence seq;
uint current; //currentTermNo
string name;
uint startSeq;
struct Range {
string termname;
uint start;
uint end;
}
address owner;
mapping(uint => Range) terms; //term [startno, endno]映射,theNumberAtWhichEachTermBeginsAndEnds。
constructor(address projectOwner) {
seq = new Sequence();
owner = projectOwner;
}
function newTerm(string termname, bytes32[4] sign) public returns (uint) {//新term
address txOrigin;
txOrigin = sign.checkSign();
require(owner == txOrigin, "Term:only project owner is authorized.");
require(bytes(termname).length > 0 && bytes(termname).length < 64, "termname should be not null and less than 64 long");
endCurTerm();
current = current + 1;
name = termname;
startSeq = seq.get();
terms[current] = Range(termname, startSeq, startSeq);
return current;
}
function getTerm() public view returns (uint, string){
return (current, name);
}
function getSeqNo() public returns (uint) {
return seq.get();
}
// endsTheCurrentPaymentDays
function endCurTerm() private {
uint end_seq = seq.getCurrent();
if (current > 1) {
terms[current] = Range(terms[current].termname, terms[current].start, end_seq);
}
}
// getsTheAddressOfTheCurrentContract
function getAddress() public view returns (address) {
return address(this);
}
}
| endsTheCurrentPaymentDays | function endCurTerm() private {
uint end_seq = seq.getCurrent();
if (current > 1) {
terms[current] = Range(terms[current].termname, terms[current].start, end_seq);
}
}
| 1,008,424 |
pragma solidity ^0.4.24;
// Contract setup ====================
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract JCLYLong is Pausable {
using SafeMath for *;
event KeyPurchase(address indexed purchaser, uint256 eth, uint256 amount);
event LeekStealOn();
address private constant WALLET_ETH_COM1 = 0x2509CF8921b95bef38DEb80fBc420Ef2bbc53ce3;
address private constant WALLET_ETH_COM2 = 0x18d9fc8e3b65124744553d642989e3ba9e41a95a;
// Configurables ====================
uint256 constant private rndInit_ = 1 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
// eth limiter
uint256 constant private ethLimiterRange1_ = 1e20;
uint256 constant private ethLimiterRange2_ = 5e20;
uint256 constant private ethLimiter1_ = 2e18;
uint256 constant private ethLimiter2_ = 7e18;
// whitelist range
uint256 constant private whitelistRange_ = 3 days;
// for price
uint256 constant private priceStage1_ = 500e18;
uint256 constant private priceStage2_ = 1000e18;
uint256 constant private priceStage3_ = 2000e18;
uint256 constant private priceStage4_ = 4000e18;
uint256 constant private priceStage5_ = 8000e18;
uint256 constant private priceStage6_ = 16000e18;
uint256 constant private priceStage7_ = 32000e18;
uint256 constant private priceStage8_ = 64000e18;
uint256 constant private priceStage9_ = 128000e18;
uint256 constant private priceStage10_ = 256000e18;
uint256 constant private priceStage11_ = 512000e18;
uint256 constant private priceStage12_ = 1024000e18;
// for gu phrase
uint256 constant private guPhrase1_ = 5 days;
uint256 constant private guPhrase2_ = 7 days;
uint256 constant private guPhrase3_ = 9 days;
uint256 constant private guPhrase4_ = 11 days;
uint256 constant private guPhrase5_ = 13 days;
uint256 constant private guPhrase6_ = 15 days;
uint256 constant private guPhrase7_ = 17 days;
uint256 constant private guPhrase8_ = 19 days;
uint256 constant private guPhrase9_ = 21 days;
uint256 constant private guPhrase10_ = 23 days;
// Data setup ====================
uint256 public contractStartDate_; // contract creation time
uint256 public allMaskGu_; // for sharing eth-profit by holding gu
uint256 public allGuGiven_; // for sharing eth-profit by holding gu
mapping (uint256 => uint256) public playOrders_; // playCounter => pID
// AIRDROP DATA
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
// LEEKSTEAL DATA
uint256 public leekStealPot_; // person who gets the first leeksteal wins part of this pot
uint256 public leekStealTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning leek steal
uint256 public leekStealToday_;
bool public leekStealOn_;
mapping (uint256 => uint256) public dayStealTime_; // dayNum => time that makes leekSteal available
// PLAYER DATA
uint256 public pID_; // total number of players
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
// mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => Datasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => Datasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (uint256 => Datasets.PlayerPhrases)) public plyrPhas_; // (pID => phraseID => data) player round data by player id & round id
// ROUND DATA
uint256 public rID_; // round id number / total rounds that have happened
mapping (uint256 => Datasets.Round) public round_; // (rID => data) round data
// PHRASE DATA
uint256 public phID_; // gu phrase ID
mapping (uint256 => Datasets.Phrase) public phrase_; // (phID_ => data) round data
// WHITELIST
mapping(address => bool) public whitelisted_Prebuy; // pID => isWhitelisted
// Constructor ====================
constructor()
public
{
// set genesis player
pIDxAddr_[WALLET_ETH_COM1] = 1;
plyr_[1].addr = WALLET_ETH_COM1;
pIDxAddr_[WALLET_ETH_COM2] = 2;
plyr_[2].addr = WALLET_ETH_COM2;
pID_ = 2;
}
// Modifiers ====================
modifier isActivated() {
require(activated_ == true);
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
// Public functions ====================
/**
* @dev emergency buy uses last stored affiliate ID
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// determine if player is new or not
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
pID_++; // grab their player ID and last aff ID, from player names contract
pIDxAddr_[msg.sender] = pID_; // set up player account
plyr_[pID_].addr = msg.sender; // set up player account
_pID = pID_;
}
// buy core
buyCore(_pID, plyr_[_pID].laff);
}
function buyXid(uint256 _affID)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// determine if player is new or not
uint256 _pID = pIDxAddr_[msg.sender]; // fetch player id
if (_pID == 0)
{
pID_++; // grab their player ID and last aff ID, from player names contract
pIDxAddr_[msg.sender] = pID_; // set up player account
plyr_[pID_].addr = msg.sender; // set up player account
_pID = pID_;
}
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own
if (_affID == 0 || _affID == _pID || _affID > pID_)
{
_affID = plyr_[_pID].laff; // use last stored affiliate code
// if affiliate code was given & its not the same as previously stored
}
else if (_affID != plyr_[_pID].laff)
{
if (plyr_[_pID].laff == 0)
plyr_[_pID].laff = _affID; // update last affiliate
else
_affID = plyr_[_pID].laff;
}
// buy core
buyCore(_pID, _affID);
}
function reLoadXid()
isActivated()
isHuman()
public
{
uint256 _pID = pIDxAddr_[msg.sender]; // fetch player ID
require(_pID > 0);
reLoadCore(_pID, plyr_[_pID].laff);
}
function reLoadCore(uint256 _pID, uint256 _affID)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// whitelist checking
if (_now < round_[rID_].strt + whitelistRange_) {
require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]);
}
// if round is active
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
uint256 _eth = withdrawEarnings(_pID, false);
plyr_[_pID].gen = 0;
// call core
core(_rID, _pID, _eth, _affID);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
endRound();
}
}
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// end the round (distributes pot)
round_[_rID].ended = true;
endRound();
// get their earnings
_eth = withdrawEarnings(_pID, true);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID, true);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
}
}
function updateWhitelist(address[] _addrs, bool _isWhitelisted)
public
onlyOwner
{
for (uint i = 0; i < _addrs.length; i++) {
whitelisted_Prebuy[_addrs[i]] = _isWhitelisted;
// determine if player is new or not
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
pID_++;
pIDxAddr_[_addrs[i]] = pID_;
plyr_[pID_].addr = _addrs[i];
}
}
}
function safeDrain()
public
onlyOwner
{
owner.transfer(this.balance);
}
// Getters ====================
function getPrice()
public
view
returns(uint256)
{
uint256 keys = keysRec(round_[rID_].eth, 1e18);
return (1e36 / keys);
}
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)),
(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)),
plyr_[_pID].aff,
plyr_[_pID].refund
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)),
(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)),
plyr_[_pID].aff,
plyr_[_pID].refund
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)),
(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)),
plyr_[_pID].aff,
plyr_[_pID].refund
);
}
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
_rID, //0
round_[_rID].allkeys, //1
round_[_rID].keys, //2
allGuGiven_, //3
round_[_rID].end, //4
round_[_rID].strt, //5
round_[_rID].pot, //6
plyr_[round_[_rID].plyr].addr, //7
round_[_rID].eth, //8
airDropTracker_ + (airDropPot_ * 1000) //9
);
}
function getCurrentPhraseInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256)
{
// setup local phID
uint256 _phID = phID_;
return
(
_phID, //0
phrase_[_phID].eth, //1
phrase_[_phID].guGiven, //2
phrase_[_phID].minEthRequired, //3
phrase_[_phID].guPoolAllocation //4
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID, phID
uint256 _rID = rID_;
uint256 _phID = phID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, // 0
plyrRnds_[_pID][_rID].keys, //1
plyr_[_pID].gu, //2
plyr_[_pID].laff, //3
(plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)).add(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth, //6 totalIn for the round
plyrPhas_[_pID][_phID].eth, //7 curr phrase referral eth
plyr_[_pID].referEth, // 8 total referral eth
plyr_[_pID].withdraw // 9 totalOut
);
}
function buyCore(uint256 _pID, uint256 _affID)
whenNotPaused
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// whitelist checking
if (_now < round_[rID_].strt + whitelistRange_) {
require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]);
}
// if round is active
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
endRound();
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID)
private
{
// if player is new to current round
if (plyrRnds_[_pID][_rID].keys == 0)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_; // update player's last round played
}
// early round eth limiter (0-100 eth)
uint256 _availableLimit;
uint256 _refund;
if (round_[_rID].eth < ethLimiterRange1_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter1_)
{
_availableLimit = (ethLimiter1_).sub(plyrRnds_[_pID][_rID].eth);
_refund = _eth.sub(_availableLimit);
plyr_[_pID].refund = plyr_[_pID].refund.add(_refund);
_eth = _availableLimit;
} else if (round_[_rID].eth < ethLimiterRange2_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter2_)
{
_availableLimit = (ethLimiter2_).sub(plyrRnds_[_pID][_rID].eth);
_refund = _eth.sub(_availableLimit);
plyr_[_pID].refund = plyr_[_pID].refund.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1e9)
{
// mint the new keys
uint256 _keys = keysRec(round_[_rID].eth, _eth);
// if they bought at least 1 whole key
if (_keys >= 1e18)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
emit KeyPurchase(plyr_[round_[_rID].plyr].addr, _eth, _keys);
}
// manage airdrops
if (_eth >= 1e17)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 1e19)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
} else if (_eth >= 1e18 && _eth < 1e19) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
} else if (_eth >= 1e17 && _eth < 1e18) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
}
// reset air drop tracker
airDropTracker_ = 0;
}
}
leekStealGo();
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].playCtr++;
playOrders_[round_[_rID].playCtr] = pID_; // for recording the 500 winners
// update round
round_[_rID].allkeys = _keys.add(round_[_rID].allkeys);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
// distribute eth
distributeExternal(_rID, _pID, _eth, _affID);
distributeInternal(_rID, _pID, _eth, _keys);
// manage gu-referral
updateGuReferral(_pID, _affID, _eth);
checkDoubledProfit(_pID, _rID);
checkDoubledProfit(_affID, _rID);
}
}
function checkDoubledProfit(uint256 _pID, uint256 _rID)
private
{
// if pID has no keys, skip this
uint256 _keys = plyrRnds_[_pID][_rID].keys;
if (_keys > 0) {
// zero out keys if the accumulated profit doubled
uint256 _balance = (plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd));
if (_balance.add(plyrRnds_[_pID][_rID].genWithdraw) >= (plyrRnds_[_pID][_rID].eth))
{
updateGenVault(_pID, plyr_[_pID].lrnd);
round_[_rID].keys = round_[_rID].keys.sub(_keys);
plyrRnds_[_pID][_rID].keys = plyrRnds_[_pID][_rID].keys.sub(_keys);
}
}
}
function keysRec(uint256 _curEth, uint256 _newEth)
private
returns (uint256)
{
uint256 _startEth;
uint256 _incrRate;
uint256 _initPrice;
if (_curEth < priceStage1_) {
_startEth = 0;
_initPrice = 33333; //3e-5;
_incrRate = 50000000; //2e-8;
}
else if (_curEth < priceStage2_) {
_startEth = priceStage1_;
_initPrice = 25000; // 4e-5;
_incrRate = 50000000; //2e-8;
}
else if (_curEth < priceStage3_) {
_startEth = priceStage2_;
_initPrice = 20000; //5e-5;
_incrRate = 50000000; //2e-8;;
}
else if (_curEth < priceStage4_) {
_startEth = priceStage3_;
_initPrice = 12500; //8e-5;
_incrRate = 26666666; //3.75e-8;
}
else if (_curEth < priceStage5_) {
_startEth = priceStage4_;
_initPrice = 5000; //2e-4;
_incrRate = 17777777; //5.625e-8;
}
else if (_curEth < priceStage6_) {
_startEth = priceStage5_;
_initPrice = 2500; // 4e-4;
_incrRate = 10666666; //9.375e-8;
}
else if (_curEth < priceStage7_) {
_startEth = priceStage6_;
_initPrice = 1000; //0.001;
_incrRate = 5688282; //1.758e-7;
}
else if (_curEth < priceStage8_) {
_startEth = priceStage7_;
_initPrice = 250; //0.004;
_incrRate = 2709292; //3.691e-7;
}
else if (_curEth < priceStage9_) {
_startEth = priceStage8_;
_initPrice = 62; //0.016;
_incrRate = 1161035; //8.613e-7;
}
else if (_curEth < priceStage10_) {
_startEth = priceStage9_;
_initPrice = 14; //0.071;
_incrRate = 451467; //2.215e-6;
}
else if (_curEth < priceStage11_) {
_startEth = priceStage10_;
_initPrice = 2; //0.354;
_incrRate = 144487; //6.921e-6;
}
else if (_curEth < priceStage12_) {
_startEth = priceStage11_;
_initPrice = 0; //2.126;
_incrRate = 40128; //2.492e-5;
}
else {
_startEth = priceStage12_;
_initPrice = 0;
_incrRate = 40128; //2.492e-5;
}
return _newEth.mul(((_incrRate.mul(_initPrice)) / (_incrRate.add(_initPrice.mul((_curEth.sub(_startEth))/1e18)))));
}
function updateGuReferral(uint256 _pID, uint256 _affID, uint256 _eth) private {
uint256 _newPhID = updateGuPhrase();
// update phrase, and distribute remaining gu for the last phrase
if (phID_ < _newPhID) {
updateReferralMasks(phID_);
plyr_[1].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[1].gu); // give 20% gu to community first, at the beginning of the phrase start
plyr_[2].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[2].gu); // give 20% gu to community first, at the beginning of the phrase start
phrase_[_newPhID].guGiven = (phrase_[_newPhID].guPoolAllocation / 5).add(phrase_[_newPhID].guGiven);
allGuGiven_ = (phrase_[_newPhID].guPoolAllocation / 5).add(allGuGiven_);
phID_ = _newPhID; // update the phrase ID
}
// update referral eth on affiliate
if (_affID != 0 && _affID != _pID) {
plyrPhas_[_affID][_newPhID].eth = _eth.add(plyrPhas_[_affID][_newPhID].eth);
plyr_[_affID].referEth = _eth.add(plyr_[_affID].referEth);
phrase_[_newPhID].eth = _eth.add(phrase_[_newPhID].eth);
}
uint256 _remainGuReward = phrase_[_newPhID].guPoolAllocation.sub(phrase_[_newPhID].guGiven);
// if 1) one has referral amt larger than requirement, 2) has remaining => then distribute certain amt of Gu, i.e. update gu instead of adding gu
if (plyrPhas_[_affID][_newPhID].eth >= phrase_[_newPhID].minEthRequired && _remainGuReward >= 1e18) {
// check if need to reward more gu
uint256 _totalReward = plyrPhas_[_affID][_newPhID].eth / phrase_[_newPhID].minEthRequired;
_totalReward = _totalReward.mul(1e18);
uint256 _rewarded = plyrPhas_[_affID][_newPhID].guRewarded;
uint256 _toReward = _totalReward.sub(_rewarded);
if (_remainGuReward < _toReward) _toReward = _remainGuReward;
// give out gu reward
if (_toReward > 0) {
plyr_[_affID].gu = _toReward.add(plyr_[_affID].gu); // give gu to player
plyrPhas_[_affID][_newPhID].guRewarded = _toReward.add(plyrPhas_[_affID][_newPhID].guRewarded);
phrase_[_newPhID].guGiven = 1e18.add(phrase_[_newPhID].guGiven);
allGuGiven_ = 1e18.add(allGuGiven_);
}
}
}
function updateReferralMasks(uint256 _phID) private {
uint256 _remainGu = phrase_[phID_].guPoolAllocation.sub(phrase_[phID_].guGiven);
if (_remainGu > 0 && phrase_[_phID].eth > 0) {
// remaining gu per total ethIn in the phrase
uint256 _gpe = (_remainGu.mul(1e18)) / phrase_[_phID].eth;
phrase_[_phID].mask = _gpe.add(phrase_[_phID].mask); // should only added once
}
}
function transferGu(address _to, uint256 _guAmt)
public
whenNotPaused
returns (bool)
{
uint256 _pIDFrom = pIDxAddr_[msg.sender];
// check if the sender (_pIDFrom) is not found or admin player
require(plyr_[_pIDFrom].addr == msg.sender);
uint256 _pIDTo = pIDxAddr_[_to];
plyr_[_pIDFrom].gu = plyr_[_pIDFrom].gu.sub(_guAmt);
plyr_[_pIDTo].gu = plyr_[_pIDTo].gu.add(_guAmt);
return true;
}
function updateGuPhrase()
private
returns (uint256) // return phraseNum
{
if (now <= contractStartDate_ + guPhrase1_) {
phrase_[1].minEthRequired = 5e18;
phrase_[1].guPoolAllocation = 100e18;
return 1;
}
if (now <= contractStartDate_ + guPhrase2_) {
phrase_[2].minEthRequired = 4e18;
phrase_[2].guPoolAllocation = 200e18;
return 2;
}
if (now <= contractStartDate_ + guPhrase3_) {
phrase_[3].minEthRequired = 3e18;
phrase_[3].guPoolAllocation = 400e18;
return 3;
}
if (now <= contractStartDate_ + guPhrase4_) {
phrase_[4].minEthRequired = 2e18;
phrase_[4].guPoolAllocation = 800e18;
return 4;
}
if (now <= contractStartDate_ + guPhrase5_) {
phrase_[5].minEthRequired = 1e18;
phrase_[5].guPoolAllocation = 1600e18;
return 5;
}
if (now <= contractStartDate_ + guPhrase6_) {
phrase_[6].minEthRequired = 1e18;
phrase_[6].guPoolAllocation = 3200e18;
return 6;
}
if (now <= contractStartDate_ + guPhrase7_) {
phrase_[7].minEthRequired = 1e18;
phrase_[7].guPoolAllocation = 6400e18;
return 7;
}
if (now <= contractStartDate_ + guPhrase8_) {
phrase_[8].minEthRequired = 1e18;
phrase_[8].guPoolAllocation = 12800e18;
return 8;
}
if (now <= contractStartDate_ + guPhrase9_) {
phrase_[9].minEthRequired = 1e18;
phrase_[9].guPoolAllocation = 25600e18;
return 9;
}
if (now <= contractStartDate_ + guPhrase10_) {
phrase_[10].minEthRequired = 1e18;
phrase_[10].guPoolAllocation = 51200e18;
return 10;
}
phrase_[11].minEthRequired = 0;
phrase_[11].guPoolAllocation = 0;
return 11;
}
function leekStealGo() private {
// get a number for today dayNum
uint leekStealToday_ = (now.sub(round_[rID_].strt) / 1 days);
if (dayStealTime_[leekStealToday_] == 0) // if there hasn't a winner today, proceed
{
leekStealTracker_++;
if (randomNum(leekStealTracker_) == true)
{
dayStealTime_[leekStealToday_] = now;
leekStealOn_ = true;
}
}
}
function stealTheLeek() public {
if (leekStealOn_)
{
if (now.sub(dayStealTime_[leekStealToday_]) > 300) // if time passed 5min, turn off and exit
{
leekStealOn_ = false;
} else {
// if yes then assign the 1eth, if the pool has 1eth
if (leekStealPot_ > 1e18) {
uint256 _pID = pIDxAddr_[msg.sender]; // fetch player ID
plyr_[_pID].win = plyr_[_pID].win.add(1e18);
leekStealPot_ = leekStealPot_.sub(1e18);
}
}
}
}
function calcUnMaskedKeyEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
if ( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)) > (plyrRnds_[_pID][_rIDlast].maskKey) )
return( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)).sub(plyrRnds_[_pID][_rIDlast].maskKey) );
else
return 0;
}
function calcUnMaskedGuEarnings(uint256 _pID)
private
view
returns(uint256)
{
if ( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)) > (plyr_[_pID].maskGu) )
return( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)).sub(plyr_[_pID].maskGu) );
else
return 0;
}
function endRound()
private
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player id
uint256 _winPID = round_[_rID].plyr;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// jcg share, and amount reserved for next pot
uint256 _win = (_pot.mul(40)) / 100;
uint256 _res = (_pot.mul(10)) / 100;
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// pay the rest of the 500 winners
pay500Winners(_pot);
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_);
round_[_rID].pot = _res;
}
function pay500Winners(uint256 _pot) private {
uint256 _rID = rID_;
uint256 _plyCtr = round_[_rID].playCtr;
// pay the 2-10th
uint256 _win2 = _pot.mul(25).div(100).div(9);
for (uint256 i = _plyCtr.sub(9); i <= _plyCtr.sub(1); i++) {
plyr_[playOrders_[i]].win = _win2.add(plyr_[playOrders_[i]].win);
}
// pay the 11-100th
uint256 _win3 = _pot.mul(15).div(100).div(90);
for (uint256 j = _plyCtr.sub(99); j <= _plyCtr.sub(10); j++) {
plyr_[playOrders_[j]].win = _win3.add(plyr_[playOrders_[j]].win);
}
// pay the 101-500th
uint256 _win4 = _pot.mul(10).div(100).div(400);
for (uint256 k = _plyCtr.sub(499); k <= _plyCtr.sub(100); k++) {
plyr_[playOrders_[k]].win = _win4.add(plyr_[playOrders_[k]].win);
}
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedKeyEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].maskKey = _earnings.add(plyrRnds_[_pID][_rIDlast].maskKey);
}
}
function updateGenGuVault(uint256 _pID)
private
{
uint256 _earnings = calcUnMaskedGuEarnings(_pID);
if (_earnings > 0)
{
// put in genGu vault
plyr_[_pID].genGu = _earnings.add(plyr_[_pID].genGu);
// zero out their earnings by updating mask
plyr_[_pID].maskGu = _earnings.add(plyr_[_pID].maskGu);
}
}
function updateReferralGu(uint256 _pID)
private
{
// get current phID
uint256 _phID = phID_;
// get last claimed phID till
uint256 _lastClaimedPhID = plyr_[_pID].lastClaimedPhID;
// calculate the gu Shares using these two input
uint256 _guShares;
for (uint i = (_lastClaimedPhID + 1); i < _phID; i++) {
_guShares = (((phrase_[i].mask).mul(plyrPhas_[_pID][i].eth))/1e18).add(_guShares);
// update record
plyr_[_pID].lastClaimedPhID = i;
phrase_[i].guGiven = _guShares.add(phrase_[i].guGiven);
plyrPhas_[_pID][i].guRewarded = _guShares.add(plyrPhas_[_pID][i].guRewarded);
}
// put gu in player
plyr_[_pID].gu = _guShares.add(plyr_[_pID].gu);
// zero out their earnings by updating mask
plyr_[_pID].maskGu = ((allMaskGu_.mul(_guShares)) / 1e18).add(plyr_[_pID].maskGu);
allGuGiven_ = _guShares.add(allGuGiven_);
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function randomNum(uint256 _tracker)
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < _tracker)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID)
private
{
// pay 2% out to community rewards
uint256 _com = _eth / 100;
address(WALLET_ETH_COM1).transfer(_com); // 1%
address(WALLET_ETH_COM2).transfer(_com); // 1%
// distribute 10% share to affiliate (8% + 2%)
uint256 _aff = _eth / 10;
// check: affiliate must not be self, and must have an ID
if (_affID != _pID && _affID != 0) {
plyr_[_affID].aff = (_aff.mul(8)/10).add(plyr_[_affID].aff); // distribute 8% to 1st aff
uint256 _affID2 = plyr_[_affID].laff; // get 2nd aff
if (_affID2 != _pID && _affID2 != 0) {
plyr_[_affID2].aff = (_aff.mul(2)/10).add(plyr_[_affID2].aff); // distribute 2% to 2nd aff
}
} else {
plyr_[1].aff = _aff.add(plyr_[_affID].aff);
}
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys)
private
{
// calculate gen share
uint256 _gen = (_eth.mul(40)) / 100; // 40%
// calculate jcg share
uint256 _jcg = (_eth.mul(20)) / 100; // 20%
// toss 3% into airdrop pot
uint256 _air = (_eth.mul(3)) / 100;
airDropPot_ = airDropPot_.add(_air);
// toss 5% into leeksteal pot
uint256 _steal = (_eth / 20);
leekStealPot_ = leekStealPot_.add(_steal);
// update eth balance (eth = eth - (2% com share + 3% airdrop + 5% leekSteal + 10% aff share))
_eth = _eth.sub(((_eth.mul(20)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen).sub(_jcg);
// distribute gen n jcg share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dustKey = updateKeyMasks(_rID, _pID, _gen, _keys);
uint256 _dustGu = updateGuMasks(_pID, _jcg);
// add eth to pot
round_[_rID].pot = _pot.add(_dustKey).add(_dustGu).add(round_[_rID].pot);
}
function updateKeyMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1e18)) / (round_[_rID].keys);
round_[_rID].maskKey = _ppt.add(round_[_rID].maskKey);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1e18);
plyrRnds_[_pID][_rID].maskKey = (((round_[_rID].maskKey.mul(_keys)) / (1e18)).sub(_pearn)).add(plyrRnds_[_pID][_rID].maskKey);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1e18)));
}
function updateGuMasks(uint256 _pID, uint256 _jcg)
private
returns(uint256)
{
if (allGuGiven_ > 0) {
// calc profit per gu & round mask based on this buy: (dust goes to pot)
uint256 _ppg = (_jcg.mul(1e18)) / allGuGiven_;
allMaskGu_ = _ppg.add(allMaskGu_);
// calculate player earning from their own buy
// & update player earnings mask
uint256 _pearn = (_ppg.mul(plyr_[_pID].gu)) / (1e18);
plyr_[_pID].maskGu = (((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)).sub(_pearn)).add(plyr_[_pID].maskGu);
// calculate & return dust
return (_jcg.sub((_ppg.mul(allGuGiven_)) / (1e18)));
} else {
return _jcg;
}
}
function withdrawEarnings(uint256 _pID, bool isWithdraw)
whenNotPaused
private
returns(uint256)
{
updateGenGuVault(_pID);
updateReferralGu(_pID);
updateGenVault(_pID, plyr_[_pID].lrnd);
if (isWithdraw) plyrRnds_[_pID][plyr_[_pID].lrnd].genWithdraw = plyr_[_pID].gen.add(plyrRnds_[_pID][plyr_[_pID].lrnd].genWithdraw); // for doubled profit
// from all vaults
uint256 _earnings = plyr_[_pID].gen.add(plyr_[_pID].win).add(plyr_[_pID].genGu).add(plyr_[_pID].aff).add(plyr_[_pID].refund);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].genGu = 0;
plyr_[_pID].aff = 0;
plyr_[_pID].refund = 0;
if (isWithdraw) plyr_[_pID].withdraw = _earnings.add(plyr_[_pID].withdraw);
}
return(_earnings);
}
bool public activated_ = false;
function activate()
onlyOwner
public
{
// can only be ran once
require(activated_ == false);
// activate the contract
activated_ = true;
contractStartDate_ = now;
// lets start first round
rID_ = 1;
round_[1].strt = now;
round_[1].end = now + rndInit_;
}
}
library Datasets {
struct Player {
address addr; // player address
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 genGu; // general gu vault
uint256 aff; // affiliate vault
uint256 refund; // refund vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
uint256 withdraw; // sum of withdraw
uint256 maskGu; // player mask gu: for sharing eth-profit by holding gu
uint256 gu;
uint256 referEth; // total referral
uint256 lastClaimedPhID; // at which phID player has claimed the remaining gu
}
struct PlayerRounds {
uint256 eth; // eth player has added to round
uint256 keys; // keys
uint256 maskKey; // player mask key: for sharing eth-profit by holding keys
uint256 genWithdraw; // eth withdraw from gen vault
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 allkeys; // all keys
uint256 keys; // active keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 maskKey; // global mask on key shares: for sharing eth-profit by holding keys
uint256 playCtr; // play counter for playOrders
}
struct PlayerPhrases {
uint256 eth; // amount of eth in of the referral
uint256 guRewarded; // if have taken the gu through referral
}
struct Phrase {
uint256 eth; // amount of total eth in of the referral
uint256 guGiven; // amount of gu distributed
uint256 mask; // a rate of remainGu per ethIn shares: for sharing gu-reward by referral eth
uint256 minEthRequired; // min refer.eth to get 1 gu
uint256 guPoolAllocation; // total number of gu
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | setup local rID grab time fetch player ID setup temp var for player eth check to see if round has ended and no one has run round end yet end the round (distributes pot) get their earnings gib moni in any other situation get their earnings gib moni | function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
round_[_rID].ended = true;
endRound();
_eth = withdrawEarnings(_pID, true);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eth = withdrawEarnings(_pID, true);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
}
}
| 131,208 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./lib/FixedPoint.sol";
import { IPool } from "./balancer/IPool.sol";
import { UniSwapV2PriceOracle } from "./UniSwapV2PriceOracle.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {
IUniswapV2Pair as Pair
} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import {
IUniswapV2Router02 as UniV2Router
} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import { PriceLibrary as Prices } from "./lib/PriceLibrary.sol";
/**
* @title UnboundTokenSeller
* @author d1ll0n
* @dev Contract for swapping undesired tokens to desired tokens for
* an index pool.
*
* This contract is deployed as a proxy for each index pool.
*
* When tokens are unbound from a pool, they are transferred to this
* contract and sold on UniSwap or to anyone who calls the contract
* in exchange for any token which is currently bound to its index pool
* and which has a desired weight about zero.
*
* It uses a short-term uniswap price oracle to price swaps and has a
* configurable premium rate which is used to decrease the expected
* output from a swap and to reward callers for triggering a sale.
*
* The contract does not track the tokens it has received in order to
* reduce gas spent by the pool contract. Tokens must be tracked via
* events, meaning this is not well suited for trades with other smart
* contracts.
*/
contract UnboundTokenSeller {
using FixedPoint for FixedPoint.uq112x112;
using FixedPoint for FixedPoint.uq144x112;
using SafeMath for uint256;
using SafeMath for uint144;
using SafeERC20 for IERC20;
using Prices for Prices.TwoWayAveragePrice;
/* --- Constants --- */
UniV2Router internal immutable _uniswapRouter;
address internal immutable _controller;
UniSwapV2PriceOracle internal immutable _oracle;
/* --- Events --- */
event PremiumPercentSet(uint8 premium);
event NewTokensToSell(
address indexed token,
uint256 amountReceived
);
/**
* @param tokenSold Token sent to caller
* @param tokenBought Token received from caller and sent to pool
* @param soldAmount Amount of `tokenSold` paid to caller
* @param boughtAmount Amount of `tokenBought` sent to pool
*/
event SwappedTokens(
address indexed tokenSold,
address indexed tokenBought,
uint256 soldAmount,
uint256 boughtAmount
);
/* --- Storage --- */
// Pool the contract is selling tokens for.
IPool internal _pool;
// Premium on the amount paid in swaps.
// Half goes to the caller, half is used to increase payments.
uint8 internal _premiumPercent;
// Reentrance lock
bool internal _mutex;
/* --- Modifiers --- */
modifier _control_ {
require(msg.sender == _controller, "ERR_NOT_CONTROLLER");
_;
}
modifier _lock_ {
require(!_mutex, "ERR_REENTRY");
_mutex = true;
_;
_mutex = false;
}
modifier _desired_(address token) {
IPool.Record memory record = _pool.getTokenRecord(token);
require(record.desiredDenorm > 0, "ERR_UNDESIRED_TOKEN");
_;
}
/* --- Constructor --- */
constructor(
UniV2Router uniswapRouter,
UniSwapV2PriceOracle oracle,
address controller
) public {
_uniswapRouter = uniswapRouter;
_oracle = oracle;
_controller = controller;
}
/**
* @dev Initialize the proxy contract with the acceptable premium rate
* and the address of the pool it is for.
*/
function initialize(IPool pool, uint8 premiumPercent)
external
_control_
{
require(address(_pool) == address(0), "ERR_INITIALIZED");
require(address(pool) != address(0), "ERR_NULL_ADDRESS");
require(
premiumPercent > 0 && premiumPercent < 20,
"ERR_PREMIUM"
);
_premiumPercent = premiumPercent;
_pool = pool;
}
/* --- Controls --- */
/**
* @dev Receive `amount` of `token` from the pool.
*/
function handleUnbindToken(address token, uint256 amount)
external
{
require(msg.sender == address(_pool), "ERR_ONLY_POOL");
emit NewTokensToSell(token, amount);
}
/**
* @dev Set the premium rate as a percent.
*/
function setPremiumPercent(uint8 premiumPercent) external _control_ {
require(
premiumPercent > 0 && premiumPercent < 20,
"ERR_PREMIUM"
);
_premiumPercent = premiumPercent;
emit PremiumPercentSet(premiumPercent);
}
/* --- Token Swaps --- */
/**
* @dev Execute a trade with UniSwap to sell some tokens held by the contract
* for some tokens desired by the pool and pays the caller the difference between
* the maximum input value and the actual paid amount.
*
* @param tokenIn Token to sell to UniSwap
* @param tokenOut Token to receive from UniSwapx
* @param amountOut Exact amount of `tokenOut` to receive from UniSwap
* @param path Swap path to execute
*/
function executeSwapTokensForExactTokens(
address tokenIn,
address tokenOut,
uint256 amountOut,
address[] calldata path
)
external
_lock_
returns (uint256 premiumPaidToCaller)
{
// calcOutGivenIn uses tokenIn as the token the pool is receiving and
// tokenOut as the token the pool is paying, whereas this function is
// the reverse.
uint256 maxAmountIn = calcOutGivenIn(tokenOut, tokenIn, amountOut);
// Approve UniSwap to transfer the input tokens
IERC20(tokenIn).safeApprove(address(_uniswapRouter), maxAmountIn);
// Verify that the first token in the path is the input token and that
// the last is the output token.
require(
path[0] == tokenIn && path[path.length - 1] == tokenOut,
"ERR_PATH_TOKENS"
);
// Execute the swap.
uint256[] memory amounts = _uniswapRouter.swapTokensForExactTokens(
amountOut,
maxAmountIn,
path,
address(_pool),
block.timestamp + 1
);
// Get the actual amount paid
uint256 amountIn = amounts[0];
// If we did not swap the full amount, remove the UniSwap allowance.
if (amountIn != maxAmountIn) {
IERC20(tokenIn).safeApprove(address(_uniswapRouter), 0);
premiumPaidToCaller = maxAmountIn - amountIn;
// Transfer the difference between what the contract was willing to pay and
// what it actually paid to the caller.
IERC20(tokenIn).safeTransfer(msg.sender, premiumPaidToCaller);
}
// Update the pool's balance of the token.
_pool.gulp(tokenOut);
emit SwappedTokens(
tokenIn,
tokenOut,
amountIn,
amountOut
);
}
/**
* @dev Executes a trade with UniSwap to sell some tokens held by the contract
* for some tokens desired by the pool and pays the caller any tokens received
* above the minimum acceptable output.
*
* @param tokenIn Token to sell to UniSwap
* @param tokenOut Token to receive from UniSwap
* @param amountIn Exact amount of `tokenIn` to give UniSwap
* @param path Swap path to execute
*/
function executeSwapExactTokensForTokens(
address tokenIn,
address tokenOut,
uint256 amountIn,
address[] calldata path
)
external
_lock_
returns (uint256 premiumPaidToCaller)
{
// calcInGivenOut uses tokenIn as the token the pool is receiving and
// tokenOut as the token the pool is paying, whereas this function is
// the reverse.
uint256 minAmountOut = calcInGivenOut(tokenOut, tokenIn, amountIn);
// Approve UniSwap to transfer the input tokens
IERC20(tokenIn).safeApprove(address(_uniswapRouter), amountIn);
// Verify that the first token in the path is the input token and that
// the last is the output token.
require(
path[0] == tokenIn && path[path.length - 1] == tokenOut,
"ERR_PATH_TOKENS"
);
// Execute the swap.
uint256[] memory amounts = _uniswapRouter.swapExactTokensForTokens(
amountIn,
minAmountOut,
path,
address(this),
block.timestamp + 1
);
// Get the actual amount paid
uint256 amountOut = amounts[amounts.length - 1];
if (amountOut != minAmountOut) {
// Transfer any tokens received beyond the minimum acceptable payment
// to the caller as a reward.
premiumPaidToCaller = amountOut - minAmountOut;
IERC20(tokenOut).safeTransfer(msg.sender, premiumPaidToCaller);
}
// Transfer the received tokens to the pool
IERC20(tokenOut).safeTransfer(address(_pool), minAmountOut);
// Update the pool's balance of the token.
_pool.gulp(tokenOut);
emit SwappedTokens(
tokenIn,
tokenOut,
amountIn,
amountOut
);
}
/**
* @dev Swap exactly `amountIn` of `tokenIn` for at least `minAmountOut`
* of `tokenOut`.
*
* @param tokenIn Token to sell to pool
* @param tokenOut Token to buy from pool
* @param amountIn Amount of `tokenIn` to sell to pool
* @param minAmountOut Minimum amount of `tokenOut` to buy from pool
*/
function swapExactTokensForTokens(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minAmountOut
)
external
_lock_
returns (uint256 amountOut)
{
amountOut = calcOutGivenIn(tokenIn, tokenOut, amountIn);
// Verify the amount is above the provided minimum.
require(amountOut >= minAmountOut, "ERR_MIN_AMOUNT_OUT");
// Transfer the input tokens to the pool
IERC20(tokenIn).safeTransferFrom(msg.sender, address(_pool), amountIn);
_pool.gulp(tokenIn);
// Transfer the output tokens to the caller
IERC20(tokenOut).safeTransfer(msg.sender, amountOut);
emit SwappedTokens(
tokenOut,
tokenIn,
amountOut,
amountIn
);
}
/**
* @dev Swap up to `maxAmountIn` of `tokenIn` for exactly `amountOut`
* of `tokenOut`.
*
* @param tokenIn Token to sell to pool
* @param tokenOut Token to buy from pool
* @param amountOut Amount of `tokenOut` to buy from pool
* @param maxAmountIn Maximum amount of `tokenIn` to sell to pool
*/
function swapTokensForExactTokens(
address tokenIn,
address tokenOut,
uint256 amountOut,
uint256 maxAmountIn
)
external
_lock_
returns (uint256 amountIn)
{
amountIn = calcInGivenOut(tokenIn, tokenOut, amountOut);
require(amountIn <= maxAmountIn, "ERR_MAX_AMOUNT_IN");
// Transfer the input tokens to the pool
IERC20(tokenIn).safeTransferFrom(msg.sender, address(_pool), amountIn);
_pool.gulp(tokenIn);
// Transfer the output tokens to the caller
IERC20(tokenOut).safeTransfer(msg.sender, amountOut);
emit SwappedTokens(
tokenOut,
tokenIn,
amountOut,
amountIn
);
}
/* --- Swap Queries --- */
function getPremiumPercent() external view returns (uint8) {
return _premiumPercent;
}
/**
* @dev Calculate the amount of `tokenIn` the pool will accept for
* `amountOut` of `tokenOut`.
*/
function calcInGivenOut(
address tokenIn,
address tokenOut,
uint256 amountOut
)
public
view
_desired_(tokenIn)
returns (uint256 amountIn)
{
require(
IERC20(tokenOut).balanceOf(address(this)) >= amountOut,
"ERR_INSUFFICIENT_BALANCE"
);
(
Prices.TwoWayAveragePrice memory avgPriceIn,
Prices.TwoWayAveragePrice memory avgPriceOut
) = _getAveragePrices(tokenIn, tokenOut);
// Compute the average weth value for `amountOut` of `tokenOut`
uint144 avgOutValue = avgPriceOut.computeAverageEthForTokens(amountOut);
// Compute the minimum weth value the contract must receive for `avgOutValue`
uint256 minInValue = _minimumReceivedValue(avgOutValue);
// Compute the average amount of `tokenIn` worth `minInValue` weth
amountIn = avgPriceIn.computeAverageTokensForEth(minInValue);
}
/**
* @dev Calculate the amount of `tokenOut` the pool will give for
* `amountIn` of `tokenIn`.
*/
function calcOutGivenIn(
address tokenIn,
address tokenOut,
uint256 amountIn
)
public
view
_desired_(tokenIn)
returns (uint256 amountOut)
{
(
Prices.TwoWayAveragePrice memory avgPriceIn,
Prices.TwoWayAveragePrice memory avgPriceOut
) = _getAveragePrices(tokenIn, tokenOut);
// Compute the average weth value for `amountIn` of `tokenIn`
uint144 avgInValue = avgPriceIn.computeAverageEthForTokens(amountIn);
// Compute the maximum weth value the contract will give for `avgInValue`
uint256 maxOutValue = _maximumPaidValue(avgInValue);
// Compute the average amount of `tokenOut` worth `maxOutValue` weth
amountOut = avgPriceOut.computeAverageTokensForEth(maxOutValue);
require(
IERC20(tokenOut).balanceOf(address(this)) >= amountOut,
"ERR_INSUFFICIENT_BALANCE"
);
}
/* --- Internal Functions --- */
function _calcAmountToCallerAndPool(
address tokenPaid,
uint256 amountPaid,
address tokenReceived,
uint256 amountReceived
)
internal
view
returns (uint256 premiumAmount, uint256 poolAmount)
{
// Get the average weth value of the amounts received and paid
(uint144 avgReceivedValue, uint144 avgPaidValue) = _getAverageValues(
tokenReceived,
amountReceived,
tokenPaid,
amountPaid
);
// Compute the minimum acceptable received value
uint256 minReceivedValue = _minimumReceivedValue(avgPaidValue);
require(avgReceivedValue >= minReceivedValue, "ERR_MIN_RECEIVED");
// Compute the premium based on the value received above the minimum
premiumAmount = (amountReceived * (avgReceivedValue - minReceivedValue)) / avgReceivedValue;
poolAmount = amountPaid - premiumAmount;
}
function _getAverageValues(
address token1,
uint256 amount1,
address token2,
uint256 amount2
)
internal
view
returns (uint144 avgValue1, uint144 avgValue2)
{
address[] memory tokens = new address[](2);
tokens[0] = token1;
tokens[1] = token2;
uint256[] memory amounts = new uint256[](2);
amounts[0] = amount1;
amounts[1] = amount2;
uint144[] memory avgValues = _oracle.computeAverageAmountsOut(tokens, amounts);
avgValue1 = avgValues[0];
avgValue2 = avgValues[1];
}
function _getAveragePrices(address token1, address token2)
internal
view
returns (
Prices.TwoWayAveragePrice memory avgPrice1,
Prices.TwoWayAveragePrice memory avgPrice2
)
{
address[] memory tokens = new address[](2);
tokens[0] = token1;
tokens[1] = token2;
Prices.TwoWayAveragePrice[] memory prices = _oracle.computeTwoWayAveragePrices(tokens);
avgPrice1 = prices[0];
avgPrice2 = prices[1];
}
function _maximumPaidValue(uint256 valueReceived)
internal
view
returns (uint256 maxPaidValue)
{
maxPaidValue = (100 * valueReceived) / (100 - _premiumPercent);
}
function _minimumReceivedValue(uint256 valuePaid)
internal
view
returns (uint256 minValueReceived)
{
minValueReceived = (valuePaid * (100 - _premiumPercent)) / 100;
}
} | Calculate the amount of `tokenOut` the pool will give for `amountIn` of `tokenIn`./ Compute the average weth value for `amountIn` of `tokenIn` Compute the maximum weth value the contract will give for `avgInValue` Compute the average amount of `tokenOut` worth `maxOutValue` weth | function calcOutGivenIn(
address tokenIn,
address tokenOut,
uint256 amountIn
)
public
view
_desired_(tokenIn)
returns (uint256 amountOut)
{
(
Prices.TwoWayAveragePrice memory avgPriceIn,
Prices.TwoWayAveragePrice memory avgPriceOut
) = _getAveragePrices(tokenIn, tokenOut);
uint144 avgInValue = avgPriceIn.computeAverageEthForTokens(amountIn);
uint256 maxOutValue = _maximumPaidValue(avgInValue);
amountOut = avgPriceOut.computeAverageTokensForEth(maxOutValue);
require(
IERC20(tokenOut).balanceOf(address(this)) >= amountOut,
"ERR_INSUFFICIENT_BALANCE"
);
}
| 1,823,294 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.