file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// Sources flattened with hardhat v2.6.5 https://hardhat.org // File contracts/EIP20Interface.sol pragma solidity 0.5.17; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); } // File contracts/SafeMath.sol pragma solidity 0.5.17; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction underflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/Staking/ReentrancyGuard.sol pragma solidity 0.5.17; /** * @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]. */ 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() public { _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; } } // File contracts/Staking/TranquilStakingProxyStorage.sol pragma solidity 0.5.17; contract TranquilStakingProxyStorage { // Current contract admin address address public admin; // Requested new admin for the contract address public pendingAdmin; // Current contract implementation address address public implementation; // Requested new contract implementation address address public pendingImplementation; } // File contracts/Staking/TranquilStakingProxy.sol pragma solidity 0.5.17; contract TranquilStakingProxy is ReentrancyGuard, TranquilStakingProxyStorage { constructor() public { admin = msg.sender; } /** * Request a new admin to be set for the contract. * * @param newAdmin New admin address */ function setPendingAdmin(address newAdmin) public adminOnly { pendingAdmin = newAdmin; } /** * Accept admin transfer from the current admin to the new. */ function acceptPendingAdmin() public { require( msg.sender == pendingAdmin && pendingAdmin != address(0), 'Caller must be the pending admin' ); admin = pendingAdmin; pendingAdmin = address(0); } /** * Request a new implementation to be set for the contract. * * @param newImplementation New contract implementation contract address */ function setPendingImplementation(address newImplementation) public adminOnly { pendingImplementation = newImplementation; } /** * Accept pending implementation change */ function acceptPendingImplementation() public { require( msg.sender == pendingImplementation && pendingImplementation != address(0), 'Only the pending implementation contract can call this' ); implementation = pendingImplementation; pendingImplementation = address(0); } function() external payable { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /******************************************************** * * * MODIFIERS * * * ********************************************************/ modifier adminOnly() { require(msg.sender == admin, 'admin only'); _; } } // File contracts/Staking/TranquilStakingStorage.sol pragma solidity 0.5.17; contract TranquilStakingStorage is TranquilStakingProxyStorage { uint256 constant nofStakingRewards = 2; uint256 constant REWARD_TRANQ = 0; uint256 constant REWARD_ONE = 1; // Address of the staked token. address public stakedTokenAddress; // Addresses of the ERC20 reward tokens mapping(uint256 => address) public rewardTokenAddresses; // Reward accrual speeds per reward token as tokens per second mapping(uint256 => uint256) public rewardSpeeds; // Unclaimed staking rewards per user and token mapping(address => mapping(uint256 => uint256)) public accruedReward; // Supplied tokens at stake per user mapping(address => uint256) public supplyAmount; // Sum of all supplied tokens at stake uint256 public totalSupplies; mapping(uint256 => uint256) public rewardIndex; mapping(address => mapping(uint256 => uint256)) public supplierRewardIndex; uint256 public accrualBlockTimestamp; } // File contracts/Staking/TranquilLockedStakingStorage.sol pragma solidity 0.5.17; contract TranquilLockedStakingStorage is TranquilStakingStorage { uint256 constant REWARD_TRANQ = 0; uint256 constant REWARD_ONE = 1; uint256 constant REWARD_WBTC = 2; uint256 constant REWARD_ETH = 3; uint256 constant REWARD_USDC = 4; uint256 constant REWARD_USDT = 5; // Total number of staking reward tokens; uint256 public rewardTokenCount; // Address of the staked token. address public stakedTokenAddress; // Addresses of the ERC20 reward tokens mapping(uint256 => address) public rewardTokenAddresses; // Reward accrual speeds per reward token as tokens per second mapping(uint256 => uint256) public rewardSpeeds; // Unclaimed staking rewards per user and token mapping(address => mapping(uint256 => uint256)) public accruedReward; // Supplied tokens at stake per user mapping(address => uint256) public supplyAmount; // Sum of all supplied tokens at stake uint256 public totalSupplies; mapping(uint256 => uint256) public rewardIndex; mapping(address => mapping(uint256 => uint256)) public supplierRewardIndex; uint256 public accrualBlockTimestamp; // Time that a deposit is locked for before it can be withdrawn. uint256 public lockDuration; struct LockedSupply { uint256 stakedTokenAmount; uint256 unlockTime; } // Locked deposits of the staked token per user mapping(address => LockedSupply[]) public lockedSupplies; // The amount of unlocked tokens per user. mapping(address => uint256) public unlockedSupplyAmount; // The percentage of staked tokens to burn if withdrawn early. Expressed as a mantissa. uint256 public earlyRedeemPenaltyMantissa; // Amount of tokens that were slashed through early redemption. uint256 public slashedTokenAmount; } // File contracts/Staking/TranquilLockedStaking.sol pragma solidity 0.5.17; pragma experimental ABIEncoderV2; contract TranquilLockedStaking is ReentrancyGuard, TranquilLockedStakingStorage { using SafeMath for uint256; constructor() public { admin = msg.sender; } /******************************************************** * * * PUBLIC FUNCTIONS * * * ********************************************************/ /** * Deposit and lock tokens into the staking contract. * * @param amount The amount of tokens to deposit */ function deposit(uint256 amount) external nonReentrant { require( stakedTokenAddress != address(0), 'Staked token address can not be zero' ); EIP20Interface stakedToken = EIP20Interface(stakedTokenAddress); uint256 contractBalance = stakedToken.balanceOf(address(this)); stakedToken.transferFrom(msg.sender, address(this), amount); uint256 depositedAmount = stakedToken.balanceOf(address(this)).sub( contractBalance ); require(depositedAmount > 0, 'Zero deposit'); distributeReward(msg.sender); totalSupplies = totalSupplies.add(depositedAmount); supplyAmount[msg.sender] = supplyAmount[msg.sender].add( depositedAmount ); LockedSupply memory lockedSupply; lockedSupply.stakedTokenAmount = depositedAmount; lockedSupply.unlockTime = block.timestamp + lockDuration; lockedSupplies[msg.sender].push(lockedSupply); updateExpiredLocks(msg.sender); } /** * Redeem tokens from the contract. * * @param amount Redeem amount */ function redeem(uint256 amount) external nonReentrant { require( stakedTokenAddress != address(0), 'Staked token address can not be zero' ); require(amount <= supplyAmount[msg.sender], 'Too large withdrawal'); require( amount <= getUnlockedBalance(msg.sender), 'Insufficient unlocked balance' ); distributeReward(msg.sender); updateExpiredLocks(msg.sender); supplyAmount[msg.sender] = supplyAmount[msg.sender].sub(amount); unlockedSupplyAmount[msg.sender] = unlockedSupplyAmount[msg.sender].sub( amount ); totalSupplies = totalSupplies.sub(amount); EIP20Interface stakedToken = EIP20Interface(stakedTokenAddress); stakedToken.transfer(msg.sender, amount); } /** * Redeems locked tokens before the unlock time with a penalty. * * @param amount Redeem amount */ function redeemEarly(uint256 amount) external nonReentrant { require( stakedTokenAddress != address(0), 'Staked token address can not be zero' ); require(amount <= supplyAmount[msg.sender], 'Too large withdrawal'); require( amount <= getLockedBalance(msg.sender), 'Insufficient locked balance' ); distributeReward(msg.sender); LockedSupply[] storage lockedSupplies = lockedSupplies[msg.sender]; uint256 totalSupplyAmount = 0; for (uint256 i = 0; i < lockedSupplies.length; ++i) { if (totalSupplyAmount == amount) { break; } uint256 supplyAmount = 0; if ( lockedSupplies[i].stakedTokenAmount <= amount - totalSupplyAmount ) { supplyAmount = lockedSupplies[i].stakedTokenAmount; delete lockedSupplies[i]; } else { supplyAmount = amount - totalSupplyAmount; lockedSupplies[i].stakedTokenAmount -= supplyAmount; } totalSupplyAmount += supplyAmount; } updateExpiredLocks(msg.sender); supplyAmount[msg.sender] = supplyAmount[msg.sender].sub(amount); totalSupplies = totalSupplies.sub(amount); uint256 penaltyAmount = SafeMath.div( SafeMath.mul(amount, earlyRedeemPenaltyMantissa), 1e18 ); uint256 amountAfterPenalty = amount - penaltyAmount; slashedTokenAmount += penaltyAmount; EIP20Interface stakedToken = EIP20Interface(stakedTokenAddress); stakedToken.transfer(msg.sender, amountAfterPenalty); } /** * Claim pending rewards from the staking contract by transferring them * to the requester. */ function claimRewards() external nonReentrant { distributeReward(msg.sender); updateExpiredLocks(msg.sender); for (uint256 i = 0; i < rewardTokenCount; i += 1) { uint256 amount = accruedReward[msg.sender][i]; if (i == REWARD_ONE) { claimOne(msg.sender, amount); } else { claimErc20(i, msg.sender, amount); } } } /** * Get the current amount of available rewards for claiming. * * @param user The user whose rewards to query * @param rewardToken Reward token whose rewards to query * @return Balance of claimable reward tokens */ function getClaimableRewards(address user, uint256 rewardToken) external view returns (uint256) { require(rewardToken <= rewardTokenCount, 'Invalid reward token'); uint256 decimalConversion = 36 + 18 - getRewardTokenDecimals(rewardToken); uint256 rewardIndexDelta = rewardIndex[rewardToken].sub( supplierRewardIndex[user][rewardToken] ); uint256 claimableReward = rewardIndexDelta .mul(supplyAmount[user]) .div(10**decimalConversion) .add(accruedReward[user][rewardToken]); return claimableReward; } /** * Gets the individual locked deposit data. * * @param user The user whose balance to query */ function getLockedSupplies(address user) external view returns (LockedSupply[] memory) { return lockedSupplies[user]; } /** * Gets the amount of unlocked redeemable tokens to unstake. * * @param user The user whose balance to query */ function getUnlockedBalance(address user) public view returns (uint256) { LockedSupply[] memory lockedSupplies = lockedSupplies[user]; uint256 unlockedAmount = unlockedSupplyAmount[user]; for (uint256 i = 0; i < lockedSupplies.length; ++i) { LockedSupply memory lockedSupply = lockedSupplies[i]; if (block.timestamp >= lockedSupply.unlockTime) { unlockedAmount += lockedSupply.stakedTokenAmount; } } return unlockedAmount; } /** * Gets the amount of locked tokens. * * @param user The user whose balance to query */ function getLockedBalance(address user) public view returns (uint256) { return supplyAmount[user] - getUnlockedBalance(user); } /** * Fallback function to accept ONE deposits. */ function() external payable {} /******************************************************** * * * ADMIN-ONLY FUNCTIONS * * * ********************************************************/ /** * Set the total number of reward tokens. * * @param newRewardTokenCount New total number of reward tokens */ function setRewardTokenCount(uint256 newRewardTokenCount) external adminOnly { rewardTokenCount = newRewardTokenCount; } /** * Set the lock duration for staked tokens. * * @param newLockDuration New lock duration */ function setLockDuration(uint256 newLockDuration) external adminOnly { lockDuration = newLockDuration; } /** * Set reward distribution speed. * * @param rewardToken Reward token speed to change * @param speed New reward speed */ function setRewardSpeed(uint256 rewardToken, uint256 speed) external adminOnly { if (accrualBlockTimestamp != 0) { accrueReward(); } rewardSpeeds[rewardToken] = speed; } /** * Set ERC20 reward token contract address. * * @param rewardToken Reward token address to set * @param rewardTokenAddress New contract address */ function setRewardTokenAddress( uint256 rewardToken, address rewardTokenAddress ) external adminOnly { require(rewardToken != REWARD_ONE, 'Cannot set ONE address'); rewardTokenAddresses[rewardToken] = rewardTokenAddress; } /** * Set the staked token contract address. * * @param newStakedTokenAddress New staked token contract address */ function setStakedTokenAddress(address newStakedTokenAddress) external adminOnly { stakedTokenAddress = newStakedTokenAddress; } /** * Set the early redeem penalty. * * @param newEarlyRedeemPenaltyMantissa New early redeem penalty */ function setEarlyRedeemPenalty(uint256 newEarlyRedeemPenaltyMantissa) external adminOnly { earlyRedeemPenaltyMantissa = newEarlyRedeemPenaltyMantissa; } /** * Accept this contract as the implementation for a proxy. * * @param proxy TranquilStakingProxy */ function becomeImplementation(TranquilStakingProxy proxy) external { require( msg.sender == proxy.admin(), 'Only proxy admin can change the implementation' ); proxy.acceptPendingImplementation(); } /** * Withdraw slashed tokens. * * @param amount The amount to withdraw */ function withdrawSlashedTokens(uint256 amount) external adminOnly { require( amount <= slashedTokenAmount, 'Withdraw amount exceeds slashed token amount' ); EIP20Interface token = EIP20Interface(stakedTokenAddress); slashedTokenAmount = slashedTokenAmount.sub(amount); token.transfer(admin, amount); } /** * Emergency withdraw of the given token. * * @param tokenAddress The address of the token to withdraw * @param amount The amount to withdraw */ function emergencyWithdraw(address tokenAddress, uint256 amount) external adminOnly { EIP20Interface token = EIP20Interface(tokenAddress); token.transfer(admin, amount); } /** * Emergency withdraw of the native ONE token. * * @param amount The amount to withdraw */ function emergencyWithdrawNative(uint256 amount) external adminOnly { msg.sender.transfer(amount); } /******************************************************** * * * INTERNAL FUNCTIONS * * * ********************************************************/ /** * Updates and removes expired locked deposits. */ function updateExpiredLocks(address user) internal { uint256 oldLockedBalance = getLockedBalance(user); LockedSupply[] storage lockedSupplies = lockedSupplies[user]; uint256 firstLockedIndex = 0; for (uint256 i = 0; i < lockedSupplies.length; ++i) { if (block.timestamp < lockedSupplies[i].unlockTime) { break; } unlockedSupplyAmount[user] += lockedSupplies[i].stakedTokenAmount; delete lockedSupplies[i]; firstLockedIndex++; } // Shift array to new length if elements were deleted. uint256 newArrayLength = lockedSupplies.length - firstLockedIndex; for (uint256 i = 0; i < newArrayLength; ++i) { lockedSupplies[i] = lockedSupplies[firstLockedIndex + i]; } lockedSupplies.length = newArrayLength; require( oldLockedBalance == getLockedBalance(user), 'Locked balance should be same before and after update.' ); } /** * Update reward accrual state. * * @dev accrueReward() must be called every time the token balances * or reward speeds change */ function accrueReward() internal { uint256 blockTimestampDelta = block.timestamp.sub( accrualBlockTimestamp ); accrualBlockTimestamp = block.timestamp; if (blockTimestampDelta == 0 || totalSupplies == 0) { return; } for (uint256 i = 0; i < rewardTokenCount; i += 1) { uint256 rewardSpeed = rewardSpeeds[i]; if (rewardSpeed == 0) { continue; } uint256 accrued = rewardSpeeds[i].mul(blockTimestampDelta); uint256 accruedPerStakedToken = accrued.mul(1e36).div( totalSupplies ); rewardIndex[i] = rewardIndex[i].add(accruedPerStakedToken); } } /** * Calculate accrued rewards for a single account based on the reward indexes. * * @param recipient Account for which to calculate accrued rewards */ function distributeReward(address recipient) internal { accrueReward(); for (uint256 i = 0; i < rewardTokenCount; i += 1) { uint256 decimalConversion = 36 + 18 - getRewardTokenDecimals(i); uint256 rewardIndexDelta = rewardIndex[i].sub( supplierRewardIndex[recipient][i] ); uint256 accruedAmount = rewardIndexDelta .mul(supplyAmount[recipient]) .div(10**decimalConversion); accruedReward[recipient][i] = accruedReward[recipient][i].add( accruedAmount ); supplierRewardIndex[recipient][i] = rewardIndex[i]; } } /** * Transfer ONE rewards from the contract to the reward recipient. * * @param recipient Address, whose ONE rewards are claimed * @param amount The amount of claimed ONE */ function claimOne(address payable recipient, uint256 amount) internal { require( accruedReward[recipient][REWARD_ONE] <= amount, 'Not enough accrued rewards' ); accruedReward[recipient][REWARD_ONE] = accruedReward[recipient][ REWARD_ONE ].sub(amount); recipient.transfer(amount); } /** * Transfer ERC20 rewards from the contract to the reward recipient. * * @param rewardToken ERC20 reward token which is claimed * @param recipient Address, whose rewards are claimed * @param amount The amount of claimed reward */ function claimErc20( uint256 rewardToken, address recipient, uint256 amount ) internal { require(rewardToken != REWARD_ONE, 'Cannot use claimErc20 for ONE'); require( accruedReward[recipient][rewardToken] <= amount, 'Not enough accrued rewards' ); require( rewardTokenAddresses[rewardToken] != address(0), 'reward token address can not be zero' ); EIP20Interface token = EIP20Interface( rewardTokenAddresses[rewardToken] ); accruedReward[recipient][rewardToken] = accruedReward[recipient][ rewardToken ].sub(amount); token.transfer(recipient, amount); } /** * Returns the decimals for a reward token. * * @param rewardToken Reward token to query */ function getRewardTokenDecimals(uint256 rewardToken) internal view returns (uint256) { require( rewardToken == REWARD_ONE || rewardTokenAddresses[rewardToken] != address(0), 'Reward token address must be set' ); if (rewardToken == REWARD_ONE) { return 18; } return EIP20Interface(rewardTokenAddresses[rewardToken]).decimals(); } /******************************************************** * * * MODIFIERS * * * ********************************************************/ modifier adminOnly() { require(msg.sender == admin, 'admin only'); _; } }
Set the early redeem penalty. newEarlyRedeemPenaltyMantissa New early redeem penalty/
function setEarlyRedeemPenalty(uint256 newEarlyRedeemPenaltyMantissa) external adminOnly { earlyRedeemPenaltyMantissa = newEarlyRedeemPenaltyMantissa; }
2,487,516
pragma solidity ^0.5.13; import './interfaces/SyscoinClaimManagerI.sol'; import './interfaces/SyscoinSuperblocksI.sol'; import './SyscoinErrorCodes.sol'; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./SyscoinParser/SyscoinMessageLibrary.sol"; // @dev - Manages a battle session between superblock submitter and challenger contract SyscoinBattleManager is Initializable, SyscoinErrorCodes, SyscoinMessageLibrary { // For verifying Syscoin difficulty uint constant TARGET_TIMESPAN = 21600; uint constant TARGET_TIMESPAN_MIN = 17280; // TARGET_TIMESPAN * (8/10); uint constant TARGET_TIMESPAN_MAX = 27000; // TARGET_TIMESPAN * (10/8); uint constant TARGET_TIMESPAN_ADJUSTMENT = 360; // 6 hour uint constant POW_LIMIT = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; struct BattleSession { address submitter; address challenger; uint lastActionTimestamp; // Last action timestamp bytes32 prevSubmitBlockhash; bytes32[] merkleRoots; // interim merkle roots to recreate final root hash on last set of headers } // AuxPoW block fields struct AuxPoW { uint blockHash; uint txHash; uint coinbaseMerkleRoot; // Merkle root of auxiliary block hash tree; stored in coinbase tx field uint[] chainMerkleProof; // proves that a given Syscoin block hash belongs to a tree with the above root uint syscoinHashIndex; // index of Syscoin block hash within block hash tree uint coinbaseMerkleRootCode; // encodes whether or not the root was found properly uint parentMerkleRoot; // Merkle root of transaction tree from parent Bitcoin block header uint[] parentMerkleProof; // proves that coinbase tx belongs to a tree with the above root uint coinbaseTxIndex; // index of coinbase tx within Bitcoin tx tree uint parentNonce; uint pos; } // Syscoin block header stored as a struct, mostly for readability purposes. // BlockHeader structs can be obtained by parsing a block header's first 80 bytes // with parseHeaderBytes. struct BlockHeader { uint32 bits; bytes32 prevBlock; uint32 timestamp; bytes32 blockHash; } mapping (bytes32 => BattleSession) sessions; uint public superblockDuration; // Superblock duration (in blocks) uint public superblockTimeout; // Timeout action (in seconds) // network that the stored blocks belong to Network private net; // Syscoin claim manager SyscoinClaimManagerI trustedSyscoinClaimManager; // Superblocks contract SyscoinSuperblocksI trustedSuperblocks; event NewBattle(bytes32 superblockHash,address submitter, address challenger); event ChallengerConvicted(bytes32 superblockHash, uint err, address challenger); event SubmitterConvicted(bytes32 superblockHash, uint err, address submitter); event RespondBlockHeaders(bytes32 superblockHash, uint merkleHashCount, address submitter); modifier onlyFrom(address sender) { require(msg.sender == sender); _; } modifier onlyChallenger(bytes32 superblockHash) { require(msg.sender == sessions[superblockHash].challenger); _; } // @dev – Configures the contract managing superblocks battles // @param _network Network type to use for block difficulty validation // @param _superblocks Contract that manages superblocks // @param _superblockDuration Superblock duration (in blocks) // @param _superblockTimeout Time to wait for challenges (in seconds) function init( Network _network, SyscoinSuperblocksI _superblocks, uint _superblockDuration, uint _superblockTimeout ) external initializer { net = _network; trustedSuperblocks = _superblocks; superblockDuration = _superblockDuration; superblockTimeout = _superblockTimeout; } function setSyscoinClaimManager(SyscoinClaimManagerI _syscoinClaimManager) external { require(address(trustedSyscoinClaimManager) == address(0) && address(_syscoinClaimManager) != address(0)); trustedSyscoinClaimManager = _syscoinClaimManager; } // @dev - Start a battle session function beginBattleSession(bytes32 superblockHash, address submitter, address challenger) external onlyFrom(address(trustedSyscoinClaimManager)) { BattleSession storage session = sessions[superblockHash]; require(session.submitter == address(0)); session.submitter = submitter; session.challenger = challenger; session.merkleRoots.length = 0; session.lastActionTimestamp = block.timestamp; emit NewBattle(superblockHash, submitter, challenger); } // 0x00 version // 0x04 prev block hash // 0x24 merkle root // 0x44 timestamp // 0x48 bits // 0x4c nonce // @dev - extract previous block field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading hash from // @return - hash of block's parent in big endian format function getHashPrevBlock(bytes memory _blockHeader, uint pos) private pure returns (uint) { uint hashPrevBlock; uint index = 0x04+pos; assembly { hashPrevBlock := mload(add(add(_blockHeader, 32), index)) } return flip32Bytes(hashPrevBlock); } // @dev - extract timestamp field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's timestamp in big-endian format function getTimestamp(bytes memory _blockHeader, uint pos) private pure returns (uint32 time) { return bytesToUint32Flipped(_blockHeader, 0x44+pos); } // @dev - extract bits field from a raw Syscoin block header // // @param _blockHeader - Syscoin block header bytes // @param pos - where to start reading bits from // @return - block's difficulty in bits format, also big-endian function getBits(bytes memory _blockHeader, uint pos) private pure returns (uint32 bits) { return bytesToUint32Flipped(_blockHeader, 0x48+pos); } // @dev - converts raw bytes representation of a Syscoin block header to struct representation // // @param _rawBytes - first 80 bytes of a block header // @return - exact same header information in BlockHeader struct form function parseHeaderBytes(bytes memory _rawBytes, uint pos) private view returns (BlockHeader memory bh) { bh.bits = getBits(_rawBytes, pos); bh.blockHash = bytes32(dblShaFlipMem(_rawBytes, pos, 80)); bh.timestamp = getTimestamp(_rawBytes, pos); bh.prevBlock = bytes32(getHashPrevBlock(_rawBytes, pos)); } function parseAuxPoW(bytes memory rawBytes, uint pos) private view returns (AuxPoW memory auxpow) { bytes memory coinbaseScript; uint slicePos; // we need to traverse the bytes with a pointer because some fields are of variable length pos += 80; // skip non-AuxPoW header (slicePos, coinbaseScript) = getSlicePos(rawBytes, pos); auxpow.txHash = dblShaFlipMem(rawBytes, pos, slicePos - pos); pos = slicePos; // parent block hash, skip and manually hash below pos += 32; (auxpow.parentMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.coinbaseTxIndex = getBytesLE(rawBytes, pos, 32); pos += 4; (auxpow.chainMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.syscoinHashIndex = getBytesLE(rawBytes, pos, 32); pos += 4; // calculate block hash instead of reading it above, as some are LE and some are BE, we cannot know endianness and have to calculate from parent block header auxpow.blockHash = dblShaFlipMem(rawBytes, pos, 80); pos += 36; // skip parent version and prev block auxpow.parentMerkleRoot = sliceBytes32Int(rawBytes, pos); pos += 40; // skip root that was just read, parent block timestamp and bits auxpow.parentNonce = getBytesLE(rawBytes, pos, 32); auxpow.pos = pos+4; uint coinbaseMerkleRootPosition; (auxpow.coinbaseMerkleRoot, coinbaseMerkleRootPosition, auxpow.coinbaseMerkleRootCode) = findCoinbaseMerkleRoot(coinbaseScript); } function sha256mem(bytes memory _rawBytes, uint offset, uint len) public view returns (bytes32 result) { assembly { // Call sha256 precompiled contract (located in address 0x02) to copy data. // Assign to ptr the next available memory position (stored in memory position 0x40). let ptr := mload(0x40) if iszero(staticcall(gas, 0x02, add(add(_rawBytes, 0x20), offset), len, ptr, 0x20)) { revert(0, 0) } result := mload(ptr) } } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlipMem(bytes memory _rawBytes, uint offset, uint len) public view returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256mem(_rawBytes, offset, len))))); } function skipOutputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_outputs; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); require(n_outputs < 10); for (uint i = 0; i < n_outputs; i++) { pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } return pos; } // get final position of inputs, outputs and lock time // this is a helper function to slice a byte array and hash the inputs, outputs and lock time function getSlicePos(bytes memory txBytes, uint pos) private view returns (uint slicePos, bytes memory coinbaseScript) { (slicePos, coinbaseScript) = skipInputsCoinbase(txBytes, pos + 4); slicePos = skipOutputs(txBytes, slicePos); slicePos += 4; // skip lock time } // scan a Merkle branch. // return array of values and the end position of the sibling hashes. // takes a 'stop' argument which sets the maximum number of // siblings to scan through. stop=0 => scan all. function scanMerkleBranch(bytes memory txBytes, uint pos, uint stop) private pure returns (uint[] memory, uint) { uint n_siblings; uint halt; (n_siblings, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_siblings) { halt = n_siblings; } else { halt = stop; } uint[] memory sibling_values = new uint[](halt); for (uint i = 0; i < halt; i++) { sibling_values[i] = flip32Bytes(sliceBytes32Int(txBytes, pos)); pos += 32; } return (sibling_values, pos); } // Slice 32 contiguous bytes from bytes `data`, starting at `start` function sliceBytes32Int(bytes memory data, uint start) private pure returns (uint slice) { assembly { slice := mload(add(data, add(0x20, start))) } } function skipInputsCoinbase(bytes memory txBytes, uint pos) private view returns (uint, bytes memory) { uint n_inputs; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); // if dummy 0x00 is present this is a witness transaction if(n_inputs == 0x00){ (n_inputs, pos) = parseVarInt(txBytes, pos); // flag require(n_inputs != 0x00); // after dummy/flag the real var int comes for txins (n_inputs, pos) = parseVarInt(txBytes, pos); } require(n_inputs == 1); pos += 36; // skip outpoint (script_len, pos) = parseVarInt(txBytes, pos); bytes memory coinbaseScript; coinbaseScript = sliceArray(txBytes, pos, pos+script_len); pos += script_len + 4; // skip sig_script, seq return (pos, coinbaseScript); } // @dev - looks for {0xfa, 0xbe, 'm', 'm'} byte sequence // returns the following 32 bytes if it appears once and only once, // 0 otherwise // also returns the position where the bytes first appear function findCoinbaseMerkleRoot(bytes memory rawBytes) private pure returns (uint, uint, uint) { uint position; uint found = 0; uint target = 0xfabe6d6d00000000000000000000000000000000000000000000000000000000; uint mask = 0xffffffff00000000000000000000000000000000000000000000000000000000; assembly { let len := mload(rawBytes) let data := add(rawBytes, 0x20) let end := add(data, len) for { } lt(data, end) { } { // while(i < end) if eq(and(mload(data), mask), target) { if eq(found, 0x0) { position := add(sub(len, sub(end, data)), 4) } found := add(found, 1) } data := add(data, 0x1) } } if (found >= 2) { return (0, position - 4, ERR_FOUND_TWICE); } else if (found == 1) { return (sliceBytes32Int(rawBytes, position), position - 4, 1); } else { // no merge mining header return (0, position - 4, ERR_NO_MERGE_HEADER); } } // @dev - calculates the Merkle root of a tree containing Bitcoin transactions // in order to prove that `ap`'s coinbase tx is in that Bitcoin block. // // @param _ap - AuxPoW information // @return - Merkle root of Bitcoin block that the Syscoin block // with this info was mined in if AuxPoW Merkle proof is correct, // garbage otherwise function computeParentMerkle(AuxPoW memory _ap) private pure returns (uint) { return flip32Bytes(computeMerkle(_ap.txHash, _ap.coinbaseTxIndex, _ap.parentMerkleProof)); } // @dev - calculates the Merkle root of a tree containing auxiliary block hashes // in order to prove that the Syscoin block identified by _blockHash // was merge-mined in a Bitcoin block. // // @param _blockHash - SHA-256 hash of a certain Syscoin block // @param _ap - AuxPoW information corresponding to said block // @return - Merkle root of auxiliary chain tree // if AuxPoW Merkle proof is correct, garbage otherwise function computeChainMerkle(uint _blockHash, AuxPoW memory _ap) private pure returns (uint) { return computeMerkle(_blockHash, _ap.syscoinHashIndex, _ap.chainMerkleProof); } // @dev - checks if a merge-mined block's Merkle proofs are correct, // i.e. Syscoin block hash is in coinbase Merkle tree // and coinbase transaction is in parent Merkle tree. // // @param _blockHash - SHA-256 hash of the block whose Merkle proofs are being checked // @param _ap - AuxPoW struct corresponding to the block // @return 1 if block was merge-mined and coinbase index, chain Merkle root and Merkle proofs are correct, // respective error code otherwise function checkAuxPoW(uint _blockHash, AuxPoW memory _ap) private pure returns (uint) { if (_ap.coinbaseTxIndex != 0) { return ERR_COINBASE_INDEX; } if (_ap.coinbaseMerkleRootCode != 1) { return _ap.coinbaseMerkleRootCode; } if (computeChainMerkle(_blockHash, _ap) != _ap.coinbaseMerkleRoot) { return ERR_CHAIN_MERKLE; } if (computeParentMerkle(_ap) != _ap.parentMerkleRoot) { return ERR_PARENT_MERKLE; } return 1; } // @dev - Bitcoin-way of computing the target from the 'bits' field of a block header // based on http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html//ref3 // // @param _bits - difficulty in bits format // @return - difficulty in target format function targetFromBits(uint32 _bits) public pure returns (uint) { uint exp = _bits / 0x1000000; // 2**24 uint mant = _bits & 0xffffff; return mant * 256**(exp - 3); } // @param _actualTimespan - time elapsed from previous block creation til current block creation; // i.e., how much time it took to mine the current block // @param _bits - previous block header difficulty (in bits) // @return - expected difficulty for the next block function calculateDifficulty(uint _actualTimespan, uint32 _bits) private pure returns (uint32 result) { uint actualTimespan = _actualTimespan; // Limit adjustment step if (actualTimespan < TARGET_TIMESPAN_MIN) { actualTimespan = TARGET_TIMESPAN_MIN; } else if (actualTimespan > TARGET_TIMESPAN_MAX) { actualTimespan = TARGET_TIMESPAN_MAX; } // Retarget uint bnNew = targetFromBits(_bits); bnNew = bnNew * actualTimespan; bnNew = bnNew / TARGET_TIMESPAN; if (bnNew > POW_LIMIT) { bnNew = POW_LIMIT; } return toCompactBits(bnNew); } // @dev - shift information to the right by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the right, i.e. divided by 2**`_shift` function shiftRight(uint _val, uint _shift) private pure returns (uint) { return _val / uint(2)**_shift; } // @dev - shift information to the left by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2**`_shift` function shiftLeft(uint _val, uint _shift) private pure returns (uint) { return _val * uint(2)**_shift; } // @dev - get the number of bits required to represent a given integer value without losing information // // @param _val - unsigned integer value // @return - given value's bit length function bitLen(uint _val) private pure returns (uint length) { uint int_type = _val; while (int_type > 0) { int_type = shiftRight(int_type, 1); length += 1; } } // @dev - Convert uint256 to compact encoding // based on https://github.com/petertodd/python-bitcoinlib/blob/2a5dda45b557515fb12a0a18e5dd48d2f5cd13c2/bitcoin/core/serialize.py // Analogous to arith_uint256::GetCompact from C++ implementation // // @param _val - difficulty in target format // @return - difficulty in bits format function toCompactBits(uint _val) private pure returns (uint32) { uint nbytes = uint (shiftRight((bitLen(_val) + 7), 3)); uint32 compact = 0; if (nbytes <= 3) { compact = uint32 (shiftLeft((_val & 0xFFFFFF), 8 * (3 - nbytes))); } else { compact = uint32 (shiftRight(_val, 8 * (nbytes - 3))); compact = uint32 (compact & 0xFFFFFF); } // If the sign bit (0x00800000) is set, divide the mantissa by 256 and // increase the exponent to get an encoding without it set. if ((compact & 0x00800000) > 0) { compact = uint32(shiftRight(compact, 8)); nbytes += 1; } return compact | uint32(shiftLeft(nbytes, 24)); } // @dev - Evaluate the merkle root // // Given an array of hashes it calculates the // root of the merkle tree. // // @return root of merkle tree function makeMerkle(bytes32[] memory hashes) public pure returns (bytes32) { uint length = hashes.length; if (length == 1) return hashes[0]; require(length > 0, "Must provide hashes"); uint i; for (i = 0; i < length; i++) { hashes[i] = bytes32(flip32Bytes(uint(hashes[i]))); } uint j; uint k; while (length > 1) { k = 0; for (i = 0; i < length; i += 2) { j = (i + 1 < length) ? i + 1 : length - 1; hashes[k] = sha256(abi.encodePacked(sha256(abi.encodePacked(hashes[i], hashes[j])))); k += 1; } length = k; } return bytes32(flip32Bytes(uint(hashes[0]))); } // @dev - Verify block headers sent by challenger function doRespondBlockHeaders( BattleSession storage session, SyscoinSuperblocksI.SuperblockInfo memory superblockInfo, bytes32 merkleRoot, BlockHeader memory lastHeader ) private returns (uint) { if (session.merkleRoots.length == 3 || net == Network.REGTEST) { bytes32[] memory merkleRoots = new bytes32[](net != Network.REGTEST ? 4 : 1); uint i; for (i = 0; i < session.merkleRoots.length; i++) { merkleRoots[i] = session.merkleRoots[i]; } merkleRoots[i] = merkleRoot; if (superblockInfo.blocksMerkleRoot != makeMerkle(merkleRoots)) { return ERR_SUPERBLOCK_INVALID_MERKLE; } // if you have the last set of headers we can enfoce checks against the end // ensure the last block's timestamp matches the superblock's proposed timestamp if (superblockInfo.timestamp != lastHeader.timestamp) { return ERR_SUPERBLOCK_INVALID_TIMESTAMP; } // ensure last headers hash matches the last hash of the superblock if (lastHeader.blockHash != superblockInfo.lastHash) { return ERR_SUPERBLOCK_HASH_SUPERBLOCK; } } else { session.merkleRoots.push(merkleRoot); } return ERR_SUPERBLOCK_OK; } function respondBlockHeaders ( bytes32 superblockHash, bytes memory blockHeaders, uint numHeaders ) public { BattleSession storage session = sessions[superblockHash]; address submitter = session.submitter; require(msg.sender == submitter); uint merkleRootsLen = session.merkleRoots.length; if (net != Network.REGTEST) { if ((merkleRootsLen <= 2 && numHeaders != 16) || (merkleRootsLen == 3 && numHeaders != 12)) { revert(); } } SyscoinSuperblocksI.SuperblockInfo memory superblockInfo; (superblockInfo.blocksMerkleRoot, superblockInfo.timestamp,superblockInfo.mtpTimestamp,superblockInfo.lastHash,superblockInfo.lastBits,superblockInfo.parentId,,,superblockInfo.height) = trustedSuperblocks.getSuperblock(superblockHash); uint pos = 0; bytes32[] memory blockHashes = new bytes32[](numHeaders); BlockHeader[] memory parsedBlockHeaders = new BlockHeader[](numHeaders); uint err = ERR_SUPERBLOCK_OK; for (uint i = 0; i < parsedBlockHeaders.length; i++){ parsedBlockHeaders[i] = parseHeaderBytes(blockHeaders, pos); uint target = targetFromBits(parsedBlockHeaders[i].bits); if (isMergeMined(blockHeaders, pos)) { AuxPoW memory ap = parseAuxPoW(blockHeaders, pos); if (ap.blockHash > target) { err = ERR_PROOF_OF_WORK_AUXPOW; break; } uint auxPoWCode = checkAuxPoW(uint(parsedBlockHeaders[i].blockHash), ap); if (auxPoWCode != 1) { err = auxPoWCode; break; } pos = ap.pos; } else { if (uint(parsedBlockHeaders[i].blockHash) > target) { err = ERR_PROOF_OF_WORK; break; } pos = pos+80; } blockHashes[i] = parsedBlockHeaders[i].blockHash; } if (err != ERR_SUPERBLOCK_OK) { convictSubmitter(superblockHash, submitter, session.challenger, err); return; } err = doRespondBlockHeaders( session, superblockInfo, makeMerkle(blockHashes), parsedBlockHeaders[parsedBlockHeaders.length-1] ); if (err != ERR_SUPERBLOCK_OK) { convictSubmitter(superblockHash, submitter, session.challenger, err); } else { session.lastActionTimestamp = block.timestamp; err = validateHeaders(session, superblockInfo, parsedBlockHeaders); if (err != ERR_SUPERBLOCK_OK) { convictSubmitter(superblockHash, submitter, session.challenger, err); return; } // only convict challenger at the end if all headers have been provided if(numHeaders == 12 || net == Network.REGTEST){ convictChallenger(superblockHash, submitter, session.challenger, err); return; } emit RespondBlockHeaders(superblockHash, merkleRootsLen + 1, submitter); } } uint32 constant VERSION_AUXPOW = (1 << 8); // @dev - checks version to determine if a block has merge mining information function isMergeMined(bytes memory _rawBytes, uint pos) private pure returns (bool) { return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0; } // @dev - Validate prev bits, prev hash of block header function checkBlocks(BattleSession storage session, BlockHeader[] memory blockHeadersParsed, uint32 prevBits) private view returns (uint) { for(uint i = blockHeadersParsed.length-1;i>0;i--){ BlockHeader memory thisHeader = blockHeadersParsed[i]; BlockHeader memory prevHeader = blockHeadersParsed[i-1]; // except for the last header except all the bits to match // last chunk has 12 headers which is the only time we care to skip the last header if (blockHeadersParsed.length != 12 || i < (blockHeadersParsed.length-1)){ if (prevBits != thisHeader.bits) return ERR_SUPERBLOCK_BITS_PREVBLOCK; } if(prevHeader.blockHash != thisHeader.prevBlock) return ERR_SUPERBLOCK_HASH_PREVBLOCK; } if (prevBits != blockHeadersParsed[0].bits) { return ERR_SUPERBLOCK_BITS_PREVBLOCK; } // enforce linking against previous submitted batch of blocks if (session.merkleRoots.length >= 2) { if (session.prevSubmitBlockhash != blockHeadersParsed[0].prevBlock) return ERR_SUPERBLOCK_HASH_INTERIM_PREVBLOCK; } return ERR_SUPERBLOCK_OK; } function sort_array(uint[11] memory arr) private pure { for(uint i = 0; i < 11; i++) { for(uint j = i+1; j < 11 ;j++) { if(arr[i] > arr[j]) { uint temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } // @dev - Gets the median timestamp of the last 11 blocks function getMedianTimestamp(BlockHeader[] memory blockHeadersParsed) private pure returns (uint){ uint[11] memory timestamps; // timestamps 0->10 = blockHeadersParsed 1->11 for(uint i=0;i<11;i++){ timestamps[i] = blockHeadersParsed[i+1].timestamp; } sort_array(timestamps); return timestamps[5]; } // @dev - Validate superblock accumulated work + other block header fields function validateHeaders(BattleSession storage session, SyscoinSuperblocksI.SuperblockInfo memory superblockInfo, BlockHeader[] memory blockHeadersParsed) private returns (uint) { SyscoinSuperblocksI.SuperblockInfo memory prevSuperblockInfo; BlockHeader memory lastHeader = blockHeadersParsed[blockHeadersParsed.length-1]; (,,prevSuperblockInfo.mtpTimestamp,prevSuperblockInfo.lastHash,prevSuperblockInfo.lastBits,,,,) = trustedSuperblocks.getSuperblock(superblockInfo.parentId); // for blocks 0 -> 16 we can check the first header if(session.merkleRoots.length <= 1){ // ensure first headers prev block matches the last hash of the prev superblock if(blockHeadersParsed[0].prevBlock != prevSuperblockInfo.lastHash) return ERR_SUPERBLOCK_HASH_PREVSUPERBLOCK; } // make sure all bits are the same and timestamps are within range as well as headers are all linked uint err = checkBlocks(session, blockHeadersParsed, prevSuperblockInfo.lastBits); if(err != ERR_SUPERBLOCK_OK) return err; // for every batch of blocks up to the last one (at superblockDuration blocks we have all the headers so we can complete the game) if(blockHeadersParsed.length != 12){ // set the last block header details in the session for subsequent batch of blocks to validate it connects to this header session.prevSubmitBlockhash = lastHeader.blockHash; } // once all the headers are received we can check merkle and enforce difficulty else{ uint mtpTimestamp = getMedianTimestamp(blockHeadersParsed); // make sure calculated MTP is same as superblock MTP if(mtpTimestamp != superblockInfo.mtpTimestamp) return ERR_SUPERBLOCK_MISMATCH_TIMESTAMP_MTP; // ensure MTP of this SB is > than last SB MTP if(mtpTimestamp <= prevSuperblockInfo.mtpTimestamp) return ERR_SUPERBLOCK_TOOSMALL_TIMESTAMP_MTP; // make sure every 6th superblock adjusts difficulty // calculate the new work from prevBits minus one as if its an adjustment we need to account for new bits, if not then just add one more prevBits work if (net != Network.REGTEST) { if (((superblockInfo.height-1) % 6) == 0) { BlockHeader memory prevToLastHeader = blockHeadersParsed[blockHeadersParsed.length-2]; // ie: superblockHeight = 7 meaning blocks 661->720, we need to check timestamp from block 719 - to block 360 // get 6 superblocks previous for second timestamp (for example block 360 has the timetamp 6 superblocks ago on second adjustment) superblockInfo.timestamp = trustedSuperblocks.getSuperblockTimestamp(trustedSuperblocks.getSuperblockAt(superblockInfo.height - 6)); uint32 newBits = calculateDifficulty(prevToLastHeader.timestamp - superblockInfo.timestamp, prevSuperblockInfo.lastBits); // ensure bits of superblock match derived bits from calculateDifficulty if (superblockInfo.lastBits != newBits) { return ERR_SUPERBLOCK_BITS_SUPERBLOCK; } } else { if (superblockInfo.lastBits != prevSuperblockInfo.lastBits) { return ERR_SUPERBLOCK_BITS_LASTBLOCK; } } // make sure superblock bits match that of the last block if (superblockInfo.lastBits != lastHeader.bits) return ERR_SUPERBLOCK_BITS_LASTBLOCK; } } return ERR_SUPERBLOCK_OK; } // @dev - Trigger conviction if response is not received in time function timeout(bytes32 superblockHash) external returns (uint) { BattleSession storage session = sessions[superblockHash]; require(session.submitter != address(0)); if (block.timestamp > session.lastActionTimestamp + superblockTimeout) { convictSubmitter(superblockHash, session.submitter, session.challenger, ERR_SUPERBLOCK_TIMEOUT); trustedSyscoinClaimManager.checkClaimFinished(superblockHash); return ERR_SUPERBLOCK_TIMEOUT; } return ERR_SUPERBLOCK_NO_TIMEOUT; } // @dev - To be called when a challenger is convicted function convictChallenger(bytes32 superblockHash, address submitter, address challenger, uint err) private { trustedSyscoinClaimManager.sessionDecided(superblockHash, submitter, challenger); emit ChallengerConvicted(superblockHash, err, challenger); disable(superblockHash); } // @dev - To be called when a submitter is convicted function convictSubmitter(bytes32 superblockHash, address submitter, address challenger, uint err) private { trustedSyscoinClaimManager.sessionDecided(superblockHash, challenger, submitter); emit SubmitterConvicted(superblockHash, err, submitter); disable(superblockHash); } // @dev - Disable session // It should be called only when either the submitter or the challenger were convicted. function disable(bytes32 superblockHash) private { delete sessions[superblockHash]; } // @dev - Check if a session's submitter did not respond before timeout function getSubmitterHitTimeout(bytes32 superblockHash) external view returns (bool) { BattleSession storage session = sessions[superblockHash]; return (block.timestamp > session.lastActionTimestamp + superblockTimeout); } function getNumMerkleHashesBySession(bytes32 superblockHash) external view returns (uint) { BattleSession memory session = sessions[superblockHash]; if (session.submitter == address(0)) return 0; return sessions[superblockHash].merkleRoots.length; } function sessionExists(bytes32 superblockHash) external view returns (bool) { return sessions[superblockHash].submitter != address(0); } }
- looks for {0xfa, 0xbe, 'm', 'm'} byte sequence returns the following 32 bytes if it appears once and only once, 0 otherwise also returns the position where the bytes first appear
function findCoinbaseMerkleRoot(bytes memory rawBytes) private pure returns (uint, uint, uint) { uint position; uint found = 0; uint target = 0xfabe6d6d00000000000000000000000000000000000000000000000000000000; uint mask = 0xffffffff00000000000000000000000000000000000000000000000000000000; assembly { let len := mload(rawBytes) let data := add(rawBytes, 0x20) let end := add(data, len) if eq(and(mload(data), mask), target) { if eq(found, 0x0) { position := add(sub(len, sub(end, data)), 4) } found := add(found, 1) } data := add(data, 0x1) } }
14,105,758
./partial_match/3/0xa6D94C6C57bE9D525fBA4d1006D1Ff4d0B28B699/sources/CVPTokenTest.sol
Error messages for require statements/
function lock(bytes32 _reason, uint256 _amount, uint256 _time, address _of) public returns (bool); function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); function totalBalanceOf(address _of) public view returns (uint256 amount); function extendLock(bytes32 _reason, uint256 _time) public returns (bool); function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); function unlock(address _of) public returns (uint256 unlockableTokens); function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } pragma solidity 0.4.24; constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; }
5,232,958
pragma solidity ^0.4.18; // File: contracts-origin/AetherAccessControl.sol /// @title A facet of AetherCore that manages special access privileges. /// @dev See the AetherCore contract documentation to understand how the various contract facets are arranged. contract AetherAccessControl { // This facet controls access control for Laputa. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the AetherCore constructor. // // - The CFO: The CFO can withdraw funds from AetherCore and its auction contracts. // // - The COO: The COO can release properties to auction. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) public onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function withdrawBalance() external onlyCFO { cfoAddress.transfer(this.balance); } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() public onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } // File: contracts-origin/AetherBase.sol /// @title Base contract for Aether. Holds all common structs, events and base variables. /// @author Project Aether (https://www.aether.city) /// @dev See the PropertyCore contract documentation to understand how the various contract facets are arranged. contract AetherBase is AetherAccessControl { /*** EVENTS ***/ /// @dev The Construct event is fired whenever a property updates. event Construct ( address indexed owner, uint256 propertyId, PropertyClass class, uint8 x, uint8 y, uint8 z, uint8 dx, uint8 dz, string data ); /// @dev Transfer event as defined in current draft of ERC721. Emitted every /// time a property ownership is assigned. event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /*** DATA ***/ enum PropertyClass { DISTRICT, BUILDING, UNIT } /// @dev The main Property struct. Every property in Aether is represented /// by a variant of this structure. struct Property { uint32 parent; PropertyClass class; uint8 x; uint8 y; uint8 z; uint8 dx; uint8 dz; } /*** STORAGE ***/ /// @dev Ensures that property occupies unique part of the universe. bool[100][100][100] public world; /// @dev An array containing the Property struct for all properties in existence. The ID /// of each property is actually an index into this array. Property[] properties; /// @dev An array containing the district addresses in existence. uint256[] districts; /// @dev A measure of world progression. uint256 public progress; /// @dev The fee associated with constructing a unit property. uint256 public unitCreationFee = 0.05 ether; /// @dev Keeps track whether updating data is paused. bool public updateEnabled = true; /// @dev A mapping from property IDs to the address that owns them. All properties have /// some valid owner address, even gen0 properties are created with a non-zero owner. mapping (uint256 => address) public propertyIndexToOwner; /// @dev A mapping from property IDs to the data that is stored on them. mapping (uint256 => string) public propertyIndexToData; /// @dev A mapping from owner address to count of tokens that address owns. /// Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev Mappings between property nodes. mapping (uint256 => uint256) public districtToBuildingsCount; mapping (uint256 => uint256[]) public districtToBuildings; mapping (uint256 => uint256) public buildingToUnitCount; mapping (uint256 => uint256[]) public buildingToUnits; /// @dev A mapping from building propertyId to unit construction privacy. mapping (uint256 => bool) public buildingIsPublic; /// @dev A mapping from PropertyIDs to an address that has been approved to call /// transferFrom(). Each Property can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public propertyIndexToApproved; /// @dev Assigns ownership of a specific Property to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // since the number of properties is capped to 2^32 // there is no way to overflow this ownershipTokenCount[_to]++; // transfer ownership propertyIndexToOwner[_tokenId] = _to; // When creating new properties _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete propertyIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } function _createUnit( uint256 _parent, uint256 _x, uint256 _y, uint256 _z, address _owner ) internal returns (uint) { require(_x == uint256(uint8(_x))); require(_y == uint256(uint8(_y))); require(_z == uint256(uint8(_z))); require(!world[_x][_y][_z]); world[_x][_y][_z] = true; return _createProperty( _parent, PropertyClass.UNIT, _x, _y, _z, 0, 0, _owner ); } function _createBuilding( uint256 _parent, uint256 _x, uint256 _y, uint256 _z, uint256 _dx, uint256 _dz, address _owner, bool _public ) internal returns (uint) { require(_x == uint256(uint8(_x))); require(_y == uint256(uint8(_y))); require(_z == uint256(uint8(_z))); require(_dx == uint256(uint8(_dx))); require(_dz == uint256(uint8(_dz))); // Looping over world space. for(uint256 i = 0; i < _dx; i++) { for(uint256 j = 0; j <_dz; j++) { if (world[_x + i][0][_z + j]) { revert(); } world[_x + i][0][_z + j] = true; } } uint propertyId = _createProperty( _parent, PropertyClass.BUILDING, _x, _y, _z, _dx, _dz, _owner ); districtToBuildingsCount[_parent]++; districtToBuildings[_parent].push(propertyId); buildingIsPublic[propertyId] = _public; return propertyId; } function _createDistrict( uint256 _x, uint256 _z, uint256 _dx, uint256 _dz ) internal returns (uint) { require(_x == uint256(uint8(_x))); require(_z == uint256(uint8(_z))); require(_dx == uint256(uint8(_dx))); require(_dz == uint256(uint8(_dz))); uint propertyId = _createProperty( districts.length, PropertyClass.DISTRICT, _x, 0, _z, _dx, _dz, cooAddress ); districts.push(propertyId); return propertyId; } /// @dev An internal method that creates a new property and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Construct event /// and a Transfer event. function _createProperty( uint256 _parent, PropertyClass _class, uint256 _x, uint256 _y, uint256 _z, uint256 _dx, uint256 _dz, address _owner ) internal returns (uint) { require(_x == uint256(uint8(_x))); require(_y == uint256(uint8(_y))); require(_z == uint256(uint8(_z))); require(_dx == uint256(uint8(_dx))); require(_dz == uint256(uint8(_dz))); require(_parent == uint256(uint32(_parent))); require(uint256(_class) <= 3); Property memory _property = Property({ parent: uint32(_parent), class: _class, x: uint8(_x), y: uint8(_y), z: uint8(_z), dx: uint8(_dx), dz: uint8(_dz) }); uint256 _tokenId = properties.push(_property) - 1; // It's never going to happen, 4 billion properties is A LOT, but // let's just be 100% sure we never let this happen. require(_tokenId <= 4294967295); Construct( _owner, _tokenId, _property.class, _property.x, _property.y, _property.z, _property.dx, _property.dz, "" ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, _tokenId); return _tokenId; } /// @dev Computing height of a building with respect to city progression. function _computeHeight( uint256 _x, uint256 _z, uint256 _height ) internal view returns (uint256) { uint256 x = _x < 50 ? 50 - _x : _x - 50; uint256 z = _z < 50 ? 50 - _z : _z - 50; uint256 distance = x > z ? x : z; if (distance > progress) { return 1; } uint256 scale = 100 - (distance * 100) / progress ; uint256 height = 2 * progress * _height * scale / 10000; return height > 0 ? height : 1; } /// @dev Convenience function to see if this building has room for a unit. function canCreateUnit(uint256 _buildingId) public view returns(bool) { Property storage _property = properties[_buildingId]; if (_property.class == PropertyClass.BUILDING && (buildingIsPublic[_buildingId] || propertyIndexToOwner[_buildingId] == msg.sender) ) { uint256 totalVolume = _property.dx * _property.dz * (_computeHeight(_property.x, _property.z, _property.y) - 1); uint256 totalUnits = buildingToUnitCount[_buildingId]; return totalUnits < totalVolume; } return false; } /// @dev This internal function skips all validation checks. Ensure that // canCreateUnit() is required before calling this method. function _createUnitHelper(uint256 _buildingId, address _owner) internal returns(uint256) { // Grab a reference to the property in storage. Property storage _property = properties[_buildingId]; uint256 totalArea = _property.dx * _property.dz; uint256 index = buildingToUnitCount[_buildingId]; // Calculate next location. uint256 y = index / totalArea + 1; uint256 intermediate = index % totalArea; uint256 z = intermediate / _property.dx; uint256 x = intermediate % _property.dx; uint256 unitId = _createUnit( _buildingId, x + _property.x, y, z + _property.z, _owner ); buildingToUnitCount[_buildingId]++; buildingToUnits[_buildingId].push(unitId); // Return the new unit's ID. return unitId; } /// @dev Update allows for setting a building privacy. function updateBuildingPrivacy(uint _tokenId, bool _public) public { require(propertyIndexToOwner[_tokenId] == msg.sender); buildingIsPublic[_tokenId] = _public; } /// @dev Update allows for setting the data associated to a property. function updatePropertyData(uint _tokenId, string _data) public { require(updateEnabled); address _owner = propertyIndexToOwner[_tokenId]; require(msg.sender == _owner); propertyIndexToData[_tokenId] = _data; Property memory _property = properties[_tokenId]; Construct( _owner, _tokenId, _property.class, _property.x, _property.y, _property.z, _property.dx, _property.dz, _data ); } } // File: contracts-origin/ERC721Draft.sol /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } // File: contracts-origin/AetherOwnership.sol /// @title The facet of the Aether core contract that manages ownership, ERC-721 (draft) compliant. /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the PropertyCore contract documentation to understand how the various contract facets are arranged. contract AetherOwnership is AetherBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public name = "Aether"; string public symbol = "AETH"; function implementsERC721() public pure returns (bool) { return true; } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Property. /// @param _claimant the address we are validating against. /// @param _tokenId property id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return propertyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Property. /// @param _claimant the address we are confirming property is approved for. /// @param _tokenId property id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return propertyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Properties on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { propertyIndexToApproved[_tokenId] = _approved; } /// @dev Transfers a property owned by this contract to the specified address. /// Used to rescue lost properties. (There is no "proper" flow where this contract /// should be the owner of any Property. This function exists for us to reassign /// the ownership of Properties that users may have accidentally sent to our address.) /// @param _propertyId - ID of property /// @param _recipient - Address to send the property to function rescueLostProperty(uint256 _propertyId, address _recipient) public onlyCOO whenNotPaused { require(_owns(this, _propertyId)); _transfer(this, _recipient, _propertyId); } /// @notice Returns the number of Properties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Property to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// Laputa specifically) or your Property may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Property to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // You can only send your own property. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Property via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Property that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Property owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Property to be transfered. /// @param _to The address that should take ownership of the Property. Can be any address, /// including the caller. /// @param _tokenId The ID of the Property to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Properties currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return properties.length; } function totalDistrictSupply() public view returns(uint count) { return districts.length; } /// @notice Returns the address currently assigned ownership of a given Property. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = propertyIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Property IDs assigned to an address. /// @param _owner The owner whose Properties we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Kitty array looking for cats belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalProperties = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all properties have IDs starting at 1 and increasing // sequentially up to the totalProperties count. uint256 tokenId; for (tokenId = 1; tokenId <= totalProperties; tokenId++) { if (propertyIndexToOwner[tokenId] == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } } // File: contracts-origin/Auction/ClockAuctionBase.sol /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev DON'T give me your money. function() external {} // Modifiers to check that inputs can be safely stored with a certain // number of bits. We use constants and multiple modifiers to save gas. modifier canBeStoredWith64Bits(uint256 _value) { require(_value <= 18446744073709551615); _; } modifier canBeStoredWith128Bits(uint256 _value) { require(_value < 340282366920938463463374607431768211455); _; } /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the incoming bid is higher than the current // price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } // File: contracts-origin/Auction/ClockAuction.sol /// @title Clock auction for non-fungible tokens. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.implementsERC721()); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); nftAddress.transfer(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) public whenNotPaused canBeStoredWith128Bits(_startingPrice) canBeStoredWith128Bits(_endingPrice) canBeStoredWith64Bits(_duration) { require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) public payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) public { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner public { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) public view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) public view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } // File: contracts-origin/Auction/AetherClockAuction.sol /// @title Clock auction modified for sale of property contract AetherClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isAetherClockAuction = true; // Tracks last 5 sale price of gen0 property sales uint256 public saleCount; uint256[5] public lastSalePrices; // Delegate constructor function AetherClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) public canBeStoredWith128Bits(_startingPrice) canBeStoredWith128Bits(_endingPrice) canBeStoredWith64Bits(_duration) { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) public payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastSalePrices[saleCount % 5] = price; saleCount++; } } function averageSalePrice() public view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastSalePrices[i]; } return sum / 5; } } // File: contracts-origin/AetherAuction.sol /// @title Handles creating auctions for sale and siring of properties. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract AetherAuction is AetherOwnership{ /// @dev The address of the ClockAuction contract that handles sales of Aether. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. AetherClockAuction public saleAuction; /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) public onlyCEO { AetherClockAuction candidateContract = AetherClockAuction(_address); // NOTE: verify that a contract is what we expect require(candidateContract.isAetherClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Put a property up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _propertyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) public whenNotPaused { // Auction contract checks input sizes // If property is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _propertyId)); _approve(_propertyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the property. saleAuction.createAuction( _propertyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Transfers the balance of the sale auction contract /// to the AetherCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCOO { saleAuction.withdrawBalance(); } } // File: contracts-origin/AetherConstruct.sol // Auction wrapper functions /// @title all functions related to creating property contract AetherConstruct is AetherAuction { uint256 public districtLimit = 16; uint256 public startingPrice = 1 ether; uint256 public auctionDuration = 1 days; /// @dev Units can be contructed within public and owned buildings. function createUnit(uint256 _buildingId) public payable returns(uint256) { require(canCreateUnit(_buildingId)); require(msg.value >= unitCreationFee); if (msg.value > unitCreationFee) msg.sender.transfer(msg.value - unitCreationFee); uint256 propertyId = _createUnitHelper(_buildingId, msg.sender); return propertyId; } /// @dev Creation of unit properties. Only callable by COO function createUnitOmni( uint32 _buildingId, address _owner ) public onlyCOO { if (_owner == address(0)) { _owner = cooAddress; } require(canCreateUnit(_buildingId)); _createUnitHelper(_buildingId, _owner); } /// @dev Creation of building properties. Only callable by COO function createBuildingOmni( uint32 _districtId, uint8 _x, uint8 _y, uint8 _z, uint8 _dx, uint8 _dz, address _owner, bool _open ) public onlyCOO { if (_owner == address(0)) { _owner = cooAddress; } _createBuilding(_districtId, _x, _y, _z, _dx, _dz, _owner, _open); } /// @dev Creation of district properties, up to a limit. Only callable by COO function createDistrictOmni( uint8 _x, uint8 _z, uint8 _dx, uint8 _dz ) public onlyCOO { require(districts.length < districtLimit); _createDistrict(_x, _z, _dx, _dz); } /// @dev Creates a new property with the given details and /// creates an auction for it. Only callable by COO. function createBuildingAuction( uint32 _districtId, uint8 _x, uint8 _y, uint8 _z, uint8 _dx, uint8 _dz, bool _open ) public onlyCOO { uint256 propertyId = _createBuilding(_districtId, _x, _y, _z, _dx, _dz, address(this), _open); _approve(propertyId, saleAuction); saleAuction.createAuction( propertyId, _computeNextPrice(), 0, auctionDuration, address(this) ); } /// @dev Updates the minimum payment required for calling createUnit(). Can only /// be called by the COO address. function setUnitCreationFee(uint256 _value) public onlyCOO { unitCreationFee = _value; } /// @dev Update world progression factor allowing for buildings to grow taller // as the city expands. Only callable by COO. function setProgress(uint256 _progress) public onlyCOO { require(_progress <= 100); require(_progress > progress); progress = _progress; } /// @dev Set property data updates flag. Only callable by COO. function setUpdateState(bool _updateEnabled) public onlyCOO { updateEnabled = _updateEnabled; } /// @dev Computes the next auction starting price, given the average of the past /// 5 prices + 50%. function _computeNextPrice() internal view returns (uint256) { uint256 avePrice = saleAuction.averageSalePrice(); // sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1). require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < startingPrice) { nextPrice = startingPrice; } return nextPrice; } } // File: contracts-origin/AetherCore.sol /// @title Aether: A city on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) contract AetherCore is AetherConstruct { // This is the main Aether contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. The auctions are seperate since their logic is somewhat complex // and there's always a risk of subtle bugs. By keeping them in their own contracts, we can upgrade // them without disrupting the main contract that tracks property ownership. // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of Aether. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - AetherBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - AetherAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - AetherOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - AetherAuction: Here we have the public methods for auctioning or bidding on property. // The actual auction functionality is handled in two sibling contracts while auction // creation and bidding is mostly mediated through this facet of the core contract. // // - AetherConstruct: This final facet contains the functionality we use for creating new gen0 cats. // the community is new). // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main Aether smart contract instance. function AetherCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) public onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) ); } /// @notice Returns all the relevant information about a specific property. /// @param _id The ID of the property of interest. function getProperty(uint256 _id) public view returns ( uint32 parent, uint8 class, uint8 x, uint8 y, uint8 z, uint8 dx, uint8 dz, uint8 height ) { Property storage property = properties[_id]; parent = uint32(property.parent); class = uint8(property.class); height = uint8(property.y); if (property.class == PropertyClass.BUILDING) { y = uint8(_computeHeight(property.x, property.z, property.y)); } else { y = uint8(property.y); } x = uint8(property.x); z = uint8(property.z); dx = uint8(property.dx); dz = uint8(property.dz); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } }
Updates the minimum payment required for calling createUnit(). Can only be called by the COO address.
function setUnitCreationFee(uint256 _value) public onlyCOO { unitCreationFee = _value; }
1,090,919
/** * Copyright 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "SafeMath.sol"; import "GovernorBravoDelegate.sol"; import "IStaking.sol"; import "StakingVoteDelegatorState.sol"; import "StakingVoteDelegatorConstants.sol"; import "SafeERC20.sol"; import "PausableGuardian.sol"; contract StakingVoteDelegator is StakingVoteDelegatorState, StakingVoteDelegatorConstants, PausableGuardian { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @notice Getter * @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) pausable external { if(delegatee == msg.sender){ delegatee = ZERO_ADDRESS; } 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) pausable external { if(delegatee == msg.sender){ delegatee = ZERO_ADDRESS; } bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes("STAKING")), 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 != ZERO_ADDRESS, "Staking::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Staking::delegateBySig: invalid nonce"); require(now <= expiry, "Staking::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) public view returns (uint256) { require(blockNumber < block.number, "Staking::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 { if(delegatee == delegator || delegator == ZERO_ADDRESS) return; address oldDelegate = _delegates[delegator]; uint256 delegatorBalance = staking.votingFromStakedBalanceOf(delegator); _delegates[delegator] = delegatee; //ZERO_ADDRESS means that user wants to revoke delegation if(delegatee == ZERO_ADDRESS && oldDelegate != ZERO_ADDRESS){ if(totalDelegators[oldDelegate] > 0) totalDelegators[oldDelegate]--; if(totalDelegators[oldDelegate] == 0 && oldDelegate != ZERO_ADDRESS){ uint32 dstRepNum = numCheckpoints[oldDelegate]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[oldDelegate][dstRepNum - 1].votes : 0; uint256 dstRepNew = 0; _writeCheckpoint(oldDelegate, dstRepNum, dstRepOld, dstRepNew); return; } } else if(delegatee != ZERO_ADDRESS){ totalDelegators[delegatee]++; if(totalDelegators[oldDelegate] > 0) totalDelegators[oldDelegate]--; } emit DelegateChanged(delegator, oldDelegate, delegatee); _moveDelegates(oldDelegate, delegatee, delegatorBalance); } function moveDelegates( address srcRep, address dstRep, uint256 amount ) public { require(msg.sender == address(staking), "unauthorized"); _moveDelegates(srcRep, dstRep, amount); } function moveDelegatesByVotingBalance( uint256 votingBalanceBefore, uint256 votingBalanceAfter, address account ) public { require(msg.sender == address(staking), "unauthorized"); address currentDelegate = _delegates[account]; if(currentDelegate == ZERO_ADDRESS) return; if(votingBalanceBefore > votingBalanceAfter){ _moveDelegates(currentDelegate, ZERO_ADDRESS, votingBalanceBefore.sub(votingBalanceAfter) ); } else{ _moveDelegates(ZERO_ADDRESS, currentDelegate, votingBalanceAfter.sub(votingBalanceBefore) ); } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != ZERO_ADDRESS) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub((amount > srcRepOld)? srcRepOld : amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != ZERO_ADDRESS) { // 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, "Staking::_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; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "IERC20.sol"; import "GovernorBravoInterfaces.sol"; contract GovernorBravoDelegate is GovernorBravoDelegateStorageV1, GovernorBravoEvents { /// @notice The name of this contract string public constant name = "bZx Governor Bravo"; /// @notice The minimum setable proposal threshold uint public constant MIN_PROPOSAL_THRESHOLD = 5150000e18; // 5,150,000 = 0.5% of BZRX /// @notice The maximum setable proposal threshold uint public constant MAX_PROPOSAL_THRESHOLD = 20600000e18; // 20,600,000 = 2% of BZRX /// @notice The minimum setable voting period uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours /// @notice The max setable voting period uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks /// @notice The min setable voting delay uint public constant MIN_VOTING_DELAY = 1; /// @notice The max setable voting delay uint public constant MAX_VOTING_DELAY = 40320; // About 1 week /// @notice The maximum number of actions that can be included in a proposal uint public constant proposalMaxOperations = 100; // 100 actions /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); mapping (uint => uint) public quorumVotesForProposal; // proposalId => quorum votes required /** * @notice Used to initialize the contract during delegator contructor * @param timelock_ The address of the Timelock * @param staking_ The address of the STAKING * @param votingPeriod_ The initial voting period * @param votingDelay_ The initial voting delay * @param proposalThreshold_ The initial proposal threshold */ function initialize(address timelock_, address staking_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public { require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once"); require(msg.sender == admin, "GovernorBravo::initialize: admin only"); require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address"); require(staking_ != address(0), "GovernorBravo::initialize: invalid STAKING address"); require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period"); require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay"); require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold"); timelock = TimelockInterface(timelock_); staking = StakingInterface(staking_); votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThreshold = proposalThreshold_; guardian = msg.sender; } /** * @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold * @param targets Target addresses for proposal calls * @param values Eth values for proposal calls * @param signatures Function signatures for proposal calls * @param calldatas Calldatas for proposal calls * @param description String description of the proposal * @return Proposal id of new proposal */ function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorBravo::propose: must provide actions"); require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal"); } uint proposalId = proposalCount + 1; require(staking._setProposalVals(msg.sender, proposalId) > proposalThreshold, "GovernorBravo::propose: proposer votes below proposal threshold"); proposalCount = proposalId; uint startBlock = add256(block.number, votingDelay); uint endBlock = add256(startBlock, votingPeriod); Proposal memory newProposal = Proposal({ id: proposalId, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, abstainVotes: 0, canceled: false, executed: false }); proposals[proposalId] = newProposal; latestProposalIds[msg.sender] = proposalId; quorumVotesForProposal[proposalId] = quorumVotes(); emit ProposalCreated(proposalId, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return proposalId; } /** * @notice Queues a proposal of state succeeded * @param proposalId The id of the proposal to queue */ function queue(uint proposalId) external { require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } /** * @notice Executes a queued proposal if eta has passed * @param proposalId The id of the proposal to execute */ function execute(uint proposalId) external payable { require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } /** * @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold * @param proposalId The id of the proposal to cancel */ function cancel(uint proposalId) external { require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == proposal.proposer || staking.votingBalanceOfNow(proposal.proposer) < proposalThreshold || msg.sender == guardian, "GovernorBravo::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } /** * @notice Gets the current voting quroum * @return The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed */ // TODO: Update for OOKI. Handle OOKI surplus mint function quorumVotes() public view returns (uint256) { uint256 vestingSupply = IERC20(0x56d811088235F11C8920698a204A5010a788f4b3) // BZRX .balanceOf(0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F); // vBZRX uint256 circulatingSupply = 1030000000e18 - vestingSupply; // no overflow uint256 quorum = circulatingSupply * 4 / 100; if (quorum < 15450000e18) { // min quorum is 1.5% of totalSupply quorum = 15450000e18; } return quorum; } /** * @notice Gets actions of a proposal * @param proposalId the id of the proposal * @return Targets, values, signatures, and calldatas of the proposal actions */ function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice Gets the receipt for a voter on a given proposal * @param proposalId the id of proposal * @param voter The address of the voter * @return The voting receipt */ function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } /** * @notice Gets the state of a proposal * @param proposalId The id of the proposal * @return Proposal state */ function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotesForProposal[proposalId]) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } /** * @notice Cast a vote for a proposal * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain */ function castVote(uint proposalId, uint8 support) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), ""); } /** * @notice Cast a vote for a proposal with a reason * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @param reason The reason given for the vote by the voter */ function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason); } /** * @notice Cast a vote for a proposal by signature * @dev External function that accepts EIP-712 signatures for voting on proposals. */ function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature"); emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), ""); } /** * @dev Allows batching to castVote function */ function castVotes(uint[] calldata proposalIds, uint8[] calldata supportVals) external { require(proposalIds.length == supportVals.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), ""); } } /** * @dev Allows batching to castVoteWithReason function */ function castVotesWithReason(uint[] calldata proposalIds, uint8[] calldata supportVals, string[] calldata reasons) external { require(proposalIds.length == supportVals.length && proposalIds.length == reasons.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), reasons[i]); } } /** * @dev Allows batching to castVoteBySig function */ function castVotesBySig(uint[] calldata proposalIds, uint8[] calldata supportVals, uint8[] calldata vs, bytes32[] calldata rs, bytes32[] calldata ss) external { require(proposalIds.length == supportVals.length && proposalIds.length == vs.length && proposalIds.length == rs.length && proposalIds.length == ss.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { castVoteBySig(proposalIds[i], supportVals[i], vs[i], rs[i], ss[i]); } } /** * @notice Internal function that caries out voting logic * @param voter The voter that is casting their vote * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @return The number of votes cast */ function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) { require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed"); require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted"); // 2**96-1 is greater than total supply of bzrx 1.3b*1e18 thus guaranteeing it won't ever overflow uint96 votes = uint96(staking.votingBalanceOf(voter, proposalId)); if (support == 0) { proposal.againstVotes = add256(proposal.againstVotes, votes); } else if (support == 1) { proposal.forVotes = add256(proposal.forVotes, votes); } else if (support == 2) { proposal.abstainVotes = add256(proposal.abstainVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; return votes; } /** * @notice Admin function for setting the voting delay * @param newVotingDelay new voting delay, in blocks */ function __setVotingDelay(uint newVotingDelay) external { require(msg.sender == admin, "GovernorBravo::__setVotingDelay: admin only"); require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::__setVotingDelay: invalid voting delay"); uint oldVotingDelay = votingDelay; votingDelay = newVotingDelay; emit VotingDelaySet(oldVotingDelay,votingDelay); } /** * @notice Admin function for setting the voting period * @param newVotingPeriod new voting period, in blocks */ function __setVotingPeriod(uint newVotingPeriod) external { require(msg.sender == admin, "GovernorBravo::__setVotingPeriod: admin only"); require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::__setVotingPeriod: invalid voting period"); uint oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); } /** * @notice Admin function for setting the proposal threshold * @dev newProposalThreshold must be greater than the hardcoded min * @param newProposalThreshold new proposal threshold */ function __setProposalThreshold(uint newProposalThreshold) external { require(msg.sender == admin, "GovernorBravo::__setProposalThreshold: admin only"); require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::__setProposalThreshold: invalid proposal threshold"); uint oldProposalThreshold = proposalThreshold; proposalThreshold = newProposalThreshold; emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function __setPendingLocalAdmin(address newPendingAdmin) external { // Check caller = admin require(msg.sender == admin, "GovernorBravo:__setPendingLocalAdmin: admin only"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function __acceptLocalAdmin() external { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:__acceptLocalAdmin: pending admin only"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } function __changeGuardian(address guardian_) public { require(msg.sender == guardian, "GovernorBravo::__changeGuardian: sender must be gov guardian"); require(guardian_ != address(0), "GovernorBravo::__changeGuardian: not allowed"); guardian = guardian_; } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorBravo::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorBravo::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorBravo::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorBravo::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainIdInternal() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; contract GovernorBravoEvents { /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal /// @param voter The address which casted a vote /// @param proposalId The proposal id which was voted on /// @param support Support value for the vote. 0=against, 1=for, 2=abstain /// @param votes Number of votes which were cast by the voter /// @param reason The reason given for the vote by the voter event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); /// @notice An event emitted when the voting delay is set event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay); /// @notice An event emitted when the voting period is set event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod); /// @notice Emitted when implementation is changed event NewImplementation(address oldImplementation, address newImplementation); /// @notice Emitted when proposal threshold is set event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold); /// @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /// @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address oldAdmin, address newAdmin); } contract GovernorBravoDelegatorStorage { /// @notice Administrator for this contract address public admin; /// @notice Pending administrator for this contract address public pendingAdmin; /// @notice Active brains of Governor address public implementation; /// @notice The address of the Governor Guardian address public guardian; } /** * @title Storage for Governor Bravo Delegate * @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new * contract which implements GovernorBravoDelegateStorageV1 and following the naming convention * GovernorBravoDelegateStorageVX. */ contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage { /// @notice The delay before voting on a proposal may take place, once proposed, in blocks uint public votingDelay; /// @notice The duration of voting on a proposal, in blocks uint public votingPeriod; /// @notice The number of votes required in order for a voter to become a proposer uint public proposalThreshold; /// @notice Initial proposal id set at become uint public initialProposalId; /// @notice The total number of proposals uint public proposalCount; /// @notice The address of the bZx Protocol Timelock TimelockInterface public timelock; /// @notice The address of the bZx governance token StakingInterface public staking; /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Current number of votes for abstaining for this proposal uint abstainVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal or abstains uint8 support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } interface TimelockInterface { function delay() external view returns (uint); function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface StakingInterface { function votingBalanceOf( address account, uint proposalCount) external view returns (uint totalVotes); function votingBalanceOfNow( address account) external view returns (uint totalVotes); function _setProposalVals( address account, uint proposalCount) external returns (uint); } interface GovernorAlpha { /// @notice The total number of proposals function proposalCount() external returns (uint); } /** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity >=0.5.0 <=0.8.4; pragma experimental ABIEncoderV2; interface IStaking { struct ProposalState { uint256 proposalTime; uint256 iBZRXWeight; uint256 lpBZRXBalance; uint256 lpTotalSupply; } struct AltRewardsUserInfo { uint256 rewardsPerShare; uint256 pendingRewards; } function vestingLastSync(address account) external view returns (uint256); function getCurrentFeeTokens() external view returns (address[] memory); function maxUniswapDisagreement() external view returns (uint256); function isPaused() external view returns (bool); function fundsWallet() external view returns (address); function callerRewardDivisor() external view returns (uint256); function maxCurveDisagreement() external view returns (uint256); function rewardPercent() external view returns (uint256); function addRewards(uint256 newBZRX, uint256 newStableCoin) external; function stake( address[] calldata tokens, uint256[] calldata values ) external; function unstake( address[] calldata tokens, uint256[] calldata values ) external; function earned(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function pendingCrvRewards(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function getVariableWeights() external view returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight); function balanceOfByAsset( address token, address account) external view returns (uint256 balance); function balanceOfByAssets( address account) external view returns ( uint256 bzrxBalance, uint256 iBZRXBalance, uint256 vBZRXBalance, uint256 LPTokenBalance, uint256 LPTokenBalanceOld ); function balanceOfStored( address account) external view returns (uint256 vestedBalance, uint256 vestingBalance); function totalSupplyStored() external view returns (uint256 supply); function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime) external view returns (uint256 vested); function votingBalanceOf( address account, uint256 proposalId) external view returns (uint256 totalVotes); function votingBalanceOfNow( address account) external view returns (uint256 totalVotes); function votingFromStakedBalanceOf( address account) external view returns (uint256 totalVotes); function _setProposalVals( address account, uint256 proposalId) external returns (uint256); function exit() external; function addAltRewards(address token, uint256 amount) external; function governor() external view returns(address); } /** * Copyright 2017-2021, bZxDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "StakingUpgradeable.sol"; import "SafeMath.sol"; import "SafeERC20.sol"; import "EnumerableBytes32Set.sol"; import "IStaking.sol"; contract StakingVoteDelegatorState is StakingUpgradeable { // A record of each accounts delegate // delegator => delegatee 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; mapping (address => uint256) public totalDelegators; } /** * Copyright 2017-2021, bZxDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "Ownable.sol"; contract StakingUpgradeable is Ownable { address public implementation; } pragma solidity ^0.5.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // 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; } } pragma solidity ^0.5.0; import "IERC20.sol"; import "SafeMath.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * Copyright 2017-2021, bZxDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; /** * @dev Library for managing loan sets * * 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. * * Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. * */ library EnumerableBytes32Set { struct Bytes32Set { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) index; bytes32[] values; } /** * @dev Add an address value to a set. O(1). * Returns false if the value was already in the set. */ function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return addBytes32(set, value); } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)){ set.index[value] = set.values.push(value); return true; } else { return false; } } /** * @dev Removes an address value from a set. O(1). * Returns false if the value was not present in the set. */ function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return removeBytes32(set, value); } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (lastIndex != toDeleteIndex) { bytes32 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns true if the value is in the set. O(1). */ function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool) { bytes32 value; assembly { value := addrvalue } return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * 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. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(Bytes32Set storage set, uint256 start, uint256 count) internal view returns (bytes32[] memory output) { uint256 end = start + count; require(end >= start, "addition overflow"); end = set.values.length < end ? set.values.length : end; if (end == 0 || start >= end) { return output; } output = new bytes32[](end-start); for (uint256 i = start; i < end; i++) { output[i-start] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return set.values.length; } /** @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 get(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return set.values[index]; } /** @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 getAddress(Bytes32Set storage set, uint256 index) internal view returns (address) { bytes32 value = set.values[index]; address addrvalue; assembly { addrvalue := value } return addrvalue; } } /** * Copyright 2017-2021, bZxDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "IStaking.sol"; contract StakingVoteDelegatorConstants { address constant internal ZERO_ADDRESS = address(0); IStaking constant staking = IStaking(0xe95Ebce2B02Ee07dEF5Ed6B53289801F7Fc137A4); /// @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); } /** * Copyright 2017-2021, bZxDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "Ownable.sol"; contract PausableGuardian is Ownable { // keccak256("Pausable_FunctionPause") bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; // keccak256("Pausable_GuardianAddress") bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf; modifier pausable { require(!_isPaused(msg.sig), "paused"); _; } modifier onlyGuardian { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); _; } function _isPaused(bytes4 sig) public view returns (bool isPaused) { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { isPaused := sload(slot) } } function toggleFunctionPause(bytes4 sig) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 1) } } function toggleFunctionUnPause(bytes4 sig) public { // only DAO can unpause, and adding guardian temporarily require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 0) } } function changeGuardian(address newGuardian) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); assembly { sstore(Pausable_GuardianAddress, newGuardian) } } function getGuardian() public view returns (address guardian) { assembly { guardian := sload(Pausable_GuardianAddress) } } }
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) pausable external { if(delegatee == msg.sender){ delegatee = ZERO_ADDRESS; } bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes("STAKING")), 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 != ZERO_ADDRESS, "Staking::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Staking::delegateBySig: invalid nonce"); require(now <= expiry, "Staking::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
1,496,436
./partial_match/1/0x9781C4E9B9cc6Ac18405891DF20Ad3566FB6B301/sources/SavingsManager.sol
Freezes streaming of mAssets/
function freezeStreams() external onlyGovernor whenStreamsNotFrozen { streamsFrozen = true; emit StreamsFrozen(); }
16,112,380
./full_match/1/0x11D1463D2D93CB26cAF34C40Cb21539e61Ef47Fa/sources/contracts/vaults/DolletVault.sol
Function to send funds into the strategy and put them to work. It's primarily called by the vault's deposit() function. _token The token used in the deposit/
function earn(IERC20Upgradeable _token, uint256 _minWant) internal { uint256 _tokenBal = _token.balanceOf(address(this)); _token.safeTransfer(address(strategy), _tokenBal); strategy.deposit(address(_token), msg.sender, _minWant); }
16,429,873
pragma solidity 0.5.7; /* required for transpiler */ #define TRANSPILE /* data constants */ #define WORD_0 0 /* 32*0 = 0 */ #define WORD_1 32 /* 32*1 = 32 */ #define WORD_2 64 /* 32*2 = 64 */ #define WORD_3 96 /* 32*3 = 96 */ #define WORD_4 128 /* 32*4 = 128 */ #define WORD_5 160 /* 32*5 = 160 */ #define WORD_6 192 /* 32*6 = 192 */ #define WORD_7 224 /* 32*7 = 224 */ #define WORD_8 256 /* 32*8 = 256 */ #define WORD_9 288 /* 32*9 = 288 */ #define WORD_10 320 /* 32*10 = 320 */ #define WORD_11 352 /* 32*11 = 352 */ #define WORD_12 384 /* 32*12 = 384 */ #define WORD_13 416 /* 32*13 = 416 */ #define WORD_14 448 /* 32*14 = 448 */ #define U64_MASK 0xFFFFFFFFFFFFFFFF #define U64_MAX 0xFFFFFFFFFFFFFFFF #define I64_MAX 0x7FFFFFFFFFFFFFFF #define I64_MIN 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8000000000000000 #define U256_MAX 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF #define MIN_UNLOCK_AT 28800 /* 8 hours in seconds */ #define MAX_UNLOCK_AT 1209600 /* 14 days in seconds */ #define TWO_HOURS 7200 /* 2 hours in seconds */ #define TWO_DAYS 172800 /* 2 days in seconds */ #define PRICE_UNITS 100000000 /* * Resolves to 1 if number cannot fit in i64. * * Valid range for i64 [-2^63, 2^64-1] * = [ -9,223,372,036,854,775,808, 9,223,372,036,854,775,807 ] * = (64 bit) [ 0x8000000000000000, 0x7fffffffffffffff ] * = (256 bit) = [ 0xffffffffffffffffffffffffffffffffffffffffffffffff8000000000000000, 0x7fffffffffffffff ] */ contract DCN { event UserCreated(address indexed creator, uint64 user_id); event UserTradeAddressUpdated(uint64 user_id); event SessionUpdated(uint64 user_id, uint64 exchange_id); event ExchangeDeposit(uint64 user_id, uint64 exchange_id, uint32 asset_id); /* address allowed to update self and add assets and exchanges */ uint256 creator; uint256 creator_recovery; uint256 creator_recovery_proposed; /* number of users */ uint256 user_count; /* number of exchanges registered */ uint256 exchange_count; /* number of assets registered */ uint256 asset_count; /* used to disable features in case of bug */ uint256 security_locked_features; uint256 security_locked_features_proposed; uint256 security_proposed_unlock_timestamp; /* maximum values */ #define EXCHANGE_COUNT 4294967296 /* 2^32 */ #define ASSET_COUNT 4294967296 /* 2^32 */ #define USER_COUNT 18446744073709551616 /* 2^64 */ #define MARKET_COUNT 18446744073709551616 /* 2^64 (2^32 * 2^32 every asset combination) */ struct Exchange { /* 11 byte name of the exchange */ uint88 name; /* prevents exchange from applying settlement groups */ uint8 locked; /* address used to manage exchange */ address owner; /* address to withdraw funds */ uint256 withdraw_address; /* recovery address to change the owner and withdraw address */ uint256 recovery_address; /* a proposed address to change recovery_address */ uint256 recovery_address_proposed; /* asset balances (in session balance units) */ uint256[ASSET_COUNT] balances; } struct Asset { /* 8 byte symbol of the asset */ uint64 symbol; /* used to scale between wallet and state balances */ uint192 unit_scale; /* address of the ERC-20 Token */ uint256 contract_address; } struct MarketState { /* net quote balance change due to settlements */ int64 quote_qty; /* net base balance change due to settlements */ int64 base_qty; /* total fees used */ uint64 fee_used; /* max value for fee_used */ uint64 fee_limit; /* min allowed value for min_quote_qty after settlement */ int64 min_quote_qty; /* min allowed value for min_base_qty after settlement */ int64 min_base_qty; /* max scaled quote/base ratio when long after settlement */ uint64 long_max_price; /* min scaled quote/base ratio when short after settlement */ uint64 short_min_price; /* version to prevent old limits from being set */ uint64 limit_version; /* how much quote_qty has been shifted by */ int96 quote_shift; /* how much base_qty has been shifted by */ int96 base_shift; } struct SessionBalance { /* used for exchange to sync balances with DCN (scaled) */ uint128 total_deposit; /* amount given to user that will be repaid in settlement (scaled) */ uint64 unsettled_withdraw_total; /* current balance of asset (scaled) */ uint64 asset_balance; } struct ExchangeSession { /* timestamp used to prevent user withdraws and allow settlements */ uint256 unlock_at; /* address used to interact with session */ uint256 trade_address; /* user balances locked with the exchange */ SessionBalance[ASSET_COUNT] balances; /* market states to protect locked balances */ MarketState[MARKET_COUNT] market_states; } struct User { /* address used to sign trading limits */ uint256 trade_address; /* address used to withdraw funds */ uint256 withdraw_address; /* address used to update trade_address / withdraw_address */ uint256 recovery_address; /* proposed address to update recovery_address */ uint256 recovery_address_proposed; /* balances under the user's control */ uint256[ASSET_COUNT] balances; /* exchange sessions */ ExchangeSession[EXCHANGE_COUNT] exchange_sessions; } User[USER_COUNT] users; Asset[ASSET_COUNT] assets; Exchange[EXCHANGE_COUNT] exchanges; constructor() public { assembly { sstore(creator_slot, caller) sstore(creator_recovery_slot, caller) } } /* utility macros */ #define REVERT(code) \ mstore(WORD_1, code) revert(const_add(WORD_1, 31), 1) #define DEBUG_REVERT(data) \ mstore(WORD_1, data) revert(WORD_1, WORD_1) #define INVALID_I64(variable) \ or(slt(variable, I64_MIN), sgt(variable, I64_MAX)) #define MSTORE_STR(MSTORE_VAR, STR_OFFSET, STR_LEN, STR_DATA) \ mstore(MSTORE_VAR, STR_OFFSET) \ mstore(add(MSTORE_VAR, STR_OFFSET), STR_LEN) \ mstore(add(MSTORE_VAR, const_add(STR_OFFSET, WORD_1)), STR_DATA) #define RETURN_0(VALUE) \ mstore(return_value_mem, VALUE) #define RETURN(WORD, VALUE) \ mstore(add(return_value_mem, WORD), VALUE) #define VALID_USER_ID(USER_ID, REVERT_1) \ { \ let user_count := sload(user_count_slot) \ if iszero(lt(USER_ID, user_count)) { \ REVERT(REVERT_1) \ } \ } #define VALID_ASSET_ID(asset_id, REVERT_1) \ { \ let asset_count := sload(asset_count_slot) \ if iszero(lt(asset_id, asset_count)) { \ REVERT(REVERT_1) \ } \ } \ #define VALID_EXCHANGE_ID(EXCHANGE_ID, REVERT_1) \ { \ let exchange_count := sload(exchange_count_slot) \ if iszero(lt(EXCHANGE_ID, exchange_count)) { \ REVERT(REVERT_1) \ } \ } /* math macros */ #define CAST_64_NEG(variable) \ variable := signextend(7, variable) #define CAST_96_NEG(variable) \ variable := signextend(11, variable) #define U64_OVERFLOW(NUMBER) \ gt(NUMBER, U64_MAX) /* pointer macros */ #define ASSET_PTR_(ASSET_ID) \ pointer(Asset, assets_slot, ASSET_ID) #define EXCHANGE_PTR_(EXCHANGE_ID) \ pointer(Exchange, exchanges_slot, EXCHANGE_ID) #define EXCHANGE_BALANCE_PTR_(EXCHANGE_PTR, ASSET_ID) \ pointer(u256, pointer_attr(Exchange, EXCHANGE_PTR, balances), ASSET_ID) #define USER_PTR_(USER_ID) \ pointer(User, users_slot, USER_ID) #define USER_BALANCE_PTR_(USER_PTR, ASSET_ID) \ pointer(u256, pointer_attr(User, USER_PTR, balances), ASSET_ID) #define SESSION_PTR_(USER_PTR, EXCHANGE_ID) \ pointer(ExchangeSession, pointer_attr(User, USER_PTR, exchange_sessions), EXCHANGE_ID) #define SESSION_BALANCE_PTR_(SESSION_PTR, ASSET_ID) \ pointer(SessionBalance, pointer_attr(ExchangeSession, SESSION_PTR, balances), ASSET_ID) #define MARKET_IDX(QUOTE_ASSET_ID, BASE_ASSET_ID) \ or(mul(QUOTE_ASSET_ID, ASSET_COUNT), BASE_ASSET_ID) #define MARKET_STATE_PTR_(SESSION_PTR, QUOTE_ASSET_ID, BASE_ASSET_ID) \ pointer(MarketState, pointer_attr(ExchangeSession, SESSION_PTR, market_states), MARKET_IDX(QUOTE_ASSET_ID, BASE_ASSET_ID)) /* feature flags to disable functions */ #define FEATURE_ADD_ASSET 0x1 #define FEATURE_ADD_EXCHANGE 0x2 #define FEATURE_CREATE_USER 0x4 #define FEATURE_EXCHANGE_DEPOSIT 0x8 #define FEATURE_USER_DEPOSIT 0x10 #define FEATURE_TRANSFER_TO_SESSION 0x20 #define FEATURE_DEPOSIT_ASSET_TO_SESSION 0x40 #define FEATURE_EXCHANGE_TRANSFER_FROM 0x80 #define FEATURE_EXCHANGE_SET_LIMITS 0x100 #define FEATURE_APPLY_SETTLEMENT_GROUPS 0x200 #define FEATURE_USER_MARKET_RESET 0x400 #define FEATURE_RECOVER_UNSETTLED_WITHDRAWS 0x800 #define FEATURE_ALL U256_MAX #define SECURITY_FEATURE_CHECK(FEATURE, REVERT_1) \ { \ let locked_features := sload(security_locked_features_slot) \ if and(locked_features, FEATURE) { REVERT(REVERT_1) } \ } /* ERC_20 */ #define ERC_20_SEND(TOKEN_ADDRESS, TO_ADDRESS, AMOUNT, REVERT_1, REVERT_2) \ mstore(transfer_in_mem, fn_hash("transfer(address,uint256)")) \ mstore(add(transfer_in_mem, 4), TO_ADDRESS) \ mstore(add(transfer_in_mem, 36), AMOUNT) \ /* call external contract */ \ { \ let success := call( \ gas, \ TOKEN_ADDRESS, \ /* don't send any ether */ 0, \ transfer_in_mem, \ /* transfer_in_mem size (bytes) */ 68, \ transfer_out_mem, \ /* transfer_out_mem size (bytes) */ 32 \ ) \ \ if iszero(success) { \ REVERT(REVERT_1) \ } \ \ switch returndatasize() \ /* invalid ERC-20 Token, doesn't return anything and didn't revert: success */ \ case 0 { } \ /* valid ERC-20 Token, has return value */ \ case 32 { \ let result := mload(transfer_out_mem) \ if iszero(result) { \ REVERT(REVERT_2) \ } \ } \ /* returned a non standard amount of data: fail */ \ default { \ REVERT(REVERT_2) \ } \ } #define ERC_20_DEPOSIT(TOKEN_ADDRESS, FROM_ADDRESS, TO_ADDRESS, AMOUNT, REVERT_1, REVERT_2) \ mstore(transfer_in_mem, /* transferFrom(address,address,uint256) */ fn_hash("transferFrom(address,address,uint256)")) \ mstore(add(transfer_in_mem, 4), FROM_ADDRESS) \ mstore(add(transfer_in_mem, 36), TO_ADDRESS) \ mstore(add(transfer_in_mem, 68), AMOUNT) \ /* call external contract */ \ { \ let success := call( \ gas, \ TOKEN_ADDRESS, \ /* don't send any ether */ 0, \ transfer_in_mem, \ /* transfer_in_mem size (bytes) */ 100, \ transfer_out_mem, \ /* transfer_out_mem size (bytes) */ 32 \ ) \ if iszero(success) { \ REVERT(REVERT_1) \ } \ switch returndatasize() \ /* invalid ERC-20 Token, doesn't return anything and didn't revert: success */ \ case 0 { } \ /* valid ERC-20 Token, has return value */ \ case 32 { \ let result := mload(transfer_out_mem) \ if iszero(result) { \ REVERT(REVERT_2) \ } \ } \ /* returned a non standard amount of data: fail */ \ default { \ REVERT(REVERT_2) \ } \ } function get_security_state() public view returns (uint256 locked_features, uint256 locked_features_proposed, uint256 proposed_unlock_timestamp) { uint256[3] memory return_value_mem; assembly { RETURN_0(sload(security_locked_features_slot)) RETURN(WORD_1, sload(security_locked_features_proposed_slot)) RETURN(WORD_2, sload(security_proposed_unlock_timestamp_slot)) return(return_value_mem, WORD_3) } } function get_creator() public view returns (address dcn_creator, address dcn_creator_recovery, address dcn_creator_recovery_proposed) { uint256[3] memory return_value_mem; assembly { RETURN_0(sload(creator_slot)) RETURN(WORD_1, sload(creator_recovery_slot)) RETURN(WORD_2, sload(creator_recovery_proposed_slot)) return(return_value_mem, WORD_3) } } function get_asset(uint32 asset_id) public view returns (string memory symbol, uint192 unit_scale, address contract_address) { uint256[5] memory return_value_mem; assembly { let asset_count := sload(asset_count_slot) if iszero(lt(asset_id, asset_count)) { REVERT(1) } let asset_ptr := ASSET_PTR_(asset_id) let asset_0 := sload(asset_ptr) let asset_1 := sload(add(asset_ptr, 1)) MSTORE_STR(return_value_mem, WORD_3, 8, asset_0) RETURN(WORD_1, attr(Asset, 0, asset_0, unit_scale)) RETURN(WORD_2, attr(Asset, 1, asset_1, contract_address)) return(return_value_mem, const_add(WORD_3, /* string header */ WORD_1 , /* string data */ 8)) } } function get_exchange(uint32 exchange_id) public view returns ( string memory name, bool locked, address owner, address withdraw_address, address recovery_address, address recovery_address_proposed ) { /* [ name_offset, owner, withdraw_address, recovery_address, recovery_address_proposed, name_len, name_data(12) ] */ uint256[8] memory return_value_mem; assembly { let exchange_count := sload(exchange_count_slot) if iszero(lt(exchange_id, exchange_count)) { REVERT(1) } let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_0 := sload(exchange_ptr) let exchange_1 := sload(add(exchange_ptr, 1)) let exchange_2 := sload(add(exchange_ptr, 2)) let exchange_3 := sload(add(exchange_ptr, 3)) MSTORE_STR(return_value_mem, WORD_6, 11, exchange_0) RETURN(WORD_1, attr(Exchange, 0, exchange_0, locked)) RETURN(WORD_2, attr(Exchange, 0, exchange_0, owner)) RETURN(WORD_3, attr(Exchange, 1, exchange_1, withdraw_address)) RETURN(WORD_4, attr(Exchange, 2, exchange_2, recovery_address)) RETURN(WORD_5, attr(Exchange, 3, exchange_3, recovery_address_proposed)) return(return_value_mem, const_add(WORD_6, /* string header */ WORD_1, /* string data */ 12)) } } function get_exchange_balance(uint32 exchange_id, uint32 asset_id) public view returns (uint256 exchange_balance) { uint256[1] memory return_value_mem; assembly { let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(exchange_ptr, asset_id) RETURN_0(sload(exchange_balance_ptr)) return(return_value_mem, WORD_1) } } function get_exchange_count() public view returns (uint32 count) { uint256[1] memory return_value_mem; assembly { RETURN_0(sload(exchange_count_slot)) return(return_value_mem, WORD_1) } } function get_asset_count() public view returns (uint32 count) { uint256[1] memory return_value_mem; assembly { RETURN_0(sload(asset_count_slot)) return(return_value_mem, WORD_1) } } function get_user_count() public view returns (uint32 count) { uint256[1] memory return_value_mem; assembly { RETURN_0(sload(user_count_slot)) return(return_value_mem, WORD_1) } } function get_user(uint64 user_id) public view returns ( address trade_address, address withdraw_address, address recovery_address, address recovery_address_proposed ) { uint256[4] memory return_value_mem; assembly { let user_count := sload(user_count_slot) if iszero(lt(user_id, user_count)) { REVERT(1) } let user_ptr := USER_PTR_(user_id) RETURN_0( sload(pointer_attr(User, user_ptr, trade_address))) RETURN(WORD_1, sload(pointer_attr(User, user_ptr, withdraw_address))) RETURN(WORD_2, sload(pointer_attr(User, user_ptr, recovery_address))) RETURN(WORD_3, sload(pointer_attr(User, user_ptr, recovery_address_proposed))) return(return_value_mem, WORD_4) } } function get_balance(uint64 user_id, uint32 asset_id) public view returns (uint256 return_balance) { uint256[1] memory return_value_mem; assembly { let user_ptr := USER_PTR_(user_id) let user_balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id) RETURN_0(sload(user_balance_ptr)) return(return_value_mem, WORD_1) } } function get_session(uint64 user_id, uint32 exchange_id) public view returns (uint256 unlock_at, address trade_address) { uint256[2] memory return_value_mem; assembly { let user_ptr := USER_PTR_(user_id) let session_ptr := SESSION_PTR_(user_ptr, exchange_id) RETURN_0(sload(pointer_attr(ExchangeSession, session_ptr, unlock_at))) RETURN(WORD_1, sload(pointer_attr(ExchangeSession, session_ptr, trade_address))) return(return_value_mem, WORD_2) } } function get_session_balance(uint64 user_id, uint32 exchange_id, uint32 asset_id) public view returns (uint128 total_deposit, uint64 unsettled_withdraw_total, uint64 asset_balance) { uint256[3] memory return_value_mem; assembly { let user_ptr := USER_PTR_(user_id) let session_ptr := SESSION_PTR_(user_ptr, exchange_id) let session_balance_ptr := SESSION_BALANCE_PTR_(session_ptr, asset_id) let session_balance_0 := sload(session_balance_ptr) RETURN_0(attr(SessionBalance, 0, session_balance_0, total_deposit)) RETURN(WORD_1, attr(SessionBalance, 0, session_balance_0, unsettled_withdraw_total)) RETURN(WORD_2, attr(SessionBalance, 0, session_balance_0, asset_balance)) return(return_value_mem, WORD_3) } } function get_market_state( uint64 user_id, uint32 exchange_id, uint32 quote_asset_id, uint32 base_asset_id ) public view returns ( int64 quote_qty, int64 base_qty, uint64 fee_used, uint64 fee_limit, int64 min_quote_qty, int64 min_base_qty, uint64 long_max_price, uint64 short_min_price, uint64 limit_version, int96 quote_shift, int96 base_shift ) { uint256[11] memory return_value_mem; assembly { /* hack to get around stack depth issues in Solidity */ base_shift := base_asset_id quote_shift := quote_asset_id let user_ptr := USER_PTR_(user_id) let exchange_session_ptr := SESSION_PTR_(user_ptr, exchange_id) let exchange_state_ptr := MARKET_STATE_PTR_(exchange_session_ptr, quote_shift, base_shift) let state_data_0 := sload(exchange_state_ptr) let state_data_1 := sload(add(exchange_state_ptr, 1)) let state_data_2 := sload(add(exchange_state_ptr, 2)) #define RETURN_64NEG(WORD, VALUE) \ { \ let tmp := VALUE \ CAST_64_NEG(tmp) \ RETURN(WORD, tmp) \ } #define RETURN_96NEG(WORD, VALUE) \ { \ let tmp := VALUE \ CAST_96_NEG(tmp) \ RETURN(WORD, tmp) \ } RETURN_64NEG(WORD_0, attr(MarketState, 0, state_data_0, quote_qty)) RETURN_64NEG(WORD_1, attr(MarketState, 0, state_data_0, base_qty)) RETURN(WORD_2, attr(MarketState, 0, state_data_0, fee_used)) RETURN(WORD_3, attr(MarketState, 0, state_data_0, fee_limit)) RETURN_64NEG(WORD_4, attr(MarketState, 1, state_data_1, min_quote_qty)) RETURN_64NEG(WORD_5, attr(MarketState, 1, state_data_1, min_base_qty)) RETURN(WORD_6, attr(MarketState, 1, state_data_1, long_max_price)) RETURN(WORD_7, attr(MarketState, 1, state_data_1, short_min_price)) RETURN(WORD_8, attr(MarketState, 2, state_data_2, limit_version)) RETURN_96NEG(WORD_9, attr(MarketState, 2, state_data_2, quote_shift)) RETURN_96NEG(WORD_10, attr(MarketState, 2, state_data_2, base_shift)) return(return_value_mem, WORD_11) } } #define CREATOR_REQUIRED(REVERT_1) \ { \ let creator := sload(creator_slot) \ if iszero(eq(caller, creator)) { \ REVERT(REVERT_1) \ } \ } /************************************ * Security Feature Lock Management * * * Taking a defensive approach, these functions allow * the creator to turn off DCN functionality. The intent * is to allow the creator to disable features if an exploit * or logic issue is found. The creator should not be able to * restrict a user's ability to withdraw their assets. * ************************************/ /** * Security Lock * * Sets which features should be locked/disabled. * * @param lock_features: bit flags for each feature to be locked */ function security_lock(uint256 lock_features) public { assembly { CREATOR_REQUIRED(/* REVERT(1) */ 1) let locked_features := sload(security_locked_features_slot) sstore(security_locked_features_slot, or(locked_features, lock_features)) /* * Sets the proposal to block all features. This is done to * ensure security_set_proposed() does not unlock features. */ sstore(security_locked_features_proposed_slot, FEATURE_ALL) } } /** * Security Propose * * Propose which features should be locked. If a feature is unlocked, * should require a timeout before the proposal can be applied. * * @param proposed_locked_features: bit flags for proposal */ function security_propose(uint256 proposed_locked_features) public { assembly { CREATOR_REQUIRED(/* REVERT(1) */ 1) /* * only update security_proposed_unlock_timestamp if * proposed_locked_features unlocks a new features */ /* * Example: current_proposal = 0b11111111 * proposed_features = 0b00010000 * differences = XOR = 0b11101111 */ let current_proposal := sload(security_locked_features_proposed_slot) let proposed_differences := xor(current_proposal, proposed_locked_features) /* * proposed_differences will have "1" in feature positions that have changed. * Want to see if those positions have proposed_locked_features as "0", meaning * that those features will be unlocked. */ let does_unlocks_features := and(proposed_differences, not(proposed_locked_features)) /* update unlock_timestamp */ if does_unlocks_features { sstore(security_proposed_unlock_timestamp_slot, add(timestamp, TWO_DAYS)) } sstore(security_locked_features_proposed_slot, proposed_locked_features) } } /** Security Set Proposed * * Applies the proposed security locks if the timestamp is met. */ function security_set_proposed() public { assembly { CREATOR_REQUIRED(/* REVERT(1) */ 1) let unlock_timestamp := sload(security_proposed_unlock_timestamp_slot) if gt(unlock_timestamp, timestamp) { REVERT(2) } sstore(security_locked_features_slot, sload(security_locked_features_proposed_slot)) } } /********************** * Creator Management * * * Allows creator to update keys * * creator_update * caller = recovery address * updates primary address * creator_propose_recovery * caller = recovery address * sets proposed recovery address * creator_set_recovery * caller = proposed recovery address * sets recovery from proposed * * Recovery update is done in these steps to ensure * value is set to valid address. * **********************/ function creator_update(address new_creator) public { assembly { let creator_recovery := sload(creator_recovery_slot) if iszero(eq(caller, creator_recovery)) { REVERT(1) } sstore(creator_slot, new_creator) } } function creator_propose_recovery(address recovery) public { assembly { let creator_recovery := sload(creator_recovery_slot) if iszero(eq(caller, creator_recovery)) { REVERT(1) } sstore(creator_recovery_proposed_slot, recovery) } } function creator_set_recovery() public { assembly { let creator_recovery_proposed := sload(creator_recovery_proposed_slot) if or(iszero(eq(caller, creator_recovery_proposed)), iszero(caller)) { REVERT(1) } sstore(creator_recovery_slot, caller) sstore(creator_recovery_proposed_slot, 0) } } /** * Set Exchange Locked * * Allows the creator to lock bad acting exchanges. * * @param exchange_id * @param locked: the desired locked state */ function set_exchange_locked(uint32 exchange_id, bool locked) public { assembly { CREATOR_REQUIRED(/* REVERT(1) */ 1) VALID_EXCHANGE_ID(exchange_id, /* REVERT(2) */ 2) let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_0 := sload(exchange_ptr) sstore(exchange_ptr, or( and(mask_out(Exchange, 0, locked), exchange_0), build(Exchange, 0, /* name */ 0, /* locked */ locked) )) } } /** * User Create * * Unrestricted function to create a new user. An event is * emitted to determine the user_id. */ function user_create() public returns (uint64 user_id) { uint256[2] memory log_data_mem; assembly { SECURITY_FEATURE_CHECK(FEATURE_CREATE_USER, /* REVERT(0) */ 0) user_id := sload(user_count_slot) if iszero(lt(user_id, USER_COUNT)) { REVERT(1) } /* increase user count */ sstore(user_count_slot, add(user_id, 1)) /* set management addresses */ let user_ptr := USER_PTR_(user_id) sstore(pointer_attr(User, user_ptr, trade_address), caller) sstore(pointer_attr(User, user_ptr, withdraw_address), caller) sstore(pointer_attr(User, user_ptr, recovery_address), caller) log_event(UserCreated, log_data_mem, caller, user_id) } } /******************* * User Management * * * user_set_trade_address * caller = recovery_address * update user's trade address * user_set_withdraw_address * caller = recovery_address * update user's withdraw address * user_propose_recovery_address * caller = recovery_address * propose recovery address * user_set_recovery_address * caller = recovery_address_proposed * set recovery adress from proposed * *******************/ function user_set_trade_address(uint64 user_id, address trade_address) public { uint256[1] memory log_data_mem; assembly { let user_ptr := USER_PTR_(user_id) let recovery_address := sload(pointer_attr(User, user_ptr, recovery_address)) if iszero(eq(caller, recovery_address)) { REVERT(1) } sstore(pointer_attr(User, user_ptr, trade_address), trade_address) log_event(UserTradeAddressUpdated, log_data_mem, user_id) } } function user_set_withdraw_address(uint64 user_id, address withdraw_address) public { assembly { let user_ptr := USER_PTR_(user_id) let recovery_address := sload(pointer_attr(User, user_ptr, recovery_address)) if iszero(eq(caller, recovery_address)) { REVERT(1) } sstore(pointer_attr(User, user_ptr, withdraw_address), withdraw_address) } } function user_propose_recovery_address(uint64 user_id, address proposed) public { assembly { let user_ptr := USER_PTR_(user_id) let recovery_address := sload(pointer_attr(User, user_ptr, recovery_address)) if iszero(eq(caller, recovery_address)) { REVERT(1) } sstore(pointer_attr(User, user_ptr, recovery_address_proposed), proposed) } } function user_set_recovery_address(uint64 user_id) public { assembly { let user_ptr := USER_PTR_(user_id) let proposed_ptr := pointer_attr(User, user_ptr, recovery_address_proposed) let recovery_address_proposed := sload(proposed_ptr) if iszero(eq(caller, recovery_address_proposed)) { REVERT(1) } sstore(proposed_ptr, 0) sstore(pointer_attr(User, user_ptr, recovery_address), recovery_address_proposed) } } /*********************** * Exchange Management * * * exchange_set_owner * caller = recovery_address * set primary address * exchange_set_withdraw * caller = recovery_address * set withdraw address * exchange_propose_recovery * caller = recovery_address * set propose recovery address * exchange_set_recovery * caller = recovery_address_proposed * set recovery_address from proposed * ***********************/ function exchange_set_owner(uint32 exchange_id, address new_owner) public { assembly { let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_recovery := sload(pointer_attr(Exchange, exchange_ptr, recovery_address)) /* ensure caller is recovery */ if iszero(eq(caller, exchange_recovery)) { REVERT(1) } let exchange_0 := sload(exchange_ptr) sstore(exchange_ptr, or( and(exchange_0, mask_out(Exchange, 0, owner)), build(Exchange, 0, /* name */ 0, /* locked */ 0, /* owner */ new_owner ) )) } } function exchange_set_withdraw(uint32 exchange_id, address new_withdraw) public { assembly { let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_recovery := sload(pointer_attr(Exchange, exchange_ptr, recovery_address)) /* ensure caller is recovery */ if iszero(eq(caller, exchange_recovery)) { REVERT(1) } sstore(pointer_attr(Exchange, exchange_ptr, withdraw_address), new_withdraw) } } function exchange_propose_recovery(uint32 exchange_id, address proposed) public { assembly { let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_recovery := sload(pointer_attr(Exchange, exchange_ptr, recovery_address)) /* ensure caller is proposed */ if iszero(eq(caller, exchange_recovery)) { REVERT(1) } /* update proposed */ sstore(pointer_attr(Exchange, exchange_ptr, recovery_address_proposed), proposed) } } function exchange_set_recovery(uint32 exchange_id) public { assembly { let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_recovery_proposed := sload(pointer_attr(Exchange, exchange_ptr, recovery_address_proposed)) /* ensure caller is proposed recovery */ if or(iszero(eq(caller, exchange_recovery_proposed)), iszero(caller)) { REVERT(1) } /* update recovery */ sstore(pointer_attr(Exchange, exchange_ptr, recovery_address), caller) } } /** * Add Asset * * caller = creator * Note, it is possible for two assets to have the same contract_address. * * @param symbol: 4 character symbol for asset * @param unit_scale: (ERC20 balance) = unit_scale * (session balance) * @param contract_address: address on the ERC20 token */ function add_asset(string memory symbol, uint192 unit_scale, address contract_address) public returns (uint64 asset_id) { assembly { SECURITY_FEATURE_CHECK(FEATURE_ADD_ASSET, /* REVERT(0) */ 0) CREATOR_REQUIRED(/* REVERT(1) */ 1) /* do not want to overflow assets array */ asset_id := sload(asset_count_slot) if iszero(lt(asset_id, ASSET_COUNT)) { REVERT(2) } /* Symbol must be 8 characters */ let symbol_len := mload(symbol) if iszero(eq(symbol_len, 8)) { REVERT(3) } /* Unit scale must be non-zero */ if iszero(unit_scale) { REVERT(4) } /* Contract address should be non-zero */ if iszero(contract_address) { REVERT(5) } let asset_symbol := mload(add(symbol, WORD_1 /* offset as first word is size */)) /* Note, symbol is already shifted not setting it in build */ let asset_data_0 := or(asset_symbol, build(Asset, 0, /* symbol */ 0, unit_scale)) let asset_ptr := ASSET_PTR_(asset_id) sstore(asset_ptr, asset_data_0) sstore(add(asset_ptr, 1), contract_address) sstore(asset_count_slot, add(asset_id, 1)) } } /** * Add Exchange * * caller = creator * * @param name: 11 character name of exchange * @param addr: address of exchange */ function add_exchange(string memory name, address addr) public returns (uint64 exchange_id) { assembly { SECURITY_FEATURE_CHECK(FEATURE_ADD_EXCHANGE, /* REVERT(0) */ 0) CREATOR_REQUIRED(/* REVERT(1) */ 1) /* Name must be 11 bytes long */ let name_len := mload(name) if iszero(eq(name_len, 11)) { REVERT(2) } /* Do not overflow exchanges */ exchange_id := sload(exchange_count_slot) if iszero(lt(exchange_id, EXCHANGE_COUNT)) { REVERT(3) } let exchange_ptr := EXCHANGE_PTR_(exchange_id) /* * name is at start of the word. After loading it is already shifted * so add to it rather than shifting twice with build */ let name_data := mload(add(name, WORD_1 /* shift, first word is length */)) let exchange_0 := or( name_data, build(Exchange, 0, /* space for name */ 0, /* locked */ 0, /* owner */ addr) ) sstore(exchange_ptr, exchange_0) /* Store owner withdraw */ sstore(pointer_attr(Exchange, exchange_ptr, withdraw_address), addr) /* Store owner recovery */ sstore(pointer_attr(Exchange, exchange_ptr, recovery_address), addr) /* Update exchange count */ sstore(exchange_count_slot, add(exchange_id, 1)) } } /** * Exchange Withdraw * * @param quantity: in session balance units */ function exchange_withdraw(uint32 exchange_id, uint32 asset_id, address destination, uint64 quantity) public { uint256[3] memory transfer_in_mem; uint256[1] memory transfer_out_mem; assembly { let exchange_ptr := EXCHANGE_PTR_(exchange_id) /* ensure caller is withdraw_address */ let withdraw_address := sload(pointer_attr(Exchange, exchange_ptr, withdraw_address)) if iszero(eq(caller, withdraw_address)) { REVERT(1) } let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(exchange_ptr, asset_id) let exchange_balance := sload(exchange_balance_ptr) /* insufficient funds */ if gt(quantity, exchange_balance) { REVERT(2) } /* decrement balance */ sstore(exchange_balance_ptr, sub(exchange_balance, quantity)) let asset_ptr := ASSET_PTR_(asset_id) let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale) let asset_address := sload(pointer_attr(Asset, asset_ptr, contract_address)) let withdraw := mul(quantity, unit_scale) ERC_20_SEND( /* TOKEN_ADDRESS */ asset_address, /* TO_ADDRESS */ destination, /* AMOUNT */ withdraw, /* REVERT(3) */ 3, /* REVERT(4) */ 4 ) } } /** * Exchange Deposit * * @param quantity: in session balance units */ function exchange_deposit(uint32 exchange_id, uint32 asset_id, uint64 quantity) public { uint256[3] memory transfer_in_mem; uint256[1] memory transfer_out_mem; assembly { SECURITY_FEATURE_CHECK(FEATURE_EXCHANGE_DEPOSIT, /* REVERT(0) */ 0) VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1) VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2) let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(EXCHANGE_PTR_(exchange_id), asset_id) let exchange_balance := sload(exchange_balance_ptr) let updated_balance := add(exchange_balance, quantity) if U64_OVERFLOW(updated_balance) { REVERT(3) } let asset_ptr := ASSET_PTR_(asset_id) let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale) let asset_address := sload(pointer_attr(Asset, asset_ptr, contract_address)) let deposit := mul(quantity, unit_scale) sstore(exchange_balance_ptr, updated_balance) ERC_20_DEPOSIT( /* TOKEN_ADDRESS */ asset_address, /* FROM_ADDRESS */ caller, /* TO_ADDRESS */ address, /* AMOUNT */ deposit, /* REVERT(4) */ 4, /* REVERT(5) */ 5 ) } } /** * User Deposit * * Deposit funds in the user's DCN balance * * @param amount: in ERC20 balance units */ function user_deposit(uint64 user_id, uint32 asset_id, uint256 amount) public { uint256[4] memory transfer_in_mem; uint256[1] memory transfer_out_mem; assembly { SECURITY_FEATURE_CHECK(FEATURE_USER_DEPOSIT, /* REVERT(0) */ 0) VALID_USER_ID(user_id, /* REVERT(1) */ 1) VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2) if iszero(amount) { stop() } let balance_ptr := USER_BALANCE_PTR_(USER_PTR_(user_id), asset_id) let current_balance := sload(balance_ptr) let proposed_balance := add(current_balance, amount) /* Prevent overflow */ if lt(proposed_balance, current_balance) { REVERT(3) } let asset_address := sload(pointer_attr(Asset, ASSET_PTR_(asset_id), contract_address)) sstore(balance_ptr, proposed_balance) ERC_20_DEPOSIT( /* TOKEN_ADDRESS */ asset_address, /* FROM_ADDRESS */ caller, /* TO_ADDRESS */ address, /* AMOUNT */ amount, /* REVERT(4) */ 4, /* REVERT(5) */ 5 ) } } /** * User Withdraw * * caller = user's withdraw_address * * Withdraw from user's DCN balance * * @param amount: in ERC20 balance units */ function user_withdraw(uint64 user_id, uint32 asset_id, address destination, uint256 amount) public { uint256[3] memory transfer_in_mem; uint256[1] memory transfer_out_mem; assembly { if iszero(amount) { stop() } VALID_USER_ID(user_id, /* REVERT(6) */ 6) VALID_ASSET_ID(asset_id, /* REVERT(1) */ 1) let user_ptr := USER_PTR_(user_id) let withdraw_address := sload(pointer_attr(User, user_ptr, withdraw_address)) if iszero(eq(caller, withdraw_address)) { REVERT(2) } let balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id) let current_balance := sload(balance_ptr) /* insufficient funds */ if lt(current_balance, amount) { REVERT(3) } sstore(balance_ptr, sub(current_balance, amount)) let asset_address := sload(pointer_attr(Asset, ASSET_PTR_(asset_id), contract_address)) ERC_20_SEND( /* TOKEN_ADDRESS */ asset_address, /* TO_ADDRESS */ destination, /* AMOUNT */ amount, /* REVERT(4) */ 4, /* REVERT(5) */ 5 ) } } /** * User Session Set Unlock At * * caller = user's trade_address * * Update the unlock_at timestamp. Also updates the trade_address * if the session is expired. Note, the trade_address should not be * updatable when the session is active. */ function user_session_set_unlock_at(uint64 user_id, uint32 exchange_id, uint256 unlock_at) public { uint256[3] memory log_data_mem; assembly { VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1) let user_ptr := USER_PTR_(user_id) let trade_address := sload(pointer_attr(User, user_ptr, trade_address)) if iszero(eq(caller, trade_address)) { REVERT(2) } /* validate time range of unlock_at */ { let fails_min_time := lt(unlock_at, add(timestamp, MIN_UNLOCK_AT)) let fails_max_time := gt(unlock_at, add(timestamp, MAX_UNLOCK_AT)) if or(fails_min_time, fails_max_time) { REVERT(3) } } let session_ptr := SESSION_PTR_(user_ptr, exchange_id) /* only update trade_address when unlocked */ let unlock_at_ptr := pointer_attr(ExchangeSession, session_ptr, unlock_at) if lt(sload(unlock_at_ptr), timestamp) { sstore(pointer_attr(ExchangeSession, session_ptr, trade_address), caller) } sstore(unlock_at_ptr, unlock_at) log_event(SessionUpdated, log_data_mem, user_id, exchange_id) } } /** * User Market Reset * * caller = user's trade_address * * Allows the user to reset their session with an exchange. * Only allowed when session in unlocked. * Persists limit_version to prevent old limits from being applied. */ function user_market_reset(uint64 user_id, uint32 exchange_id, uint32 quote_asset_id, uint32 base_asset_id) public { assembly { SECURITY_FEATURE_CHECK(FEATURE_USER_MARKET_RESET, /* REVERT(0) */ 0) VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1) let user_ptr := USER_PTR_(user_id) let trade_address := sload(pointer_attr(User, user_ptr, trade_address)) if iszero(eq(caller, trade_address)) { REVERT(2) } let session_ptr := SESSION_PTR_(user_ptr, exchange_id) let unlock_at := sload(pointer_attr(ExchangeSession, session_ptr, unlock_at)) if gt(unlock_at, timestamp) { REVERT(3) } let market_state_ptr := MARKET_STATE_PTR_(session_ptr, quote_asset_id, base_asset_id) sstore(market_state_ptr, 0) sstore(add(market_state_ptr, 1), 0) /* increment limit_version */ let market_state_2_ptr := add(market_state_ptr, 2) let market_state_2 := sload(market_state_2_ptr) let limit_version := add(attr(MarketState, 2, market_state_2, limit_version), 1) sstore(market_state_2_ptr, build(MarketState, 2, /* limit_version */ limit_version )) } } /** * Transfer To Session * * caller = user's withdraw_address * * Transfer funds from DCN balance to trading session * * @param quantity: in session balance units */ function transfer_to_session(uint64 user_id, uint32 exchange_id, uint32 asset_id, uint64 quantity) public { uint256[4] memory log_data_mem; assembly { SECURITY_FEATURE_CHECK(FEATURE_TRANSFER_TO_SESSION, /* REVERT(0) */ 0) VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1) VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2) if iszero(quantity) { stop() } let asset_ptr := ASSET_PTR_(asset_id) let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale) let scaled_quantity := mul(quantity, unit_scale) let user_ptr := USER_PTR_(user_id) /* ensure caller is withdraw_address as funds are moving out of DCN account */ { let withdraw_address := sload(pointer_attr(User, user_ptr, withdraw_address)) if iszero(eq(caller, withdraw_address)) { REVERT(3) } } let user_balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id) let user_balance := sload(user_balance_ptr) /* insufficient funds */ if lt(user_balance, scaled_quantity) { REVERT(4) } /* load exchange balance */ let session_balance_ptr := SESSION_BALANCE_PTR_(SESSION_PTR_(user_ptr, exchange_id), asset_id) let session_balance_0 := sload(session_balance_ptr) let updated_exchange_balance := add(attr(SessionBalance, 0, session_balance_0, asset_balance), quantity) if U64_OVERFLOW(updated_exchange_balance) { REVERT(5) } /* don't care about overflow for total_deposit, is used by exchange to detect update */ let updated_total_deposit := add(attr(SessionBalance, 0, session_balance_0, total_deposit), quantity) /* update user balance */ sstore(user_balance_ptr, sub(user_balance, scaled_quantity)) /* update exchange balance */ sstore(session_balance_ptr, or( and(mask_out(SessionBalance, 0, total_deposit, asset_balance), session_balance_0), build(SessionBalance, 0, /* total_deposit */ updated_total_deposit, /* unsettled_withdraw_total */ 0, /* asset_balance */ updated_exchange_balance) )) log_event(ExchangeDeposit, log_data_mem, user_id, exchange_id, asset_id) } } /** * Transfer From Session * * caller = user's trade_address * * When session is unlocked, allow transfer funds from trading session to DCN balance. * * @param quantity: in session balance units */ function transfer_from_session(uint64 user_id, uint32 exchange_id, uint32 asset_id, uint64 quantity) public { uint256[4] memory log_data_mem; assembly { if iszero(quantity) { stop() } VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1) VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2) let user_ptr := USER_PTR_(user_id) { let trade_address := sload(pointer_attr(User, user_ptr, trade_address)) if iszero(eq(caller, trade_address)) { REVERT(3) } } let session_ptr := SESSION_PTR_(user_ptr, exchange_id) /* ensure session in unlocked */ { let session_0 := sload(session_ptr) let unlock_at := attr(ExchangeSession, 0, session_0, unlock_at) if gt(unlock_at, timestamp) { REVERT(4) } } /* load exchange balance */ let session_balance_ptr := SESSION_BALANCE_PTR_(session_ptr, asset_id) let session_balance_0 := sload(session_balance_ptr) let session_balance := attr(SessionBalance, 0, session_balance_0, asset_balance) /* insufficient funds */ if gt(quantity, session_balance) { REVERT(5) } let updated_exchange_balance := sub(session_balance, quantity) let unsettled_withdraw_total := attr(SessionBalance, 0, session_balance_0, unsettled_withdraw_total) /* do not let user withdraw money owed to the exchange */ if lt(updated_exchange_balance, unsettled_withdraw_total) { REVERT(6) } sstore(session_balance_ptr, or( and(mask_out(SessionBalance, 0, asset_balance), session_balance_0), build(SessionBalance, 0, /* total_deposit */ 0, /* unsettled_withdraw_total */ 0, /* asset_balance */ updated_exchange_balance) )) let asset_ptr := ASSET_PTR_(asset_id) let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale) let scaled_quantity := mul(quantity, unit_scale) let user_balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id) let user_balance := sload(user_balance_ptr) let updated_user_balance := add(user_balance, scaled_quantity) /* protect against addition overflow */ if lt(updated_user_balance, user_balance) { REVERT(7) } sstore(user_balance_ptr, updated_user_balance) } } /** * User Deposit To Session * * Deposits funds directly into a trading session with an exchange. * * @param quantity: in session balance units */ function user_deposit_to_session(uint64 user_id, uint32 exchange_id, uint32 asset_id, uint64 quantity) public { uint256[4] memory transfer_in_mem; uint256[1] memory transfer_out_mem; uint256[3] memory log_data_mem; assembly { SECURITY_FEATURE_CHECK(FEATURE_DEPOSIT_ASSET_TO_SESSION, /* REVERT(0) */ 0) VALID_EXCHANGE_ID(exchange_id, /* REVERT(1) */ 1) VALID_ASSET_ID(asset_id, /* REVERT(2) */ 2) if iszero(quantity) { stop() } let session_balance_ptr := SESSION_BALANCE_PTR_(SESSION_PTR_(USER_PTR_(user_id), exchange_id), asset_id) let session_balance_0 := sload(session_balance_ptr) let updated_exchange_balance := add(attr(SessionBalance, 0, session_balance_0, asset_balance), quantity) if U64_OVERFLOW(updated_exchange_balance) { REVERT(3) } let asset_ptr := ASSET_PTR_(asset_id) let unit_scale := attr(Asset, 0, sload(asset_ptr), unit_scale) let asset_address := sload(pointer_attr(Asset, asset_ptr, contract_address)) let scaled_quantity := mul(quantity, unit_scale) let updated_total_deposit := add(attr(SessionBalance, 0, session_balance_0, total_deposit), quantity) /* update exchange balance */ sstore(session_balance_ptr, or( and(mask_out(SessionBalance, 0, total_deposit, asset_balance), session_balance_0), build(SessionBalance, 0, /* total_deposit */ updated_total_deposit, /* unsettled_withdraw_total */ 0, /* asset_balance */ updated_exchange_balance) )) ERC_20_DEPOSIT( /* TOKEN_ADDRESS */ asset_address, /* FROM_ADDRESS */ caller, /* TO_ADDRESS */ address, /* AMOUNT */ scaled_quantity, /* REVERT(4) */ 4, /* REVERT(5) */ 5 ) log_event(ExchangeDeposit, log_data_mem, user_id, exchange_id, asset_id) } } struct UnsettledWithdrawHeader { uint32 exchange_id; uint32 asset_id; uint32 user_count; } struct UnsettledWithdrawUser { uint64 user_id; } /** * Recover Unsettled Withdraws * * exchange_transfer_from allows users to pull unsettled * funds from the exchange's balance. This is tracked by * unsettled_withdraw_total in SessionBalance. This function * returns funds to the Exchange. * * @param data, a binary payload * - UnsettledWithdrawHeader * - 1st UnsettledWithdrawUser * - 2nd UnsettledWithdrawUser * - ... * - (UnsettledWithdrawHeader.user_count)th UnsettledWithdrawUser */ function recover_unsettled_withdraws(bytes memory data) public { assembly { SECURITY_FEATURE_CHECK(FEATURE_RECOVER_UNSETTLED_WITHDRAWS, /* REVERT(0) */ 0) let data_len := mload(data) let cursor := add(data, WORD_1) let cursor_end := add(cursor, data_len) for {} lt(cursor, cursor_end) {} { let unsettled_withdraw_header_0 := mload(cursor) let exchange_id := attr(UnsettledWithdrawHeader, 0, unsettled_withdraw_header_0, exchange_id) let asset_id := attr(UnsettledWithdrawHeader, 0, unsettled_withdraw_header_0, asset_id) let user_count := attr(UnsettledWithdrawHeader, 0, unsettled_withdraw_header_0, user_count) let group_end := add( cursor, add( sizeof(UnsettledWithdrawHeader), mul(user_count, sizeof(UnsettledWithdrawUser)) )) if gt(group_end, cursor_end) { REVERT(1) } let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(EXCHANGE_PTR_(exchange_id), asset_id) let exchange_balance := sload(exchange_balance_ptr) let start_exchange_balance := exchange_balance for {} lt(cursor, group_end) { cursor := add(cursor, sizeof(UnsettledWithdrawUser)) } { let user_id := attr(UnsettledWithdrawUser, 0, mload(cursor), user_id) let session_balance_ptr := SESSION_BALANCE_PTR_(SESSION_PTR_(USER_PTR_(user_id), exchange_id), asset_id) let session_balance_0 := sload(session_balance_ptr) let asset_balance := attr(SessionBalance, 0, session_balance_0, asset_balance) let unsettled_balance := attr(SessionBalance, 0, session_balance_0, unsettled_withdraw_total) let to_recover := unsettled_balance if gt(to_recover, asset_balance) { to_recover := asset_balance } /* non zero */ if to_recover { exchange_balance := add(exchange_balance, to_recover) asset_balance := sub(asset_balance, to_recover) unsettled_balance := sub(unsettled_balance, to_recover) /* ensure exchange_balance doesn't overflow */ if gt(start_exchange_balance, exchange_balance) { REVERT(2) } sstore(session_balance_ptr, or( and(mask_out(SessionBalance, 0, unsettled_withdraw_total, asset_balance), session_balance_0), build( SessionBalance, 0, /* total_deposit */ 0, /* unsettled_withdraw_total */ unsettled_balance, /* asset_balance */ asset_balance) )) } } sstore(exchange_balance_ptr, exchange_balance) } } } struct ExchangeTransfersHeader { uint32 exchange_id; } struct ExchangeTransferGroup { uint32 asset_id; uint8 allow_overdraft; uint8 transfer_count; } struct ExchangeTransfer { uint64 user_id; uint64 quantity; } #define CURSOR_LOAD(TYPE, REVERT_1) \ mload(cursor) \ cursor := add(cursor, sizeof(TYPE)) \ if gt(cursor, cursor_end) { \ REVERT(REVERT_1) \ } /** * Exchange Transfer From * * caller = exchange owner * * Gives the exchange the ability to move funds from a user's * trading session into the user's DCN balance. This should be * the only way funds can be withdrawn from a trading session * while it is locked. * * Exchange has the option to allow_overdraft. If the user's * balance in the tradng_session is not enough to cover the * target withdraw quantity, the exchange's funds will be used. * These funds can be repaid with a call to recover_unsettled_withdraws. * * @param data, a binary payload * - ExchangeTransfersHeader * - 1st ExchangeTransferGroup * - 1st ExchangeTransfer * - 2nd ExchangeTransfer * - ... * - (ExchangeTransferGroup.transfer_count)th ExchangeTransfer * - 2nd ExchangeTransferGroup * - 1st ExchangeTransfer * - 2nd ExchangeTransfer * - ... * - (ExchangeTransferGroup.transfer_count)th ExchangeTransfer * - ... */ function exchange_transfer_from(bytes memory data) public { assembly { SECURITY_FEATURE_CHECK(FEATURE_EXCHANGE_TRANSFER_FROM, /* REVERT(0) */ 0) let data_len := mload(data) let cursor := add(data, WORD_1) let cursor_end := add(cursor, data_len) /* load exchange_id */ let header_0 := CURSOR_LOAD(ExchangeTransfersHeader, /* REVERT(1) */ 1) let exchange_id := attr(ExchangeTransfersHeader, 0, header_0, exchange_id) VALID_EXCHANGE_ID(exchange_id, /* REVERT(2) */ 2) { /* ensure exchange is caller */ let exchange_data := sload(EXCHANGE_PTR_(exchange_id)) if iszero(eq(caller, attr(Exchange, 0, exchange_data, owner))) { REVERT(3) } /* ensure exchange is not locked */ if attr(Exchange, 0, exchange_data, locked) { REVERT(4) } } let asset_count := sload(asset_count_slot) for {} lt(cursor, cursor_end) {} { let group_0 := CURSOR_LOAD(ExchangeTransferGroup, /* REVERT(5) */ 5) let asset_id := attr(ExchangeTransferGroup, 0, group_0, asset_id) /* Validate asset id */ if iszero(lt(asset_id, asset_count)) { REVERT(6) } let disallow_overdraft := iszero(attr(ExchangeTransferGroup, 0, group_0, allow_overdraft)) let cursor_group_end := add(cursor, mul( attr(ExchangeTransferGroup, 0, group_0, transfer_count), sizeof(ExchangeTransfer) )) /* ensure data fits in input */ if gt(cursor_group_end, cursor_end) { REVERT(7) } let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(EXCHANGE_PTR_(exchange_id), asset_id) let exchange_balance_remaining := sload(exchange_balance_ptr) let unit_scale := attr(Asset, 0, sload(ASSET_PTR_(asset_id)), unit_scale) for {} lt(cursor, cursor_group_end) { cursor := add(cursor, sizeof(ExchangeTransfer)) } { let transfer_0 := mload(cursor) let user_ptr := USER_PTR_(attr(ExchangeTransfer, 0, transfer_0, user_id)) let quantity := attr(ExchangeTransfer, 0, transfer_0, quantity) let exchange_balance_used := 0 let session_balance_ptr := SESSION_BALANCE_PTR_(SESSION_PTR_(user_ptr, exchange_id), asset_id) let session_balance_0 := sload(session_balance_ptr) let session_balance := attr(SessionBalance, 0, session_balance_0, asset_balance) let session_balance_updated := sub(session_balance, quantity) /* * check for underflow (quantity > user_exchange_balance), * then need to dip into exchange_balance_remaining if user_exchange_balance isn't enough */ if gt(session_balance_updated, session_balance) { if disallow_overdraft { REVERT(8) } exchange_balance_used := sub(quantity, session_balance) session_balance_updated := 0 if gt(exchange_balance_used, exchange_balance_remaining) { REVERT(9) } exchange_balance_remaining := sub(exchange_balance_remaining, exchange_balance_used) } let quantity_scaled := mul(quantity, unit_scale) let user_balance_ptr := USER_BALANCE_PTR_(user_ptr, asset_id) let user_balance := sload(user_balance_ptr) let updated_user_balance := add(user_balance, quantity_scaled) /* prevent overflow */ if gt(user_balance, updated_user_balance) { REVERT(10) } let unsettled_withdraw_total_updated := add( attr(SessionBalance, 0, session_balance_0, unsettled_withdraw_total), exchange_balance_used ) /* prevent overflow */ if gt(unsettled_withdraw_total_updated, U64_MAX) { REVERT(11) } sstore(session_balance_ptr, or( and(mask_out(SessionBalance, 0, unsettled_withdraw_total, asset_balance), session_balance_0), build(SessionBalance, 0, /* total_deposit */ 0, /* unsettled_withdraw_total */ unsettled_withdraw_total_updated, /* asset_balance */ session_balance_updated) )) sstore(user_balance_ptr, updated_user_balance) } sstore(exchange_balance_ptr, exchange_balance_remaining) } } } struct SetLimitsHeader { uint32 exchange_id; } struct Signature { uint256 sig_r; uint256 sig_s; uint8 sig_v; } struct UpdateLimit { uint32 dcn_id; uint64 user_id; uint32 exchange_id; uint32 quote_asset_id; uint32 base_asset_id; uint64 fee_limit; int64 min_quote_qty; int64 min_base_qty; uint64 long_max_price; uint64 short_min_price; uint64 limit_version; uint96 quote_shift; uint96 base_shift; } #define UPDATE_LIMIT_BYTES const_add(sizeof(UpdateLimit), sizeof(Signature)) #define SIG_HASH_HEADER 0x1901000000000000000000000000000000000000000000000000000000000000 #define DCN_HEADER_HASH 0x6c1a0baa584339032b4ed0d2fdb53c23d290c0b8a7da5a9e05ce919faa986a59 #define UPDATE_LIMIT_TYPE_HASH 0xbe6b685e53075dd48bdabc4949b848400d5a7e53705df48e04ace664c3946ad2 struct SetLimitMemory { uint256 user_id; uint256 exchange_id; uint256 quote_asset_id; uint256 base_asset_id; uint256 limit_version; uint256 quote_shift; uint256 base_shift; } /** * Exchange Set Limits * * caller = exchange owner * * Update trading limits for an exchange's session. Requires * - proper signature * - exchange_id is for exchange * - limit_version is an increase (prevents replays) * * @param data, a binary payload * - SetLimitsHeader * - 1st Signature + UpdateLimit * - 2nd Signature + UpdateLimit * - ... */ function exchange_set_limits(bytes memory data) public { uint256[14] memory to_hash_mem; uint256 cursor; uint256 cursor_end; uint256 exchange_id; uint256[sizeof(SetLimitMemory)] memory set_limit_memory_space; #define MEM_PTR(KEY) \ add(set_limit_memory_space, byte_offset(SetLimitMemory, KEY)) #define SAVE_MEM(KEY, VALUE) \ mstore(MEM_PTR(KEY), VALUE) #define LOAD_MEM(KEY) \ mload(MEM_PTR(KEY)) /* * Ensure caller is exchange and setup cursors. */ assembly { SECURITY_FEATURE_CHECK(FEATURE_EXCHANGE_SET_LIMITS, /* REVERT(0) */ 0) let data_size := mload(data) cursor := add(data, WORD_1) cursor_end := add(cursor, data_size) let set_limits_header_0 := CURSOR_LOAD(SetLimitsHeader, /* REVERT(1) */ 1) exchange_id := attr(SetLimitsHeader, 0, set_limits_header_0, exchange_id) let exchange_0 := sload(EXCHANGE_PTR_(exchange_id)) let exchange_owner := attr(Exchange, 0, exchange_0, owner) /* ensure caller is the exchange owner */ if iszero(eq(caller, exchange_owner)) { REVERT(2) } /* ensure exchange is not locked */ if attr(Exchange, 0, exchange_0, locked) { REVERT(3) } } /* * Iterate through each limit to validate and apply */ while (true) { uint256 update_limit_0; uint256 update_limit_1; uint256 update_limit_2; bytes32 limit_hash; /* hash limit, and extract variables */ assembly { /* Reached the end */ if eq(cursor, cursor_end) { return(0, 0) } update_limit_0 := mload(cursor) update_limit_1 := mload(add(cursor, WORD_1)) update_limit_2 := mload(add(cursor, WORD_2)) cursor := add(cursor, sizeof(UpdateLimit)) if gt(cursor, cursor_end) { REVERT(4) } /* macro to make life easier */ #define ATTR_GET(INDEX, ATTR_NAME) \ attr(UpdateLimit, INDEX, update_limit_##INDEX, ATTR_NAME) #define BUF_PUT(WORD, INDEX, ATTR_NAME) \ temp_var := ATTR_GET(INDEX, ATTR_NAME) \ mstore(add(to_hash_mem, WORD), temp_var) #define BUF_PUT_I64(WORD, INDEX, ATTR_NAME) \ temp_var := ATTR_GET(INDEX, ATTR_NAME) \ CAST_64_NEG(temp_var) \ mstore(add(to_hash_mem, WORD), temp_var) #define BUF_PUT_I96(WORD, INDEX, ATTR_NAME) \ temp_var := ATTR_GET(INDEX, ATTR_NAME) \ CAST_96_NEG(temp_var) \ mstore(add(to_hash_mem, WORD), temp_var) #define SAVE(VAR_NAME) \ SAVE_MEM(VAR_NAME, temp_var) #define LOAD(VAR_NAME) \ LOAD_MEM(VAR_NAME) /* store data to hash */ { mstore(to_hash_mem, UPDATE_LIMIT_TYPE_HASH) let temp_var := 0 BUF_PUT(WORD_1, 0, dcn_id) BUF_PUT(WORD_2, 0, user_id) SAVE(user_id) BUF_PUT(WORD_3, 0, exchange_id) BUF_PUT(WORD_4, 0, quote_asset_id) SAVE(quote_asset_id) BUF_PUT(WORD_5, 0, base_asset_id) SAVE(base_asset_id) BUF_PUT(WORD_6, 0, fee_limit) BUF_PUT_I64(WORD_7, 1, min_quote_qty) BUF_PUT_I64(WORD_8, 1, min_base_qty) BUF_PUT(WORD_9, 1, long_max_price) BUF_PUT(WORD_10, 1, short_min_price) BUF_PUT(WORD_11, 2, limit_version) SAVE(limit_version) BUF_PUT_I96(WORD_12, 2, quote_shift) SAVE(quote_shift) BUF_PUT_I96(WORD_13, 2, base_shift) SAVE(base_shift) } limit_hash := keccak256(to_hash_mem, WORD_14) mstore(to_hash_mem, SIG_HASH_HEADER) mstore(add(to_hash_mem, 2), DCN_HEADER_HASH) mstore(add(to_hash_mem, const_add(WORD_1, 2)), limit_hash) limit_hash := keccak256(to_hash_mem, const_add(WORD_2, 2)) } /* verify signature */ { bytes32 sig_r; bytes32 sig_s; uint8 sig_v; /* Load signature data */ assembly { sig_r := attr(Signature, 0, mload(cursor), sig_r) sig_s := attr(Signature, 1, mload(add(cursor, WORD_1)), sig_s) sig_v := attr(Signature, 2, mload(add(cursor, WORD_2)), sig_v) cursor := add(cursor, sizeof(Signature)) if gt(cursor, cursor_end) { REVERT(5) } } uint256 recovered_address = uint256(ecrecover( /* hash */ limit_hash, /* v */ sig_v, /* r */ sig_r, /* s */ sig_s )); assembly { let user_ptr := USER_PTR_(LOAD(user_id)) let session_ptr := SESSION_PTR_(user_ptr, exchange_id) let trade_address := sload(pointer_attr(ExchangeSession, session_ptr, trade_address)) if iszero(eq(recovered_address, trade_address)) { REVERT(6) } } } /* validate and apply new limit */ assembly { /* limit's exchange id should match */ { if iszero(eq(LOAD(exchange_id), exchange_id)) { REVERT(7) } } let user_ptr := USER_PTR_(LOAD(user_id)) let session_ptr := SESSION_PTR_(user_ptr, exchange_id) let market_state_ptr := MARKET_STATE_PTR_( session_ptr, LOAD(quote_asset_id), LOAD(base_asset_id) ) let market_state_0 := sload(market_state_ptr) let market_state_1 := sload(add(market_state_ptr, 1)) let market_state_2 := sload(add(market_state_ptr, 2)) /* verify limit version is greater */ { let current_limit_version := attr(MarketState, 2, market_state_2, limit_version) if iszero(gt(LOAD(limit_version), current_limit_version)) { REVERT(8) } } let quote_qty := attr(MarketState, 0, market_state_0, quote_qty) CAST_64_NEG(quote_qty) let base_qty := attr(MarketState, 0, market_state_0, base_qty) CAST_64_NEG(base_qty) #define APPLY_SHIFT(SIDE, REVERT_1) \ { \ let current_shift := attr(MarketState, 2, market_state_2, SIDE##_shift) \ CAST_96_NEG(current_shift) \ \ let new_shift := LOAD(SIDE##_shift) \ \ SIDE##_qty := add(SIDE##_qty, sub(new_shift, current_shift)) \ if INVALID_I64(SIDE##_qty) { \ REVERT(REVERT_1) \ } \ } APPLY_SHIFT(quote, /* REVERT(9) */ 9) APPLY_SHIFT(base, /* REVERT(10) */ 10) let new_market_state_0 := or( build_with_mask( MarketState, 0, /* quote_qty */ quote_qty, /* base_qty */ base_qty, /* fee_used */ 0, /* fee_limit */ update_limit_0), and(mask_out(MarketState, 0, quote_qty, base_qty, fee_limit), market_state_0) /* extract fee_used */ ) sstore(market_state_ptr, new_market_state_0) sstore(add(market_state_ptr, 1), update_limit_1) sstore(add(market_state_ptr, 2), update_limit_2) } } } struct ExchangeId { uint32 exchange_id; } struct GroupHeader { uint32 quote_asset_id; uint32 base_asset_id; uint8 user_count; } struct Settlement { uint64 user_id; int64 quote_delta; int64 base_delta; uint64 fees; } /** * Exchange Apply Settlement Groups * * caller = exchange owner * * Apply quote & base delta to session balances. Deltas must net to zero * to ensure no funds are created or destroyed. Session's balance should * only apply if the net result fits within the session's trading limit. * * @param data, a binary payload * - ExchangeId * - 1st GroupHeader * - 1st Settlement * - 2nd Settlement * - ... * - (GroupHeader.user_count)th Settlement * - 2nd GroupHeader * - 1st Settlement * - 2nd Settlement * - ... * - (GroupHeader.user_count)th Settlement * - ... */ function exchange_apply_settlement_groups(bytes memory data) public { uint256[6] memory variables; assembly { /* Check security lock */ SECURITY_FEATURE_CHECK(FEATURE_APPLY_SETTLEMENT_GROUPS, /* REVERT(0) */ 0) let data_len := mload(data) let cursor := add(data, WORD_1) let cursor_end := add(cursor, data_len) let exchange_id_0 := CURSOR_LOAD(ExchangeId, /* REVERT(1) */ 1) let exchange_id := attr(ExchangeId, 0, exchange_id_0, exchange_id) VALID_EXCHANGE_ID(exchange_id, 2) { let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_0 := sload(exchange_ptr) /* caller must be exchange owner */ if iszero(eq(caller, attr(Exchange, 0, exchange_0, owner))) { REVERT(2) } /* exchange must not be locked */ if attr(Exchange, 0, exchange_0, locked) { REVERT(3) } } /* keep looping while there is space for a GroupHeader */ for {} lt(cursor, cursor_end) {} { let header_0 := CURSOR_LOAD(GroupHeader, /* REVERT(4) */ 4) let quote_asset_id := attr(GroupHeader, 0, header_0, quote_asset_id) let base_asset_id := attr(GroupHeader, 0, header_0, base_asset_id) if eq(quote_asset_id, base_asset_id) { REVERT(16) } let group_end := add(cursor, mul( attr(GroupHeader, 0, header_0 /* GroupHeader */, user_count), sizeof(Settlement) )) /* validate quote_asset_id and base_asset_id */ { let asset_count := sload(asset_count_slot) if iszero(and(lt(quote_asset_id, asset_count), lt(base_asset_id, asset_count))) { REVERT(5) } } /* ensure there is enough space for the settlement group */ if gt(group_end, cursor_end) { REVERT(6) } let quote_net := 0 let base_net := 0 let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_balance_ptr := EXCHANGE_BALANCE_PTR_(exchange_ptr, quote_asset_id) let exchange_balance := sload(exchange_balance_ptr) /* loop through each settlement */ for {} lt(cursor, group_end) { cursor := add(cursor, sizeof(Settlement)) } { let settlement_0 := mload(cursor) let user_ptr := USER_PTR_(attr(Settlement, 0, settlement_0, user_id)) /* Stage user's quote/base/fee update and test against limit */ let session_ptr := SESSION_PTR_(user_ptr, exchange_id) let market_state_ptr := MARKET_STATE_PTR_( session_ptr, quote_asset_id, base_asset_id ) let quote_delta := attr(Settlement, 0, settlement_0, quote_delta) CAST_64_NEG(quote_delta) let base_delta := attr(Settlement, 0, settlement_0, base_delta) CAST_64_NEG(base_delta) quote_net := add(quote_net, quote_delta) base_net := add(base_net, base_delta) let fees := attr(Settlement, 0, settlement_0, fees) exchange_balance := add(exchange_balance, fees) let market_state_0 := sload(market_state_ptr) /* Validate Limit */ { let quote_qty := attr(MarketState, 0, market_state_0, quote_qty) CAST_64_NEG(quote_qty) let base_qty := attr(MarketState, 0, market_state_0, base_qty) CAST_64_NEG(base_qty) quote_qty := add(quote_qty, quote_delta) base_qty := add(base_qty, base_delta) if or(INVALID_I64(quote_qty), INVALID_I64(base_qty)) { REVERT(7) } let fee_used := add(attr(MarketState, 0, market_state_0, fee_used), fees) let fee_limit := attr(MarketState, 0, market_state_0, fee_limit) if gt(fee_used, fee_limit) { REVERT(8) } market_state_0 := build( MarketState, 0, /* quote_qty */ quote_qty, /* base_qty */ and(base_qty, U64_MASK), /* fee_used */ fee_used, /* fee_limit */ fee_limit ) let market_state_1 := sload(add(market_state_ptr, 1)) /* Check against min_qty */ { let min_quote_qty := attr(MarketState, 1, market_state_1, min_quote_qty) CAST_64_NEG(min_quote_qty) let min_base_qty := attr(MarketState, 1, market_state_1, min_base_qty) CAST_64_NEG(min_base_qty) if or(slt(quote_qty, min_quote_qty), slt(base_qty, min_base_qty)) { REVERT(9) } } /* Check against limit */ { /* Check if price fits limit */ let negatives := add(slt(quote_qty, 1), mul(slt(base_qty, 1), 2)) switch negatives /* Both negative */ case 3 { /* if one value is non zero, it must be negative */ if or(quote_qty, base_qty) { REVERT(10) } } /* long: quote_qty negative or zero */ case 1 { let current_price := div(mul(sub(0, quote_qty), PRICE_UNITS), base_qty) let long_max_price := attr(MarketState, 1, market_state_1, long_max_price) if gt(current_price, long_max_price) { REVERT(11) } } /* short: base_qty negative */ case 2 { if base_qty { let current_price := div(mul(quote_qty, PRICE_UNITS), sub(0, base_qty)) let short_min_price := attr(MarketState, 1, market_state_1, short_min_price) if lt(current_price, short_min_price) { REVERT(12) } } } } } let quote_session_balance_ptr := SESSION_BALANCE_PTR_(session_ptr, quote_asset_id) let base_session_balance_ptr := SESSION_BALANCE_PTR_(session_ptr, base_asset_id) let quote_session_balance_0 := sload(quote_session_balance_ptr) let base_session_balance_0 := sload(base_session_balance_ptr) let quote_balance := attr(SessionBalance, 0, quote_session_balance_0, asset_balance) quote_balance := add(quote_balance, quote_delta) quote_balance := sub(quote_balance, fees) if U64_OVERFLOW(quote_balance) { REVERT(13) } let base_balance := attr(SessionBalance, 0, base_session_balance_0, asset_balance) base_balance := add(base_balance, base_delta) if U64_OVERFLOW(base_balance) { REVERT(14) } sstore(market_state_ptr, market_state_0) sstore(quote_session_balance_ptr, or( and(mask_out(SessionBalance, 0, asset_balance), quote_session_balance_0), build( SessionBalance, 0, /* total_deposit */ 0, /* unsettled_withdraw_total */ 0, /* asset_balance */ quote_balance) )) sstore(base_session_balance_ptr, or( and(mask_out(SessionBalance, 0, asset_balance), base_session_balance_0), build( SessionBalance, 0, /* total_deposit */ 0, /* unsettled_withdraw_total */ 0, /* asset_balance */ base_balance) )) } if or(quote_net, base_net) { REVERT(15) } sstore(exchange_balance_ptr, exchange_balance) } } } }
[ name_offset, owner, withdraw_address, recovery_address, recovery_address_proposed, name_len, name_data(12) ] /
function get_exchange(uint32 exchange_id) public view returns ( string memory name, bool locked, address owner, address withdraw_address, address recovery_address, address recovery_address_proposed ) { uint256[8] memory return_value_mem; assembly { let exchange_count := sload(exchange_count_slot) if iszero(lt(exchange_id, exchange_count)) { REVERT(1) } let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_0 := sload(exchange_ptr) let exchange_1 := sload(add(exchange_ptr, 1)) let exchange_2 := sload(add(exchange_ptr, 2)) let exchange_3 := sload(add(exchange_ptr, 3)) MSTORE_STR(return_value_mem, WORD_6, 11, exchange_0) RETURN(WORD_1, attr(Exchange, 0, exchange_0, locked)) RETURN(WORD_2, attr(Exchange, 0, exchange_0, owner)) RETURN(WORD_3, attr(Exchange, 1, exchange_1, withdraw_address)) RETURN(WORD_4, attr(Exchange, 2, exchange_2, recovery_address)) RETURN(WORD_5, attr(Exchange, 3, exchange_3, recovery_address_proposed)) return(return_value_mem, const_add(WORD_6, /* string header */ WORD_1, /* string data */ 12)) } }
14,122,818
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; /** @author Open Zeppelin / Tellor @title ERC20 @dev Taken from OZ, but no context **/ contract ERC20 is IERC20 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; address public whitelistAdmin; bool public isWhitelistedSystem; mapping(address => uint) public whitelistedAmount; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; event NewWhitelistAdmin(address _newAdmin); event NewWhitelistedAmount(address _user, uint256 _amount); /** * @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_, bool _isWhitelistedSystem) { _name = name_; _symbol = symbol_; _decimals = 18; isWhitelistedSystem = _isWhitelistedSystem; whitelistAdmin = msg.sender; } /** * @dev Allows the user to set a new admin address * @param _newAdmin the address of the new admin address */ function setWhitelistAdmin(address _newAdmin) external { require(msg.sender == whitelistAdmin, "not the whitelist admin"); require(_newAdmin != address(0), "cannot send to the zero address"); whitelistAdmin = _newAdmin; emit NewWhitelistAdmin(_newAdmin); } function setWhitelistedAmount(address _user, uint256 _amount) external{ require(msg.sender == whitelistAdmin, "not the whitelist admin"); whitelistedAmount[_user] = _amount; emit NewWhitelistedAmount(_user,_amount); } /** * @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. */ 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"); if (isWhitelistedSystem){ require(_balances[recipient] + amount <= whitelistedAmount[recipient], "recipient not whitelisted for amount"); require(_balances[sender] <= whitelistedAmount[sender], "sender not whitelisted for 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"); if (isWhitelistedSystem){ require(_balances[account] + amount <= whitelistedAmount[account], "recipient not whitelisted for 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"); _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); } }
Destroys `amount` tokens from `account`, reducing the total supply. Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address. - `account` must have at least `amount` tokens./
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account] - amount; _totalSupply = _totalSupply - amount; emit Transfer(account, address(0), amount); }
12,984,346
// SPDX-License-Identifier: Unlicense pragma solidity 0.7.6; // Part: IStrategy interface IStrategy { function rebalance() external; function shouldRebalance() external view returns (bool); } // Part: IVault interface IVault { function deposit( uint256, uint256, uint256, uint256, address ) external returns ( uint256, uint256, uint256 ); function withdraw( uint256, uint256, uint256, address ) external returns (uint256, uint256); function getTotalAmounts() external view returns (uint256, uint256); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/ReentrancyGuard /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // Part: PositionKey library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } // Part: Uniswap/[email protected]/FixedPoint96 /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // Part: Uniswap/[email protected]/FullMath /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // Part: Uniswap/[email protected]/IUniswapV3MintCallback /// @title Callback for IUniswapV3PoolActions#mint /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface interface IUniswapV3MintCallback { /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external; } // Part: Uniswap/[email protected]/IUniswapV3PoolActions /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // Part: Uniswap/[email protected]/IUniswapV3PoolDerivedState /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // Part: Uniswap/[email protected]/IUniswapV3PoolEvents /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // Part: Uniswap/[email protected]/IUniswapV3PoolImmutables /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // Part: Uniswap/[email protected]/IUniswapV3PoolOwnerActions /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // Part: Uniswap/[email protected]/IUniswapV3PoolState /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // Part: Uniswap/[email protected]/IUniswapV3SwapCallback /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // Part: Uniswap/[email protected]/TickMath /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // Part: LiquidityAmounts /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // Part: OpenZeppelin/[email protected]/ERC20 /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: Uniswap/[email protected]/IUniswapV3Pool /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // Part: AlphaVault /** * @title Alpha Vault * @notice A vault that provides liquidity on Uniswap V3. */ contract AlphaVault is IVault, IUniswapV3MintCallback, IUniswapV3SwapCallback, ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; event Deposit( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event Withdraw( address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1 ); event CollectFees( uint256 feesToVault0, uint256 feesToVault1, uint256 feesToProtocol0, uint256 feesToProtocol1 ); event Snapshot(int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 totalSupply); IUniswapV3Pool public immutable pool; IERC20 public immutable token0; IERC20 public immutable token1; int24 public immutable tickSpacing; uint256 public protocolFee; uint256 public maxTotalSupply; address public strategy; address public governance; address public pendingGovernance; int24 public baseLower; int24 public baseUpper; int24 public limitLower; int24 public limitUpper; uint256 public accruedProtocolFees0; uint256 public accruedProtocolFees1; /** * @dev After deploying, strategy needs to be set via `setStrategy()` * @param _pool Underlying Uniswap V3 pool * @param _protocolFee Protocol fee expressed as multiple of 1e-6 * @param _maxTotalSupply Cap on total supply */ constructor( address _pool, uint256 _protocolFee, uint256 _maxTotalSupply ) ERC20("Alpha Vault", "AV") { pool = IUniswapV3Pool(_pool); token0 = IERC20(IUniswapV3Pool(_pool).token0()); token1 = IERC20(IUniswapV3Pool(_pool).token1()); tickSpacing = IUniswapV3Pool(_pool).tickSpacing(); protocolFee = _protocolFee; maxTotalSupply = _maxTotalSupply; governance = msg.sender; require(_protocolFee < 1e6, "protocolFee"); } /** * @notice Deposits tokens in proportion to the vault's current holdings. * @dev These tokens sit in the vault and are not used for liquidity on * Uniswap until the next rebalance. Also note it's not necessary to check * if user manipulated price to deposit cheaper, as the value of range * orders can only by manipulated higher. * @param amount0Desired Max amount of token0 to deposit * @param amount1Desired Max amount of token1 to deposit * @param amount0Min Revert if resulting `amount0` is less than this * @param amount1Min Revert if resulting `amount1` is less than this * @param to Recipient of shares * @return shares Number of shares minted * @return amount0 Amount of token0 deposited * @return amount1 Amount of token1 deposited */ function deposit( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override nonReentrant returns ( uint256 shares, uint256 amount0, uint256 amount1 ) { require(amount0Desired > 0 || amount1Desired > 0, "amount0Desired or amount1Desired"); require(to != address(0) && to != address(this), "to"); // Poke positions so vault's current holdings are up-to-date _poke(baseLower, baseUpper); _poke(limitLower, limitUpper); // Calculate amounts proportional to vault's holdings (shares, amount0, amount1) = _calcSharesAndAmounts(amount0Desired, amount1Desired); require(shares > 0, "shares"); require(amount0 >= amount0Min, "amount0Min"); require(amount1 >= amount1Min, "amount1Min"); // Pull in tokens from sender if (amount0 > 0) token0.safeTransferFrom(msg.sender, address(this), amount0); if (amount1 > 0) token1.safeTransferFrom(msg.sender, address(this), amount1); // Mint shares to recipient _mint(to, shares); emit Deposit(msg.sender, to, shares, amount0, amount1); require(totalSupply() <= maxTotalSupply, "maxTotalSupply"); } /// @dev Do zero-burns to poke a position on Uniswap so earned fees are /// updated. Should be called if total amounts needs to include up-to-date /// fees. function _poke(int24 tickLower, int24 tickUpper) internal { (uint128 liquidity, , , , ) = _position(tickLower, tickUpper); if (liquidity > 0) { pool.burn(tickLower, tickUpper, 0); } } /// @dev Calculates the largest possible `amount0` and `amount1` such that /// they're in the same proportion as total amounts, but not greater than /// `amount0Desired` and `amount1Desired` respectively. function _calcSharesAndAmounts(uint256 amount0Desired, uint256 amount1Desired) internal view returns ( uint256 shares, uint256 amount0, uint256 amount1 ) { uint256 totalSupply = totalSupply(); (uint256 total0, uint256 total1) = getTotalAmounts(); // If total supply > 0, vault can't be empty assert(totalSupply == 0 || total0 > 0 || total1 > 0); if (totalSupply == 0) { // For first deposit, just use the amounts desired amount0 = amount0Desired; amount1 = amount1Desired; shares = Math.max(amount0, amount1); } else if (total0 == 0) { amount1 = amount1Desired; shares = amount1.mul(totalSupply).div(total1); } else if (total1 == 0) { amount0 = amount0Desired; shares = amount0.mul(totalSupply).div(total0); } else { uint256 cross = Math.min(amount0Desired.mul(total1), amount1Desired.mul(total0)); require(cross > 0, "cross"); // Round up amounts amount0 = cross.sub(1).div(total1).add(1); amount1 = cross.sub(1).div(total0).add(1); shares = cross.mul(totalSupply).div(total0).div(total1); } } /** * @notice Withdraws tokens in proportion to the vault's holdings. * @param shares Shares burned by sender * @param amount0Min Revert if resulting `amount0` is smaller than this * @param amount1Min Revert if resulting `amount1` is smaller than this * @param to Recipient of tokens * @return amount0 Amount of token0 sent to recipient * @return amount1 Amount of token1 sent to recipient */ function withdraw( uint256 shares, uint256 amount0Min, uint256 amount1Min, address to ) external override nonReentrant returns (uint256 amount0, uint256 amount1) { require(shares > 0, "shares"); require(to != address(0) && to != address(this), "to"); uint256 totalSupply = totalSupply(); // Burn shares _burn(msg.sender, shares); // Calculate token amounts proportional to unused balances uint256 unusedAmount0 = getBalance0().mul(shares).div(totalSupply); uint256 unusedAmount1 = getBalance1().mul(shares).div(totalSupply); // Withdraw proportion of liquidity from Uniswap pool (uint256 baseAmount0, uint256 baseAmount1) = _burnLiquidityShare(baseLower, baseUpper, shares, totalSupply); (uint256 limitAmount0, uint256 limitAmount1) = _burnLiquidityShare(limitLower, limitUpper, shares, totalSupply); // Sum up total amounts owed to recipient amount0 = unusedAmount0.add(baseAmount0).add(limitAmount0); amount1 = unusedAmount1.add(baseAmount1).add(limitAmount1); require(amount0 >= amount0Min, "amount0Min"); require(amount1 >= amount1Min, "amount1Min"); // Push tokens to recipient if (amount0 > 0) token0.safeTransfer(to, amount0); if (amount1 > 0) token1.safeTransfer(to, amount1); emit Withdraw(msg.sender, to, shares, amount0, amount1); } /// @dev Withdraws share of liquidity in a range from Uniswap pool. function _burnLiquidityShare( int24 tickLower, int24 tickUpper, uint256 shares, uint256 totalSupply ) internal returns (uint256 amount0, uint256 amount1) { (uint128 totalLiquidity, , , , ) = _position(tickLower, tickUpper); uint256 liquidity = uint256(totalLiquidity).mul(shares).div(totalSupply); if (liquidity > 0) { (uint256 burned0, uint256 burned1, uint256 fees0, uint256 fees1) = _burnAndCollect(tickLower, tickUpper, _toUint128(liquidity)); // Add share of fees amount0 = burned0.add(fees0.mul(shares).div(totalSupply)); amount1 = burned1.add(fees1.mul(shares).div(totalSupply)); } } /** * @notice Updates vault's positions. Can only be called by the strategy. * @dev Two orders are placed - a base order and a limit order. The base * order is placed first with as much liquidity as possible. This order * should use up all of one token, leaving only the other one. This excess * amount is then placed as a single-sided bid or ask order. */ function rebalance( int256 swapAmount, uint160 sqrtPriceLimitX96, int24 _baseLower, int24 _baseUpper, int24 _bidLower, int24 _bidUpper, int24 _askLower, int24 _askUpper ) external nonReentrant { require(msg.sender == strategy, "strategy"); _checkRange(_baseLower, _baseUpper); _checkRange(_bidLower, _bidUpper); _checkRange(_askLower, _askUpper); (, int24 tick, , , , , ) = pool.slot0(); require(_bidUpper <= tick, "bidUpper"); require(_askLower > tick, "askLower"); // inequality is strict as tick is rounded down // Withdraw all current liquidity from Uniswap pool { (uint128 baseLiquidity, , , , ) = _position(baseLower, baseUpper); (uint128 limitLiquidity, , , , ) = _position(limitLower, limitUpper); _burnAndCollect(baseLower, baseUpper, baseLiquidity); _burnAndCollect(limitLower, limitUpper, limitLiquidity); } // Emit snapshot to record balances and supply uint256 balance0 = getBalance0(); uint256 balance1 = getBalance1(); emit Snapshot(tick, balance0, balance1, totalSupply()); if (swapAmount != 0) { pool.swap( address(this), swapAmount > 0, swapAmount > 0 ? swapAmount : -swapAmount, sqrtPriceLimitX96, "" ); balance0 = getBalance0(); balance1 = getBalance1(); } // Place base order on Uniswap uint128 liquidity = _liquidityForAmounts(_baseLower, _baseUpper, balance0, balance1); _mintLiquidity(_baseLower, _baseUpper, liquidity); (baseLower, baseUpper) = (_baseLower, _baseUpper); balance0 = getBalance0(); balance1 = getBalance1(); // Place bid or ask order on Uniswap depending on which token is left uint128 bidLiquidity = _liquidityForAmounts(_bidLower, _bidUpper, balance0, balance1); uint128 askLiquidity = _liquidityForAmounts(_askLower, _askUpper, balance0, balance1); if (bidLiquidity > askLiquidity) { _mintLiquidity(_bidLower, _bidUpper, bidLiquidity); (limitLower, limitUpper) = (_bidLower, _bidUpper); } else { _mintLiquidity(_askLower, _askUpper, askLiquidity); (limitLower, limitUpper) = (_askLower, _askUpper); } } function _checkRange(int24 tickLower, int24 tickUpper) internal view { int24 _tickSpacing = tickSpacing; require(tickLower < tickUpper, "tickLower < tickUpper"); require(tickLower >= TickMath.MIN_TICK, "tickLower too low"); require(tickUpper <= TickMath.MAX_TICK, "tickUpper too high"); require(tickLower % _tickSpacing == 0, "tickLower % tickSpacing"); require(tickUpper % _tickSpacing == 0, "tickUpper % tickSpacing"); } /// @dev Withdraws liquidity from a range and collects all fees in the /// process. function _burnAndCollect( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal returns ( uint256 burned0, uint256 burned1, uint256 feesToVault0, uint256 feesToVault1 ) { if (liquidity > 0) { (burned0, burned1) = pool.burn(tickLower, tickUpper, liquidity); } // Collect all owed tokens including earned fees (uint256 collect0, uint256 collect1) = pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); feesToVault0 = collect0.sub(burned0); feesToVault1 = collect1.sub(burned1); uint256 feesToProtocol0; uint256 feesToProtocol1; // Update accrued protocol fees uint256 _protocolFee = protocolFee; if (_protocolFee > 0) { feesToProtocol0 = feesToVault0.mul(_protocolFee).div(1e6); feesToProtocol1 = feesToVault1.mul(_protocolFee).div(1e6); feesToVault0 = feesToVault0.sub(feesToProtocol0); feesToVault1 = feesToVault1.sub(feesToProtocol1); accruedProtocolFees0 = accruedProtocolFees0.add(feesToProtocol0); accruedProtocolFees1 = accruedProtocolFees1.add(feesToProtocol1); } emit CollectFees(feesToVault0, feesToVault1, feesToProtocol0, feesToProtocol1); } /// @dev Deposits liquidity in a range on the Uniswap pool. function _mintLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal { if (liquidity > 0) { pool.mint(address(this), tickLower, tickUpper, liquidity, ""); } } /** * @notice Calculates the vault's total holdings of token0 and token1 - in * other words, how much of each token the vault would hold if it withdrew * all its liquidity from Uniswap. */ function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) { (uint256 baseAmount0, uint256 baseAmount1) = getPositionAmounts(baseLower, baseUpper); (uint256 limitAmount0, uint256 limitAmount1) = getPositionAmounts(limitLower, limitUpper); total0 = getBalance0().add(baseAmount0).add(limitAmount0); total1 = getBalance1().add(baseAmount1).add(limitAmount1); } /** * @notice Amounts of token0 and token1 held in vault's position. Includes * owed fees but excludes the proportion of fees that will be paid to the * protocol. Doesn't include fees accrued since last poke. */ function getPositionAmounts(int24 tickLower, int24 tickUpper) public view returns (uint256 amount0, uint256 amount1) { (uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = _position(tickLower, tickUpper); (amount0, amount1) = _amountsForLiquidity(tickLower, tickUpper, liquidity); // Subtract protocol fees uint256 oneMinusFee = uint256(1e6).sub(protocolFee); amount0 = amount0.add(uint256(tokensOwed0).mul(oneMinusFee).div(1e6)); amount1 = amount1.add(uint256(tokensOwed1).mul(oneMinusFee).div(1e6)); } /** * @notice Balance of token0 in vault not used in any position. */ function getBalance0() public view returns (uint256) { return token0.balanceOf(address(this)).sub(accruedProtocolFees0); } /** * @notice Balance of token1 in vault not used in any position. */ function getBalance1() public view returns (uint256) { return token1.balanceOf(address(this)).sub(accruedProtocolFees1); } /// @dev Wrapper around `IUniswapV3Pool.positions()`. function _position(int24 tickLower, int24 tickUpper) internal view returns ( uint128, uint256, uint256, uint128, uint128 ) { bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper); return pool.positions(positionKey); } /// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. function _amountsForLiquidity( int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256, uint256) { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidity ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. function _liquidityForAmounts( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ) internal view returns (uint128) { (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), amount0, amount1 ); } /// @dev Casts uint256 to uint128 with overflow check. function _toUint128(uint256 x) internal pure returns (uint128) { assert(x <= type(uint128).max); return uint128(x); } /// @dev Callback for Uniswap V3 pool. function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external override { require(msg.sender == address(pool)); if (amount0 > 0) token0.safeTransfer(msg.sender, amount0); if (amount1 > 0) token1.safeTransfer(msg.sender, amount1); } /// @dev Callback for Uniswap V3 pool. function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external override { require(msg.sender == address(pool)); if (amount0Delta > 0) token0.safeTransfer(msg.sender, uint256(amount0Delta)); if (amount1Delta > 0) token1.safeTransfer(msg.sender, uint256(amount1Delta)); } /** * @notice Used to collect accumulated protocol fees. */ function collectProtocol( uint256 amount0, uint256 amount1, address to ) external onlyGovernance { accruedProtocolFees0 = accruedProtocolFees0.sub(amount0); accruedProtocolFees1 = accruedProtocolFees1.sub(amount1); if (amount0 > 0) token0.safeTransfer(to, amount0); if (amount1 > 0) token1.safeTransfer(to, amount1); } /** * @notice Removes tokens accidentally sent to this vault. */ function sweep( IERC20 token, uint256 amount, address to ) external onlyGovernance { require(token != token0 && token != token1, "token"); token.safeTransfer(to, amount); } /** * @notice Used to set the strategy contract that determines the position * ranges and calls rebalance(). Must be called after this vault is * deployed. */ function setStrategy(address _strategy) external onlyGovernance { strategy = _strategy; } /** * @notice Used to change the protocol fee charged on pool fees earned from * Uniswap, expressed as multiple of 1e-6. */ function setProtocolFee(uint256 _protocolFee) external onlyGovernance { require(_protocolFee < 1e6, "protocolFee"); protocolFee = _protocolFee; } /** * @notice Used to change deposit cap for a guarded launch or to ensure * vault doesn't grow too large relative to the pool. Cap is on total * supply rather than amounts of token0 and token1 as those amounts * fluctuate naturally over time. */ function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyGovernance { maxTotalSupply = _maxTotalSupply; } /** * @notice Removes liquidity in case of emergency. */ function emergencyBurn( int24 tickLower, int24 tickUpper, uint128 liquidity ) external onlyGovernance { pool.burn(tickLower, tickUpper, liquidity); pool.collect(address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max); } /** * @notice Governance address is not updated until the new governance * address has called `acceptGovernance()` to accept this responsibility. */ function setGovernance(address _governance) external onlyGovernance { pendingGovernance = _governance; } /** * @notice `setGovernance()` should be called by the existing governance * address prior to calling this function. */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "pendingGovernance"); governance = msg.sender; } modifier onlyGovernance { require(msg.sender == governance, "governance"); _; } } // File: PassiveStrategy.sol /** * @title Passive Strategy * @notice Rebalancing strategy for Alpha Vault that maintains the two * following range orders: * * 1. Base order is placed between X - B and X + B + TS. * 2. Limit order is placed between X - L and X, or between X + TS * and X + L + TS, depending on which token it holds more of. * * where: * * X = current tick rounded down to multiple of tick spacing * TS = tick spacing * B = base threshold * L = limit threshold * * Note that after these two orders, the vault should have deposited * all its tokens and should only have a few wei left. * * Because the limit order tries to sell whichever token the vault * holds more of, the vault's holdings will have a tendency to get * closer to a 1:1 balance. This enables it to continue providing * liquidity without running out of inventory of either token, and * achieves this without the need to swap directly on Uniswap and pay * fees. */ contract PassiveStrategy is IStrategy { using SafeMath for uint256; AlphaVault public immutable vault; IUniswapV3Pool public immutable pool; int24 public immutable tickSpacing; int24 public baseThreshold; int24 public limitThreshold; uint256 public period; int24 public minTickMove; int24 public maxTwapDeviation; uint32 public twapDuration; address public keeper; uint256 public lastTimestamp; int24 public lastTick; /** * @param _vault Underlying Alpha Vault * @param _baseThreshold Used to determine base order range * @param _limitThreshold Used to determine limit order range * @param _period Can only rebalance if this length of time has passed * @param _minTickMove Can only rebalance if price has moved at least this much * @param _maxTwapDeviation Max deviation from TWAP during rebalance * @param _twapDuration TWAP duration in seconds for deviation check * @param _keeper Account that can call `rebalance()` */ constructor( address _vault, int24 _baseThreshold, int24 _limitThreshold, uint256 _period, int24 _minTickMove, int24 _maxTwapDeviation, uint32 _twapDuration, address _keeper ) { IUniswapV3Pool _pool = AlphaVault(_vault).pool(); int24 _tickSpacing = _pool.tickSpacing(); vault = AlphaVault(_vault); pool = _pool; tickSpacing = _tickSpacing; baseThreshold = _baseThreshold; limitThreshold = _limitThreshold; period = _period; minTickMove = _minTickMove; maxTwapDeviation = _maxTwapDeviation; twapDuration = _twapDuration; keeper = _keeper; _checkThreshold(_baseThreshold, _tickSpacing); _checkThreshold(_limitThreshold, _tickSpacing); require(_minTickMove >= 0, "minTickMove must be >= 0"); require(_maxTwapDeviation >= 0, "maxTwapDeviation must be >= 0"); require(_twapDuration > 0, "twapDuration must be > 0"); (, lastTick, , , , , ) = _pool.slot0(); } /** * @notice Calculates new ranges for orders and calls `vault.rebalance()` * so that vault can update its positions. Can only be called by keeper. */ function rebalance() external override { require(shouldRebalance(), "cannot rebalance"); int24 tick = getTick(); int24 tickFloor = _floor(tick); int24 tickCeil = tickFloor + tickSpacing; vault.rebalance( 0, 0, tickFloor - baseThreshold, tickCeil + baseThreshold, tickFloor - limitThreshold, tickFloor, tickCeil, tickCeil + limitThreshold ); lastTimestamp = block.timestamp; lastTick = tick; } function shouldRebalance() public view override returns (bool) { // check called by keeper if (msg.sender != keeper) { return false; } // check enough time has passed if (block.timestamp < lastTimestamp.add(period)) { return false; } // check price has moved enough int24 tick = getTick(); int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick; if (tickMove < minTickMove) { return false; } // check price near twap int24 twap = getTwap(); int24 twapDeviation = tick > twap ? tick - twap : twap - tick; if (twapDeviation > maxTwapDeviation) { return false; } // check price not too close to boundary int24 maxThreshold = baseThreshold > limitThreshold ? baseThreshold : limitThreshold; if (tick < TickMath.MIN_TICK + maxThreshold + tickSpacing) { return false; } if (tick > TickMath.MAX_TICK - maxThreshold - tickSpacing) { return false; } return true; } function getTick() public view returns (int24) { (, int24 tick, , , , , ) = pool.slot0(); return tick; } /// @dev Fetches time-weighted average price in ticks from Uniswap pool. function getTwap() public view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); } /// @dev Rounds tick down towards negative infinity so that it's a multiple /// of `tickSpacing`. function _floor(int24 tick) internal view returns (int24) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; return compressed * tickSpacing; } function _checkThreshold(int24 threshold, int24 _tickSpacing) internal pure { require(threshold > 0, "threshold must be > 0"); require(threshold <= TickMath.MAX_TICK, "threshold too high"); require(threshold % _tickSpacing == 0, "threshold must be multiple of tickSpacing"); } function setKeeper(address _keeper) external onlyGovernance { keeper = _keeper; } function setBaseThreshold(int24 _baseThreshold) external onlyGovernance { _checkThreshold(_baseThreshold, tickSpacing); baseThreshold = _baseThreshold; } function setLimitThreshold(int24 _limitThreshold) external onlyGovernance { _checkThreshold(_limitThreshold, tickSpacing); limitThreshold = _limitThreshold; } function setPeriod(uint256 _period) external onlyGovernance { period = _period; } function setMinTickMove(int24 _minTickMove) external onlyGovernance { require(_minTickMove >= 0, "minTickMove must be >= 0"); minTickMove = _minTickMove; } function setMaxTwapDeviation(int24 _maxTwapDeviation) external onlyGovernance { require(_maxTwapDeviation >= 0, "maxTwapDeviation must be >= 0"); maxTwapDeviation = _maxTwapDeviation; } function setTwapDuration(uint32 _twapDuration) external onlyGovernance { require(_twapDuration > 0, "twapDuration must be > 0"); twapDuration = _twapDuration; } /// @dev Uses same governance as underlying vault. modifier onlyGovernance { require(msg.sender == vault.governance(), "governance"); _; } }
check called by keeper check enough time has passed
function shouldRebalance() public view override returns (bool) { if (msg.sender != keeper) { return false; } if (block.timestamp < lastTimestamp.add(period)) { return false; } int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick; if (tickMove < minTickMove) { return false; } int24 twapDeviation = tick > twap ? tick - twap : twap - tick; if (twapDeviation > maxTwapDeviation) { return false; } if (tick < TickMath.MIN_TICK + maxThreshold + tickSpacing) { return false; } if (tick > TickMath.MAX_TICK - maxThreshold - tickSpacing) { return false; } return true; }
352,578
//Address: 0x5c743a35E903F6c584514ec617ACEe0611Cf44f3 //Contract name: ExyToken //Balance: 0 Ether //Verification Date: 2/24/2018 //Transacion Count: 12523 // CODE STARTS HERE pragma solidity ^0.4.19; contract ERC223ReceivingContract { function tokenFallback(address _from, uint256 _value, bytes _data) public; } contract ERC223Token { using SafeMath for uint256; // token constants string public name; bytes32 public symbol; uint8 public decimals; uint256 public totalSupply; // token balances mapping(address => uint256) public balanceOf; // token spending allowance, used by transferFrom(), for compliance with ERC20 mapping (address => mapping(address => uint256)) internal allowances; // Function that is called when a user or another contract wants to transfer funds. function transfer(address to, uint256 value, bytes data) public returns (bool) { require(balanceOf[msg.sender] >= value); uint256 codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(to) } balanceOf[msg.sender] -= value; // underflow checked by require() above balanceOf[to] = balanceOf[to].add(value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(to); receiver.tokenFallback(msg.sender, value, data); } ERC223Transfer(msg.sender, to, value, data); return true; } // Standard function transfer similar to ERC20 transfer with no _data. // Added due to backwards compatibility reasons. function transfer(address to, uint256 value) public returns (bool) { require(balanceOf[msg.sender] >= value); uint256 codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(to) } balanceOf[msg.sender] -= value; // underflow checked by require() above balanceOf[to] = balanceOf[to].add(value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(to); receiver.tokenFallback(msg.sender, value, empty); } ERC223Transfer(msg.sender, to, value, empty); // ERC20 compatible event: Transfer(msg.sender, to, value); return true; } // Send _value tokens to _to from _from on the condition it is approved by _from. // Added for full compliance with ERC20 function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(_value <= balanceOf[_from]); require(_value <= allowances[_from][msg.sender]); bytes memory empty; balanceOf[_from] = balanceOf[_from] -= _value; allowances[_from][msg.sender] -= _value; balanceOf[_to] = balanceOf[_to].add(_value); // No need to call tokenFallback(), cause this is ERC20's solution to the same problem // tokenFallback solves in ERC223. Just fire the ERC223 event for logs consistency. ERC223Transfer(_from, _to, _value, empty); Transfer(_from, _to, _value); return true; } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) public returns (bool success) { allowances[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowances[_owner][_spender]; } event ERC223Transfer(address indexed from, address indexed to, uint256 value, bytes indexed data); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); } contract ERC223MintableToken is ERC223Token { uint256 public circulatingSupply; function mint(address to, uint256 value) internal returns (bool) { uint256 codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(to) } circulatingSupply += value; balanceOf[to] += value; // No safe math needed, won't exceed totalSupply. if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(to); bytes memory empty; receiver.tokenFallback(msg.sender, value, empty); } Mint(to, value); return true; } event Mint(address indexed to, uint256 value); } contract ERC20Token { function balanceOf(address owner) public view returns (uint256 balance); function transfer(address to, uint256 tokens) public returns (bool success); } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } } contract BountyTokenAllocation is Ownable { // This contract describes how the bounty tokens are allocated. // After a bounty allocation was proposed by a signatory, another // signatory must accept this allocation. // Total amount of remaining tokens to be distributed uint256 public remainingBountyTokens; // Addresses which have a bounty allocation, in order of proposals address[] public allocationAddressList; // Possible split states: Proposed, Approved, Rejected // Proposed is the initial state. // Both Approved and Rejected are final states. // The only possible transitions are: // Proposed => Approved // Proposed => Rejected // keep map here of bounty proposals mapping (address => Types.StructBountyAllocation) public bountyOf; /** * Bounty token allocation constructor. * * @param _remainingBountyTokens Total number of bounty tokens that will be * allocated. */ function BountyTokenAllocation(uint256 _remainingBountyTokens) Ownable() public { remainingBountyTokens = _remainingBountyTokens; } /** * Propose a bounty transfer * * @param _dest Address of bounty reciepent * @param _amount Amount of tokens he will receive */ function proposeBountyTransfer(address _dest, uint256 _amount) public onlyOwner { require(_amount > 0); require(_amount <= remainingBountyTokens); // we can't overwrite existing proposal // but we can overwrite rejected proposal with new values require(bountyOf[_dest].proposalAddress == 0x0 || bountyOf[_dest].bountyState == Types.BountyState.Rejected); if (bountyOf[_dest].bountyState != Types.BountyState.Rejected) { allocationAddressList.push(_dest); } remainingBountyTokens = SafeMath.sub(remainingBountyTokens, _amount); bountyOf[_dest] = Types.StructBountyAllocation({ amount: _amount, proposalAddress: msg.sender, bountyState: Types.BountyState.Proposed }); } /** * Approves a bounty transfer * * @param _dest Address of bounty reciepent * @return amount of tokens which we approved */ function approveBountyTransfer(address _approverAddress, address _dest) public onlyOwner returns (uint256) { require(bountyOf[_dest].bountyState == Types.BountyState.Proposed); require(bountyOf[_dest].proposalAddress != _approverAddress); bountyOf[_dest].bountyState = Types.BountyState.Approved; return bountyOf[_dest].amount; } /** * Rejects a bounty transfer * * @param _dest Address of bounty reciepent for whom we are rejecting bounty transfer */ function rejectBountyTransfer(address _dest) public onlyOwner { var tmp = bountyOf[_dest]; require(tmp.bountyState == Types.BountyState.Proposed); bountyOf[_dest].bountyState = Types.BountyState.Rejected; remainingBountyTokens = remainingBountyTokens + bountyOf[_dest].amount; } } library SafeMath { function sub(uint256 a, uint256 b) pure internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) pure internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function min(uint256 a, uint256 b) pure internal returns (uint256) { if(a > b) return b; else return a; } } contract SignatoryOwnable { mapping (address => bool) public IS_SIGNATORY; function SignatoryOwnable(address signatory0, address signatory1, address signatory2) internal { IS_SIGNATORY[signatory0] = true; IS_SIGNATORY[signatory1] = true; IS_SIGNATORY[signatory2] = true; } modifier onlySignatory() { require(IS_SIGNATORY[msg.sender]); _; } } contract SignatoryPausable is SignatoryOwnable { bool public paused; // == false by default address public pauseProposer; // == 0x0 (no proposal) by default function SignatoryPausable(address signatory0, address signatory1, address signatory2) SignatoryOwnable(signatory0, signatory1, signatory2) internal {} modifier whenPaused(bool status) { require(paused == status); _; } /** * @dev First signatory consent for contract pause state change. */ function proposePauseChange(bool status) onlySignatory whenPaused(!status) public { require(pauseProposer == 0x0); // require there's no pending proposal already pauseProposer = msg.sender; } /** * @dev Second signatory consent for contract pause state change, triggers the change. */ function approvePauseChange(bool status) onlySignatory whenPaused(!status) public { require(pauseProposer != 0x0); // require that a change was already proposed require(pauseProposer != msg.sender); // approver must be different than proposer pauseProposer = 0x0; paused = status; LogPause(paused); } /** * @dev Reject pause status change proposal. * Can also be called by the proposer, to cancel his proposal. */ function rejectPauseChange(bool status) onlySignatory whenPaused(!status) public { pauseProposer = 0x0; } event LogPause(bool status); } contract ExyToken is ERC223MintableToken, SignatoryPausable { using SafeMath for uint256; VestingAllocation private partnerTokensAllocation; VestingAllocation private companyTokensAllocation; BountyTokenAllocation private bountyTokensAllocation; /* * ICO TOKENS * 33% (including SEED TOKENS) * * Ico tokens are sent to the ICO_TOKEN_ADDRESS immediately * after ExyToken initialization */ uint256 private constant ICO_TOKENS = 14503506112248500000000000; address private constant ICO_TOKENS_ADDRESS = 0x97c967524d1eacAEb375d4269bE4171581a289C7; /* * SEED TOKENS * 33% (including ICO TOKENS) * * Seed tokens are sent to the SEED_TOKENS_ADDRESS immediately * after ExyToken initialization */ uint256 private constant SEED_TOKENS = 11700000000000000000000000; address private constant SEED_TOKENS_ADDRESS = 0x7C32c7649aA1335271aF00cd4280f87166474778; /* * COMPANY TOKENS * 33% * * Company tokens are being distrubited in 36 months * Total tokens = COMPANY_TOKENS_PER_PERIOD * COMPANY_PERIODS */ uint256 private constant COMPANY_TOKENS_PER_PERIOD = 727875169784680000000000; uint256 private constant COMPANY_PERIODS = 36; uint256 private constant MINUTES_IN_COMPANY_PERIOD = 60 * 24 * 365 / 12; /* * PARTNER TOKENS * 30% * * Partner tokens are available after 18 months * Total tokens = PARTNER_TOKENS_PER_PERIOD * PARTNER_PERIODS */ uint256 private constant PARTNER_TOKENS_PER_PERIOD = 23821369192953200000000000; uint256 private constant PARTNER_PERIODS = 1; uint256 private constant MINUTES_IN_PARTNER_PERIOD = MINUTES_IN_COMPANY_PERIOD * 18; // MINUTES_IN_COMPANY_PERIOD equals one month (see declaration of MINUTES_IN_COMPANY_PERIOD constant) /* * BOUNTY TOKENS * 3% * * Bounty tokens can be sent immediately after initialization */ uint256 private constant BOUNTY_TOKENS = 2382136919295320000000000; /* * MARKETING COST TOKENS * 1% * * Tokens are sent to the MARKETING_COST_ADDRESS immediately * after ExyToken initialization */ uint256 private constant MARKETING_COST_TOKENS = 794045639765106000000000; address private constant MARKETING_COST_ADDRESS = 0xF133ef3BE68128c9Af16F5aF8F8707f7A7A51452; uint256 public INIT_DATE; string public constant name = "Experty Token"; bytes32 public constant symbol = "EXY"; uint8 public constant decimals = 18; uint256 public constant totalSupply = ( COMPANY_TOKENS_PER_PERIOD * COMPANY_PERIODS + PARTNER_TOKENS_PER_PERIOD * PARTNER_PERIODS + BOUNTY_TOKENS + MARKETING_COST_TOKENS + ICO_TOKENS + SEED_TOKENS); /** * ExyToken contructor. * * Exy token contains allocations of: * - partnerTokensAllocation * - companyTokensAllocation * - bountyTokensAllocation * * param signatory0 Address of first signatory. * param signatory1 Address of second signatory. * param signatory2 Address of third signatory. * */ function ExyToken(address signatory0, address signatory1, address signatory2) SignatoryPausable(signatory0, signatory1, signatory2) public { // NOTE: the contract is safe as long as this assignment is not changed nor updated. // If, in the future, INIT_DATE could have a different value, calculations using its value // should most likely use SafeMath. INIT_DATE = block.timestamp; companyTokensAllocation = new VestingAllocation( COMPANY_TOKENS_PER_PERIOD, COMPANY_PERIODS, MINUTES_IN_COMPANY_PERIOD, INIT_DATE); partnerTokensAllocation = new VestingAllocation( PARTNER_TOKENS_PER_PERIOD, PARTNER_PERIODS, MINUTES_IN_PARTNER_PERIOD, INIT_DATE); bountyTokensAllocation = new BountyTokenAllocation( BOUNTY_TOKENS ); // minting marketing cost tokens mint(MARKETING_COST_ADDRESS, MARKETING_COST_TOKENS); // minting ICO tokens mint(ICO_TOKENS_ADDRESS, ICO_TOKENS); // minting SEED tokens mint(SEED_TOKENS_ADDRESS, SEED_TOKENS); } /** * Transfer ERC20 tokens out of this contract, to avoid them being stuck here forever. * Only one signatory decision needed, to minimize contract size since this is a rare case. */ function erc20TokenTransfer(address _tokenAddr, address _dest) public onlySignatory { ERC20Token token = ERC20Token(_tokenAddr); token.transfer(_dest, token.balanceOf(address(this))); } /** * Adds a proposition of a company token split to companyTokensAllocation */ function proposeCompanyAllocation(address _dest, uint256 _tokensPerPeriod) public onlySignatory onlyPayloadSize(2 * 32) { companyTokensAllocation.proposeAllocation(msg.sender, _dest, _tokensPerPeriod); } /** * Approves a proposition of a company token split */ function approveCompanyAllocation(address _dest) public onlySignatory { companyTokensAllocation.approveAllocation(msg.sender, _dest); } /** * Rejects a proposition of a company token split. * it can reject only not approved method */ function rejectCompanyAllocation(address _dest) public onlySignatory { companyTokensAllocation.rejectAllocation(_dest); } /** * Return number of remaining company tokens allocations * @return Length of company allocations per period */ function getRemainingCompanyTokensAllocation() public view returns (uint256) { return companyTokensAllocation.remainingTokensPerPeriod(); } /** * Given the index of the company allocation in allocationAddressList * we find its reciepent address and return struct with informations * about this allocation * * @param nr Index of allocation in allocationAddressList * @return Information about company alloction */ function getCompanyAllocation(uint256 nr) public view returns (uint256, address, uint256, Types.AllocationState, address) { address recipientAddress = companyTokensAllocation.allocationAddressList(nr); var (tokensPerPeriod, proposalAddress, claimedPeriods, allocationState) = companyTokensAllocation.allocationOf(recipientAddress); return (tokensPerPeriod, proposalAddress, claimedPeriods, allocationState, recipientAddress); } /** * Adds a proposition of a partner token split to companyTokensAllocation */ function proposePartnerAllocation(address _dest, uint256 _tokensPerPeriod) public onlySignatory onlyPayloadSize(2 * 32) { partnerTokensAllocation.proposeAllocation(msg.sender, _dest, _tokensPerPeriod); } /** * Approves a proposition of a partner token split */ function approvePartnerAllocation(address _dest) public onlySignatory { partnerTokensAllocation.approveAllocation(msg.sender, _dest); } /** * Rejects a proposition of a partner token split. * it can reject only not approved method */ function rejectPartnerAllocation(address _dest) public onlySignatory { partnerTokensAllocation.rejectAllocation(_dest); } /** * Return number of remaining partner tokens allocations * @return Length of partner allocations per period */ function getRemainingPartnerTokensAllocation() public view returns (uint256) { return partnerTokensAllocation.remainingTokensPerPeriod(); } /** * Given the index of the partner allocation in allocationAddressList * we find its reciepent address and return struct with informations * about this allocation * * @param nr Index of allocation in allocationAddressList * @return Information about partner alloction */ function getPartnerAllocation(uint256 nr) public view returns (uint256, address, uint256, Types.AllocationState, address) { address recipientAddress = partnerTokensAllocation.allocationAddressList(nr); var (tokensPerPeriod, proposalAddress, claimedPeriods, allocationState) = partnerTokensAllocation.allocationOf(recipientAddress); return (tokensPerPeriod, proposalAddress, claimedPeriods, allocationState, recipientAddress); } function proposeBountyTransfer(address _dest, uint256 _amount) public onlySignatory onlyPayloadSize(2 * 32) { bountyTokensAllocation.proposeBountyTransfer(_dest, _amount); } /** * Approves a bounty transfer and mint tokens * * @param _dest Address of the bounty reciepent to whom we should mint token */ function approveBountyTransfer(address _dest) public onlySignatory { uint256 tokensToMint = bountyTokensAllocation.approveBountyTransfer(msg.sender, _dest); mint(_dest, tokensToMint); } /** * Rejects a proposition of a bounty token. * it can reject only not approved method */ function rejectBountyTransfer(address _dest) public onlySignatory { bountyTokensAllocation.rejectBountyTransfer(_dest); } function getBountyTransfers(uint256 nr) public view returns (uint256, address, Types.BountyState, address) { address recipientAddress = bountyTokensAllocation.allocationAddressList(nr); var (amount, proposalAddress, bountyState) = bountyTokensAllocation.bountyOf(recipientAddress); return (amount, proposalAddress, bountyState, recipientAddress); } /** * Return number of remaining bounty tokens allocations * @return Length of company allocations */ function getRemainingBountyTokens() public view returns (uint256) { return bountyTokensAllocation.remainingBountyTokens(); } function claimTokens() public { mint( msg.sender, partnerTokensAllocation.claimTokens(msg.sender) + companyTokensAllocation.claimTokens(msg.sender) ); } /** * Override the transfer and mint functions to respect pause state. */ function transfer(address to, uint256 value, bytes data) public whenPaused(false) returns (bool) { return super.transfer(to, value, data); } function transfer(address to, uint256 value) public whenPaused(false) returns (bool) { return super.transfer(to, value); } function mint(address to, uint256 value) internal whenPaused(false) returns (bool) { if (circulatingSupply.add(value) > totalSupply) { paused = true; // emergency pause, this should never happen! return false; } return super.mint(to, value); } modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; } } contract Types { // Possible split states: Proposed, Approved, Rejected // Proposed is the initial state. // Both Approved and Rejected are final states. // The only possible transitions are: // Proposed => Approved // Proposed => Rejected enum AllocationState { Proposed, Approved, Rejected } // Structure used for storing company and partner allocations struct StructVestingAllocation { // How many tokens per period we want to pass uint256 tokensPerPeriod; // By whom was this split proposed. Another signatory must approve too address proposerAddress; // How many times did we release tokens uint256 claimedPeriods; // State of actual split. AllocationState allocationState; } enum BountyState { Proposed, // 0 Approved, // 1 Rejected // 2 } struct StructBountyAllocation { // How many tokens send him or her uint256 amount; // By whom was this allocation proposed address proposalAddress; // State of actual split. BountyState bountyState; } } contract VestingAllocation is Ownable { // This contract describes how the tokens are being released in time // Addresses which have a vesting allocation, in order of proposals address[] public allocationAddressList; // How many distributions periods there are uint256 public periods; // How long is one interval uint256 public minutesInPeriod; // Total amount of remaining tokens to be distributed uint256 public remainingTokensPerPeriod; // Total amount of all tokens uint256 public totalSupply; // Inital timestamp uint256 public initTimestamp; // For each address we can add exactly one possible split. // If we try to add another proposal on existing address it will be rejected mapping (address => Types.StructVestingAllocation) public allocationOf; /** * VestingAllocation contructor. * RemainingTokensPerPeriod variable which represents * the remaining amount of tokens to be distributed * */ function VestingAllocation(uint256 _tokensPerPeriod, uint256 _periods, uint256 _minutesInPeriod, uint256 _initalTimestamp) Ownable() public { totalSupply = _tokensPerPeriod * _periods; periods = _periods; minutesInPeriod = _minutesInPeriod; remainingTokensPerPeriod = _tokensPerPeriod; initTimestamp = _initalTimestamp; } /** * Propose split method adds proposal to the splits Array. * * @param _dest - address of the new receiver * @param _tokensPerPeriod - how many tokens we are giving to dest */ function proposeAllocation(address _proposerAddress, address _dest, uint256 _tokensPerPeriod) public onlyOwner { require(_tokensPerPeriod > 0); require(_tokensPerPeriod <= remainingTokensPerPeriod); // In solidity there is no "exist" method on a map key. // We can't overwrite existing proposal, so we are checking if it is the default value (0x0) // Add `allocationOf[_dest].allocationState == Types.AllocationState.Rejected` for possibility to overwrite rejected allocation require(allocationOf[_dest].proposerAddress == 0x0 || allocationOf[_dest].allocationState == Types.AllocationState.Rejected); if (allocationOf[_dest].allocationState != Types.AllocationState.Rejected) { allocationAddressList.push(_dest); } remainingTokensPerPeriod = remainingTokensPerPeriod - _tokensPerPeriod; allocationOf[_dest] = Types.StructVestingAllocation({ tokensPerPeriod: _tokensPerPeriod, allocationState: Types.AllocationState.Proposed, proposerAddress: _proposerAddress, claimedPeriods: 0 }); } /** * Approves the split allocation, so it can be claimed after periods * * @param _address - address for the split */ function approveAllocation(address _approverAddress, address _address) public onlyOwner { require(allocationOf[_address].allocationState == Types.AllocationState.Proposed); require(allocationOf[_address].proposerAddress != _approverAddress); allocationOf[_address].allocationState = Types.AllocationState.Approved; } /** * Rejects the split allocation * * @param _address - address for the split to be rejected */ function rejectAllocation(address _address) public onlyOwner { var tmp = allocationOf[_address]; require(tmp.allocationState == Types.AllocationState.Proposed); allocationOf[_address].allocationState = Types.AllocationState.Rejected; remainingTokensPerPeriod = remainingTokensPerPeriod + tmp.tokensPerPeriod; } function claimTokens(address _address) public returns (uint256) { Types.StructVestingAllocation storage alloc = allocationOf[_address]; if (alloc.allocationState == Types.AllocationState.Approved) { uint256 periodsElapsed = SafeMath.min((block.timestamp - initTimestamp) / (minutesInPeriod * 1 minutes), periods); uint256 tokens = (periodsElapsed - alloc.claimedPeriods) * alloc.tokensPerPeriod; alloc.claimedPeriods = periodsElapsed; return tokens; } return 0; } }
Second signatory consent for contract pause state change, triggers the change./
function approvePauseChange(bool status) onlySignatory whenPaused(!status) public { pauseProposer = 0x0; paused = status; LogPause(paused); }
15,833,596
./full_match/97/0x670B9706b9f798e65Ed1608945055E5ca3966A47/sources/contracts/Rebuy.sol
approve token transfer to cover all possible scenarios add the liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, block.timestamp ); uniswapV2Router.addLiquidityETH{value: ethAmount}( }
3,267,978
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; // ---------------------- Built with 💘 for everyone -------------------------- /// @author Kinois Le Roi /// @title SmACV1 [Smart Ads Contract V1] - This contract enables addresses to deploy smart ads. /// Token : Paid Per Click - The winning crypto of the internet. /// Symbol : PPeC - Spelled [P:E:K] // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- /// @title PPeC : Paid Per Click [ERC20] Interface // ---------------------------------------------------------------------------- interface PPeC { /// Transfer `amount` tokens to `to`. function transfer(address to, uint256 amount) external returns (bool); /// Get the amount of tokens owned by account `owner`. function balanceOf(address owner) external view returns(uint256); /// Get treasury address. function treasury() external view returns(address); /// Get founder address. function founder() external view returns(address); } // ---------------------------------------------------------------------------- /// @title AdCreator : Smart Ads Contract Creator [SmACCor] - Enables addresses to publish Ads. /// @notice Smart Ads cannot be updated once promoted. // ---------------------------------------------------------------------------- contract AdCreator { // Define public constant variables. address PPeCAddress = 0xE1498556390645cA488320fe979bC72BdecB6A57; // PPeC contract address. address public founder; // PPeC founder address. address public treasury; // PPeC treasury address. uint256 public minClaimerBalance; // The minimum balance an address must have before claiming rewards. uint256 public minReward; // The minimum reward a promoter will offer to a claimer. uint256 public promoterFee; // Fee for ad space a promoter must pay [in % | 100 = 1%]. uint256 public claimerFee; // Fee a claimer must pay [in % | 100 = 1%]. bool public paused = false; // Advertisement publishing status. mapping(address => uint256) public pledged; // Total pledged balance of an address. mapping(address => bool) public delegateContract; // Delegate status of a contract. mapping(address => SmACV1[]) public promoterAds; // All ads for a given address. SmACV1[] public advertisements; // All ads. // Set immutable values. constructor(uint256 minReward_, uint256 minBalance_) { founder = PPeC(PPeCAddress).founder(); treasury = PPeC(PPeCAddress).treasury(); minClaimerBalance = minBalance_; minReward = minReward_; promoterFee = 2000; claimerFee = 5000; } // Events that will be emitted on changes. event Pause(); event Unpause(); event RemoveAd(); event LaunchAd( string link, string title, uint256 reach, uint256 reward, uint256 budget, uint256 indexed created, address indexed promoter, address indexed adsContract ); // Errors that describe failures. // The triple-slash comments are so-called natspec // comments. They will be shown when the user // is asked to confirm a transaction or // when an error is displayed. (source: solidity.org) /// The budget exceeds your balance. /// Your budget is `budget`, however your balance is `balance`. error BudgetExceedBalance(uint256 budget, uint256 balance); /// Your balance pledged `pledged` cannot exceeds your balance `balance`. error PledgeExceedBalance(uint256 pledged, uint256 balance); /// Your reward `reward` is lower than (`minReward`) the minimum required. error RewardTooLow(uint256 reward, uint256 minReward); /// The index entered `index` is out of bound. error IndexOutOfBound(uint256 index); /// You are not a delegate Contract. error NotDelegateContract(); /// Make a function callable only when the contract is not paused. modifier whenNotPaused() { require(paused == false, "All publications have been paused."); _; } /// Make a function callable only when the contract is paused. modifier whenPaused() { require(paused); _; } /// Make a function callable only by the founder. modifier onlyFounder() { require(msg.sender == founder, "Your are not the Founder."); _; } /// Launch a smart advertisement. function launchAd(string memory title, string memory link, uint256 reach, uint256 reward) whenNotPaused public returns(bool success) { // Require to reach at least 30 people. require(reach >= 30, "You must enter at least 30."); // Check promoter's [token] balance and pledged balance. // NOTE - Always check balances before transaction. uint256 PromoterBalance = PPeC(PPeCAddress).balanceOf(msg.sender); uint256 balancePledged = pledged[msg.sender]; // Set the budget. uint256 budget = reach * reward; // Revert the call if the budget required // is greater than the current balance. if (budget > PromoterBalance) revert BudgetExceedBalance(budget, PromoterBalance); // Revert the call if the balance pledged // will be greater than the current balance. // This requirement makes it harder for an address // to publish multiple ads. [more tokens = more ads] if (balancePledged + budget > PromoterBalance) revert PledgeExceedBalance(balancePledged, PromoterBalance); // Revert the call if the reward offered is // less than the minimum reward required. if (reward < minReward) revert RewardTooLow(reward, minReward); // Increase sender pledged balance. pledged[msg.sender] += budget; // Create the advertisement (SmAC constructor). // Variable orders should match bellow with SmAC constructor !!important!! SmACV1 newAdvertisement = new SmACV1( msg.sender, PPeCAddress, link, title, reach, reward, minReward, claimerFee, promoterFee, minClaimerBalance ); // 1. Add advertisement to array. advertisements.push(newAdvertisement); // 2. Add advertisement to the sender array. promoterAds[msg.sender].push(newAdvertisement); // Set the new contract as a delegate // enabling calls [from SmAC] to function updatePledged() [in SmACCor]. delegateContract[address(newAdvertisement)] = true; // See {event LaunchAds} emit LaunchAd( link, title, reach, reward, budget, block.timestamp, msg.sender, // promoter address address(newAdvertisement) //contract address ); return true; } /// Remove an advertisement from the array. function removeAd(uint256 index) public onlyFounder returns(bool removed) { // Revert the call if the index is // greater than or equal to the array length. if (index >= advertisements.length) revert IndexOutOfBound(index); // Shift array indexes. for (uint256 i = index; i < advertisements.length - 1; i++) { advertisements[i] = advertisements[i + 1]; } // Remove last advertisement from array. advertisements.pop(); // See {event RemoveAd} emit RemoveAd(); return true; } /// Update promoter's pledged balance (SmAC Contracts calls only). function updatePledged(address promoter, uint256 amount) public returns(bool success) { // Revert the call if the sender is not // a delegate contract address. if (delegateContract[msg.sender] != true) revert NotDelegateContract(); // Update pledged balance. pledged[promoter] = amount; return true; } /// Change minimum reward to `newMin`. function setMinReward(uint256 newMin) public onlyFounder returns(bool success) { // set new minReward minReward = newMin; return true; } /// Change the minimum balance a claimer must have before claiming rewards to `newMin`. function setMinClaimerBalance(uint256 newMin) public onlyFounder returns(bool success) { // set new minClaimerBalance minClaimerBalance = newMin; return true; } /// Change promoters' fee to `newFee`. function setPromoterFee(uint256 newFee) public onlyFounder returns(bool success) { // set new promoterFee promoterFee = newFee; return true; } /// Change claimers' fee to `newFee`. function setClaimerFee(uint256 newFee) public onlyFounder returns(bool success) { // set new claimerFee claimerFee = newFee; return true; } /// Pause advertisement publication. function pause() public onlyFounder whenNotPaused returns(bool success) { // Set pause paused = true; // See {event Pause} emit Pause(); return true; } /// Unpause advertisement publication. function unpause() public onlyFounder whenPaused returns(bool success) { // Unset pause paused = false; // See {event Unpause} emit Unpause(); return true; } /// Get the number of advertisements in our array. function promotionCount() public view returns(uint256) { return advertisements.length; // promotions count. } /// Get the amount of tokens owned by account `owner`. function balanceOf(address owner) public view returns(uint256) { return PPeC(PPeCAddress).balanceOf(owner); } /// Get the number of advertisements for `promoter`. function promoterAdCount(address promoter) public view returns(uint256) { return promoterAds[promoter].length; } /// Get the balances and ad count of `owner`. function ownerInfo(address owner) public view returns(uint256 wallet, uint256 pledge, uint256 adCount) { return ( PPeC(PPeCAddress).balanceOf(owner), // owner balance pledged[owner], // owner pledged balance promoterAds[owner].length // owner ad count ); } /// Get the contract information. function contractInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256) { return ( PPeC(PPeCAddress).balanceOf(treasury), // treasury balance advertisements.length, // ad count minClaimerBalance, // minimum claimer balance promoterFee, // promoter fee claimerFee, // claimer fee minReward // minimum reward ); } } // ---------------------------------------------------------------------------- /// @title SmACCor : AdCreator [Smart ads Contract Creator] Interface. // ---------------------------------------------------------------------------- interface SmACCor { /// Update the promoter pledged balance [SmAC contracts calls only]. function updatePledged(address promoter, uint256 amount) external returns(bool); /// Get promoter total pledged balance. function pledged(address owner) external view returns(uint256); } // ---------------------------------------------------------------------------- /// @title Advertisement : Defines the sturcture of an advertisement. // ---------------------------------------------------------------------------- struct Advertisement { string link; string title; uint256 reach; uint256 reward; uint256 budget; uint256 created; uint256 expired; uint256 claimers; uint256 scamReport; address promoter; } // ---------------------------------------------------------------------------- /// @title SmACV1 : Smart Ads Contract [SmAC V1] Version 1. // ---------------------------------------------------------------------------- contract SmACV1 { // Define public constant variables. address PPeCAddress; // PPeC contract address. address public adCreatorAddress; // AdCreator [SmACCoror] address. uint256 public minClaimerBalance; // Holds minimum claimer balance needed before claiming rewards. uint256 public minReward; // Holds minimum reward required for each claim. uint256 promoterFee; // fee uint256 claimerFee; // fee Advertisement public Ads; // Holds the advertisement. mapping(address => mapping(address => bool)) claimed; // Holds each address claim status. // Set immutable values. constructor( address eoa, // eoa [externaly owned account] | [msg.sender] address PPeCAddress_, string memory link_, string memory title_, uint256 reach_, uint256 reward_, uint256 minReward_, uint256 claimerFee_, uint256 promoterFee_, uint256 minClaimerBalance_ ) { Ads.link = link_; Ads.title = title_; Ads.promoter = eoa; Ads.reach = reach_; Ads.budget = reach_ * reward_; Ads.reward = reward_; Ads.created = block.timestamp; Ads.expired = Ads.created + 15 days; Ads.claimers = 0; Ads.scamReport = 0; minReward = minReward_; claimerFee = claimerFee_; PPeCAddress = PPeCAddress_; promoterFee = promoterFee_; adCreatorAddress = msg.sender; minClaimerBalance = minClaimerBalance_; } // Events that will be emitted on changes. event Scam(); event Destroy(); event ScamReport(); event Claim(address indexed claimer, uint256 reward); event DelegateCleaner(address indexed claimer, uint256 reward); /// You have already claimed the reward. error Claimed(); /// You do not have enough tokens to claim rewards. error NotEnoughTokens(uint256 minBalance, uint256 balance); /// Reward exceed coffer balance. error NotEnoughReward(uint256 reward, uint256 coffer); /// The promotion has expired. error PromotionEnded(); /// The promotion has not expired. error PromotionRunning(); /// The promoter refund/claim date has not passed. error CannotClean(); /// @dev Make a function not callable by the founder nor the promoter. modifier notOwners() { require(msg.sender != Ads.promoter, "Your are the Promoter."); require(msg.sender != PPeC(PPeCAddress).founder(), "Your are the Founder."); _; } /// @dev Make a function callable only by the founder. modifier onlyFounder() { require(msg.sender == PPeC(PPeCAddress).founder(), "Your are not the Founder."); _; } /// @dev Make a function callable only by the promoter. modifier onlyPromoter() { require(msg.sender == Ads.promoter, "Your are not the Promoter."); _; } /// Claim rewards. // Before anyone can claim a reward, we must perform some checks: // 1. The promoter and the founded cannot claim rewards. // 2. A claimer can claim only once. // 3. A claimer must have a minimum amount of tokens. // 4. The coffer must have enough funds for the claim. // 5. The Ad have to be running, not expired. function claim() public notOwners { // Claimer balance. uint256 claimerBalance = PPeC(PPeCAddress).balanceOf(msg.sender); // Claimer claim status. bool claimedStatus = claimed[address(this)][msg.sender]; // Revert the call if the sender // already claimed the reward. if (claimedStatus == true) revert Claimed(); // Revert the call if the sender does not have // the minimum balance required for claiming rewards. if (minClaimerBalance > claimerBalance) revert NotEnoughTokens(minClaimerBalance, claimerBalance); // Revert the call if the reward exceeds or the budget // the coffer balance. if (Ads.reward > cofferBalance() || Ads.reward > Ads.budget) revert NotEnoughReward(Ads.reward, cofferBalance()); // Revert the call if the promotion is not running. if (block.timestamp > Ads.expired) revert PromotionEnded(); // Set claimer status to true [ claimed ☑ ]. claimed[address(this)][msg.sender] = true; // Increase claimers count. // Note: We only want to increase claimers count. Ads.claimers += 1; // Start the transfer. // see reusable function [_transfer(receiver, fee, reward, unPledged)] _transfer(msg.sender, claimerFee, Ads.reward, Ads.reward); // feedback. emit Claim(msg.sender, Ads.reward); } /// Claim leftover rewards after advertisement expires. // if/when an Ad did not run successfully for any reason // We want promoters to be able to claim their tokens back. // We have to make sure that the Ad has expired. function destroy() public onlyPromoter { // Revert the call if the promotion is still running. if (block.timestamp < Ads.expired) revert PromotionRunning(); // Checking if the promoter over/under funded the contract. _extraTokenCheck(Ads.promoter, promoterFee, cofferBalance()); // feedback. emit Destroy(); } /// Claim leftover tokens 4 days after advertisement expires, /// if the promoter fails to claim tokens from the expired advertisement. function delegateCleaner() public notOwners { // Revert the call if the promotion has // not passed 4 days AFTER expriration. if (block.timestamp < Ads.expired + 4 days) revert CannotClean(); // Checking if the promoter over/under funded the contract. _extraTokenCheck(msg.sender, claimerFee, cofferBalance()); // feedback. emit DelegateCleaner(msg.sender, cofferBalance()); } /// Empty the contract's tokens and make it harder for /// the promoter to advertise. // We have a big surprise for scammers! loss of funds. Don't do it. // Refrain from scamming others, and abide by all community rules my friend! function scam() public onlyFounder returns (bool success) { // Update pledged balance [The amount is too large for scammers to scam again]. SmACCor(adCreatorAddress).updatePledged(Ads.promoter, 10000000000E18); // Transfer tokens to the treasury. PPeC(PPeCAddress).transfer(PPeC(PPeCAddress).treasury(), cofferBalance()); // Reset budget Ads.budget = 0; // feedbacks. emit Scam(); return true; } /// Report this SmAC as a scam. function scamReport() public returns (bool reported) { // Claimer balance. uint256 claimerBalance = PPeC(PPeCAddress).balanceOf(msg.sender); // Claimer claim status. bool claimedStatus = claimed[address(this)][msg.sender]; // Revert the call if the sender // already claimed the reward or // reported the SmAC as a scam. if (claimedStatus == true) revert Claimed(); // Revert the call if the sender does not have // the minimum balance required for claiming rewards. if (minClaimerBalance > claimerBalance) revert NotEnoughTokens(minClaimerBalance, claimerBalance); // Revert the call if the promotion is not running. if (block.timestamp > Ads.expired) revert PromotionEnded(); // Set claimer status to true [ claimed ☑ ]. // Scam Reporter cannot claim this reward. claimed[address(this)][msg.sender] = true; // Increase report count. Ads.scamReport += 1; // feedbacks. emit ScamReport(); return true; } // Reusable function function _transfer(address receiver, uint256 fee, uint256 reward, uint256 unPledged) internal virtual returns(bool success) { // Let set fees for treasury and set receiver reward. uint256 treasuryShare = ((reward * 100) * fee) / 1000000; // fees uint256 receiverShare = reward - treasuryShare; // rewards // Set Pledged balance. uint256 pledged = SmACCor(adCreatorAddress).pledged(Ads.promoter); // Update pledged balance. SmACCor(adCreatorAddress).updatePledged(Ads.promoter, pledged - unPledged); // Reduce budget Ads.budget -= unPledged; // Transfer tokens. PPeC(PPeCAddress).transfer(PPeC(PPeCAddress).treasury(), treasuryShare); // send to treasury. PPeC(PPeCAddress).transfer(receiver, receiverShare); // send to caller. return true; } // Reusable function // Since we do not have a way to limit the promoter // from funding a contract, we have to check for discrepancies. // These checks will help us reduce the pledged amount appropriately. // 1. Check if the promoter over funded the contract. // 2. Check if the promoter under funded the contract. // 3. Check if the promoter correctly funded the contract. function _extraTokenCheck(address receiver, uint256 fee, uint256 balance) internal virtual { // set reward uint256 reward; // set extraToken - promoter extra tokens. uint256 extraToken; // set pledge - reduces the pledged balance. uint256 pledge; // Check if the promoter sent more tokens // to the contract than the budget required. if (balance > Ads.budget){ // set the extra tokens to exclude from fees. extraToken = balance - Ads.budget; // remove the extra tokens from the reward. reward = balance - extraToken; // set the pledged amount to be reduced by. pledge = reward; } // Check if the promoter sent less tokens // to the contract than the budget required. else if (balance < Ads.budget) { // set the extra tokens to exclude from fees. extraToken = 0; // set the reward to the balance. reward = balance; // set the pledged amount to be reduced by. pledge = Ads.budget; } // The promoter correctly funded the contract. else { // set the reward reward = balance; // no extra reward detected extraToken = 0; // set pledge pledge = balance; } // see reusable function [_transfer(receiver, fee, reward, pledge)] _transfer(receiver, fee, reward, pledge); // send the promoter the extra balance. PPeC(PPeCAddress).transfer(Ads.promoter, extraToken); } /// Get claimer's claim status. function claimStatus() public view returns(bool) { return claimed[address(this)][msg.sender]; } /// Get the contract [coffer] balance. function cofferBalance() public view returns(uint256) { return PPeC(PPeCAddress).balanceOf(address(this)); } /// Get the promoter's pledged balance. function pledgedBalance() public view returns(uint256) { return SmACCor(adCreatorAddress).pledged(Ads.promoter); } /// Get important advertisement information. function getInfo() public view returns(string memory, string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool, address) { return ( Ads.title, // ad title Ads.link, // ad link Ads.reach, // number of addresses to reward per click Ads.reward, // reward amount Ads.scamReport, // scam report count Ads.created, // created date Ads.expired, // expiration date Ads.claimers, // claimer count Ads.budget, // budget amount PPeC(PPeCAddress).balanceOf(address(this)), // coffer balance claimed[address(this)][msg.sender], // sender claim status Ads.promoter // promoter address ); } }
Claim rewards. Before anyone can claim a reward, we must perform some checks: 1. The promoter and the founded cannot claim rewards. 2. A claimer can claim only once. 3. A claimer must have a minimum amount of tokens. 4. The coffer must have enough funds for the claim. 5. The Ad have to be running, not expired. Claimer balance. Claimer claim status. Revert the call if the sender already claimed the reward. Revert the call if the sender does not have the minimum balance required for claiming rewards. Revert the call if the reward exceeds or the budget the coffer balance. Revert the call if the promotion is not running. Set claimer status to true [ claimed ☑ ]. Increase claimers count. Note: We only want to increase claimers count. Start the transfer. see reusable function [_transfer(receiver, fee, reward, unPledged)] feedback.
function claim() public notOwners { uint256 claimerBalance = PPeC(PPeCAddress).balanceOf(msg.sender); bool claimedStatus = claimed[address(this)][msg.sender]; if (claimedStatus == true) revert Claimed(); if (minClaimerBalance > claimerBalance) revert NotEnoughTokens(minClaimerBalance, claimerBalance); if (Ads.reward > cofferBalance() || Ads.reward > Ads.budget) revert NotEnoughReward(Ads.reward, cofferBalance()); if (block.timestamp > Ads.expired) revert PromotionEnded(); claimed[address(this)][msg.sender] = true; Ads.claimers += 1; _transfer(msg.sender, claimerFee, Ads.reward, Ads.reward); emit Claim(msg.sender, Ads.reward); }
12,804,922
./full_match/5/0xA5EA05358F4D65548cb04aeCC2C4a2381F573E9B/sources/contracts/MinerIssuance.sol
Issue exactly `exactMinerOut` Miner for no more than `maxAmountIn` of the selected token. @ dev Emits a SwappedTokenToMiner event if successful. path address[] The optimal path to take when swapping a token for ETH. Must be a valid ERC20-compatible token and the final token must be WETH. maxAmountIn uint256 The maximum amount of tokens to swap for Miner. Reverts if the minimum is not met. exactMinerOut uint256 The exact amount of Miner token to receive. deadline uint256 A timestamp indicating how long the swap will stay active. Reverts if expired. return uint256 The amount of Miner token swapped./
function issueExactMinerForTokens( address[] calldata path, uint256 maxAmountIn, uint256 exactMinerOut, uint256 deadline ) external returns (uint256) { IUniswapV2Router02 router = IUniswapV2Router02(uniswapRouter); uint256 requiredETHIn = _calculateMinerToETH(exactMinerOut); uint256 requiredTokensIn = router.getAmountsIn(requiredETHIn, path)[0]; require( requiredTokensIn <= maxAmountIn, "Issuance/excessive-amount-in" ); TransferHelper.safeTransferFrom( path[0], msg.sender, address(this), requiredTokensIn ); TransferHelper.safeApprove(path[0], uniswapRouter, requiredTokensIn); uint256 balanceBefore = payments(owner()); uint256[] memory amounts = router.swapTokensForExactETH( requiredETHIn, requiredTokensIn, path, address(this), deadline ); uint256 balanceAfter = payments(owner()); require( balanceAfter == balanceBefore + amounts[amounts.length - 1], "Issuance/invalid-eth-amount" ); MinerReserve(reserve).issue(_msgSender(), exactMinerOut); emit Issued(_msgSender(), reserve, requiredTokensIn, exactMinerOut); return exactMinerOut; }
7,034,076
pragma solidity >=0.4.21 <0.6.0; contract ArtWarehouse { // define a Pictureobject. Each picture will be stored as this on the blockchain struct Picture { int id; string link; int worth; address owner; } // define an associated array for listing all pictures in dependece of the pictureId mapping(int => Picture) public pictureList; // Store Pictures Count int public picturesCount; // constructor. Will be called when the SmartContract is migrated to the Blockchain only once constructor () public { picturesCount = 0; } // function for adding a picture to the blockchain. Will be called from the app.js function addPicture (string memory link) public { // boolean used to determine if a picture has already been uploaded bool used = false; // iterate through all stored pictures for (int i = 0; i <= picturesCount; i++) { // compare the names of a picture if(compareLinks(link, pictureList[i].link) == true){ // if picture is already existing set boolean to true used = true; } } // require the boolean used to be false. Otherwise the picture won't be stored a failure will be returned require(used == false, "Bild bereits vorhanden!"); // if picture is valid the pictureCount will be added by 1 picturesCount ++; // the new picture will be written to the blockchain with the new picturesCount value as ID pictureList[picturesCount] = Picture(picturesCount, link, 0, msg.sender); // Event emmitten emit pictureUpload(msg.sender, picturesCount, link); } // function for setting the worth of a picture. Will be called from app.js function setWorth (int pictureID, int worth) public { // require a valid picture require((pictureID > 0 && pictureID <= picturesCount && worth <= 10 && worth >= 0), "ID nicht gültig."); // update pictures worth pictureList[pictureID].worth = worth; } // function for comparing the pictures names. Strings can't be compared in without hashing the strings function compareLinks (string memory a, string memory b) private pure returns (bool) { if(keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b))){ return true; }else{ return false; } } // this event will be emitted when a new picture has been added. Will be watched by the oraclePattern in app.js, which will then be fired event pictureUpload (address indexed sid, int pictureId, string link); }
function for adding a picture to the blockchain. Will be called from the app.js boolean used to determine if a picture has already been uploaded iterate through all stored pictures compare the names of a picture if picture is already existing set boolean to true
function addPicture (string memory link) public { bool used = false; for (int i = 0; i <= picturesCount; i++) { if(compareLinks(link, pictureList[i].link) == true){ used = true; } } }
12,708,953
./full_match/5/0x507092d20022999DC3179EF6E959B7A5da784f09/sources/project_/contracts/ProxyFactory.sol
This deploys an extremely minimalist proxy contract with the mainAddress embedded within. Note: The bytecode is explained in comments below this contract. return dst The new contract address./ copy init code into memory and immutable ExchangeDeposit address onto stack Get the position of the start of init code grab the first 32 bytes shift the address bytes 8 bits left bitwise OR them and add the address into the init code memory create the contract revert if failed
function deployNewInstance(bytes32 salt) external returns (address dst) { bytes memory initCodeMem = INIT_CODE; address payable addrStack = mainAddress; assembly { let pos := add(initCodeMem, 0x20) let first32 := mload(pos) let addrBytesShifted := shl(8, addrStack) mstore(pos, or(first32, addrBytesShifted)) dst := create2( ) if eq(dst, 0) { revert(0, 0) } } }
1,876,296
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: ICurveFi interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // stETH pool uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount, bool use_underlying ) external; function add_liquidity( // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount, bool use_underlying ) external; function add_liquidity( // stETH pool uint256[2] calldata amounts, uint256 min_mint_amount, bool use_underlying ) external payable; function coins(uint256) external returns (address); function underlying_coins(uint256) external returns (address); function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function calc_withdraw_one_coin(uint256 _amount, int128 i) external view returns (uint256); function calc_withdraw_one_coin(uint256 _amount, int128 i, bool use_underlying) external view returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount, bool use_underlying ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external payable; function balances(int128) external view returns (uint256); function get_dy( int128 from, int128 to, uint256 _from_amount ) external view returns (uint256); function calc_token_amount( uint256[2] calldata amounts, bool is_deposit) external view returns (uint256); function calc_token_amount( uint256[3] calldata amounts, bool is_deposit) external view returns (uint256); function calc_token_amount( uint256[4] calldata amounts, bool is_deposit) external view returns (uint256); } // Part: IERC20Extended interface IERC20Extended{ function decimals() external view returns (uint8); function name() external view returns (string memory); function symbol() external view returns (string memory); } // Part: IUni interface IUni { function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: ICrvV3 interface ICrvV3 is IERC20 { function minter() external view returns (address); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.5"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: Strategy.sol // Import interfaces for many popular DeFi projects, or add your own! //import "../interfaces/<protocol>/<Interface>.sol"; contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; ICurveFi public curvePool;// = ICurveFi(address(0x4CA9b3063Ec5866A4B82E437059D2C43d1be596F)); ICrvV3 public curveToken;// = ICrvV3(address(0xb19059ebb43466C323583928285a49f558E572Fd)); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); VaultAPI public yvToken;// = IVaultV1(address(0x46AFc2dfBd1ea0c0760CAD8262A5838e803A37e5)); //IERC20Extended public middleToken; // the token between bluechip and curve pool uint256 public lastInvest = 0; uint256 public minTimePerInvest;// = 3600; uint256 public maxSingleInvest;// // 2 hbtc per hour default uint256 public slippageProtectionIn;// = 50; //out of 10000. 50 = 0.5% uint256 public slippageProtectionOut;// = 50; //out of 10000. 50 = 0.5% uint256 public constant DENOMINATOR = 10000; uint8 private want_decimals; uint8 private middle_decimals; int128 public curveId; uint256 public poolSize; bool public hasUnderlying; bool public withdrawProtection; constructor( address _vault, uint256 _maxSingleInvest, uint256 _minTimePerInvest, uint256 _slippageProtectionIn, address _curvePool, address _curveToken, address _yvToken, uint256 _poolSize, bool _hasUnderlying ) public BaseStrategy(_vault) { _initializeStrat(_maxSingleInvest, _minTimePerInvest, _slippageProtectionIn, _curvePool, _curveToken, _yvToken, _poolSize, _hasUnderlying); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, uint256 _maxSingleInvest, uint256 _minTimePerInvest, uint256 _slippageProtectionIn, address _curvePool, address _curveToken, address _yvToken, uint256 _poolSize, bool _hasUnderlying ) external { //note: initialise can only be called once. in _initialize in BaseStrategy we have: require(address(want) == address(0), "Strategy already initialized"); _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_maxSingleInvest, _minTimePerInvest, _slippageProtectionIn, _curvePool, _curveToken, _yvToken, _poolSize, _hasUnderlying); } function _initializeStrat( uint256 _maxSingleInvest, uint256 _minTimePerInvest, uint256 _slippageProtectionIn, address _curvePool, address _curveToken, address _yvToken, uint256 _poolSize, bool _hasUnderlying ) internal { require(want_decimals == 0, "Already Initialized"); require(_poolSize > 1 && _poolSize < 5, "incorrect pool size"); curvePool = ICurveFi(_curvePool); if(curvePool.coins(0) == address(want) || (_hasUnderlying && curvePool.underlying_coins(0) == address(want) )){ curveId =0; }else if ( curvePool.coins(1) == address(want) || (_hasUnderlying && curvePool.underlying_coins(1) == address(want) )){ curveId =1; }else if ( curvePool.coins(2) == address(want) || (_hasUnderlying && curvePool.underlying_coins(2) == address(want) )){ curveId =2; }else if ( curvePool.coins(3) == address(want) || (_hasUnderlying && curvePool.underlying_coins(3) == address(want) )){ //will revert if there are not enough coins curveId =3; }else{ require(false, "incorrect want for curve pool"); } /*if(_hasUnderlying){ middleToken = IERC20Extended(curvePool.coins(uint256(curveId))); middle_decimals = middleToken.decimals(); }*/ maxSingleInvest = _maxSingleInvest; minTimePerInvest = _minTimePerInvest; slippageProtectionIn = _slippageProtectionIn; slippageProtectionOut = _slippageProtectionIn; // use In to start with to save on stack poolSize = _poolSize; hasUnderlying = _hasUnderlying; yvToken = VaultAPI(_yvToken); curveToken = ICrvV3(_curveToken); _setupStatics(); } function _setupStatics() internal { maxReportDelay = 86400; profitFactor = 1500; minReportDelay = 3600; debtThreshold = 100*1e18; withdrawProtection = true; want_decimals = IERC20Extended(address(want)).decimals(); want.safeApprove(address(curvePool), uint256(-1)); curveToken.approve(address(yvToken), uint256(-1)); } event Cloned(address indexed clone); function cloneSingleSidedCurve( address _vault, address _strategist, address _rewards, address _keeper, uint256 _maxSingleInvest, uint256 _minTimePerInvest, uint256 _slippageProtectionIn, address _curvePool, address _curveToken, address _yvToken, uint256 _poolSize, bool _hasUnderlying ) external returns (address newStrategy){ bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper, _maxSingleInvest, _minTimePerInvest, _slippageProtectionIn, _curvePool, _curveToken, _yvToken, _poolSize, _hasUnderlying); emit Cloned(newStrategy); } function name() external override view returns (string memory) { return string(abi.encodePacked("SingleSidedCrv", IERC20Extended(address(want)).symbol())); } function updateMinTimePerInvest(uint256 _minTimePerInvest) public onlyGovernance { minTimePerInvest = _minTimePerInvest; } function updateMaxSingleInvest(uint256 _maxSingleInvest) public onlyGovernance { maxSingleInvest = _maxSingleInvest; } function updateSlippageProtectionIn(uint256 _slippageProtectionIn) public onlyGovernance { slippageProtectionIn = _slippageProtectionIn; } function updateSlippageProtectionOut(uint256 _slippageProtectionOut) public onlyGovernance { slippageProtectionOut = _slippageProtectionOut; } function delegatedAssets() public override view returns (uint256) { return Math.min(curveTokenToWant(curveTokensInYVault()), vault.strategies(address(this)).totalDebt); } function estimatedTotalAssets() public override view returns (uint256) { uint256 totalCurveTokens = curveTokensInYVault().add(curveToken.balanceOf(address(this))); return want.balanceOf(address(this)).add(curveTokenToWant(totalCurveTokens)); } // returns value of total function curveTokenToWant(uint256 tokens) public view returns (uint256) { if(tokens == 0){ return 0; } //we want to choose lower value of virtual price and amount we really get out //this means we will always underestimate current assets. uint256 virtualOut = virtualPriceToWant().mul(tokens).div(1e18); /*uint256 realOut; if(hasUnderlying){ realOut = curvePool.calc_withdraw_one_coin(tokens, curveId, true); }else{ realOut = curvePool.calc_withdraw_one_coin(tokens, curveId); }*/ //return Math.min(virtualOut, realOut); return virtualOut; } //we lose some precision here. but it shouldnt matter as we are underestimating function virtualPriceToWant() public view returns (uint256) { if(want_decimals < 18){ return curvePool.get_virtual_price().div(10 ** (uint256(uint8(18) - want_decimals))); }else{ return curvePool.get_virtual_price(); } } /*function virtualPriceToMiddle() public view returns (uint256) { if(middle_decimals < 18){ return curvePool.get_virtual_price().div(10 ** (uint256(uint8(18) - middle_decimals))); }else{ return curvePool.get_virtual_price(); } }*/ function curveTokensInYVault() public view returns (uint256) { uint256 balance = yvToken.balanceOf(address(this)); if(yvToken.totalSupply() == 0){ //needed because of revert on priceperfullshare if 0 return 0; } uint256 pricePerShare = yvToken.pricePerShare(); //curve tokens are 1e18 decimals return balance.mul(pricePerShare).div(1e18); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _debtPayment = _debtOutstanding; uint256 debt = vault.strategies(address(this)).totalDebt; uint256 currentValue = estimatedTotalAssets(); uint256 wantBalance = want.balanceOf(address(this)); if(debt < currentValue){ //profit _profit = currentValue.sub(debt); }else{ _loss = debt.sub(currentValue); } uint256 toFree = _debtPayment.add(_profit); if(toFree > wantBalance){ toFree = toFree.sub(wantBalance); (, uint256 withdrawalLoss) = withdrawSome(toFree); //when we withdraw we can lose money in the withdrawal if(withdrawalLoss < _profit){ _profit = _profit.sub(withdrawalLoss); }else{ _loss = _loss.add(withdrawalLoss.sub(_profit)); _profit = 0; } wantBalance = want.balanceOf(address(this)); if(wantBalance < _profit){ _profit = wantBalance; _debtPayment = 0; }else if (wantBalance < _debtPayment.add(_profit)){ _debtPayment = wantBalance.sub(_profit); } } } function harvestTrigger(uint256 callCost) public view override returns (bool) { uint256 wantCallCost; if (address(want) == weth) { wantCallCost = callCost; } else { wantCallCost = _ethToWant(callCost); } return super.harvestTrigger(wantCallCost); } function _ethToWant(uint256 _amount) internal view returns (uint256) { address[] memory path = new address[](2); path[0] = weth; path[1] = address(want); uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } function tendTrigger(uint256 callCost) public override view returns (bool) { uint256 wantBal = want.balanceOf(address(this)); uint256 _wantToInvest = Math.min(wantBal, maxSingleInvest); if(lastInvest.add(minTimePerInvest) < block.timestamp && _wantToInvest > 1 && _checkSlip(_wantToInvest)){ //return true; } } function _checkSlip(uint256 _wantToInvest) public view returns (bool){ return true; /* //convertToMiddle if(hasUnderlying){ if(want_decimals > middle_decimals){ _wantToInvest = _wantToInvest.div(10 ** uint256(want_decimals - middle_decimals)); }else if (want_decimals < middle_decimals){ _wantToInvest = _wantToInvest.mul(10 ** uint256(middle_decimals - want_decimals)); } } uint256 vp = virtualPriceToWant(); uint256 expectedOut = _wantToInvest.mul(1e18).div(vp); uint256 maxSlip = expectedOut.mul(DENOMINATOR.sub(slippageProtectionIn)).div(DENOMINATOR); uint256 roughOut; if(poolSize == 2){ uint256[2] memory amounts; amounts[uint256(curveId)] = _wantToInvest; //note doesnt take into account underlying roughOut = curvePool.calc_token_amount(amounts, true); }else if (poolSize == 3){ uint256[3] memory amounts; amounts[uint256(curveId)] = _wantToInvest; //note doesnt take into account underlying roughOut = curvePool.calc_token_amount(amounts, true); }else{ uint256[4] memory amounts; amounts[uint256(curveId)] = _wantToInvest; //note doesnt take into account underlying roughOut = curvePool.calc_token_amount(amounts, true); } if(roughOut >= maxSlip){ return true; }*/ } function adjustPosition(uint256 _debtOutstanding) internal override { if(lastInvest.add(minTimePerInvest) > block.timestamp ){ return; } // Invest the rest of the want uint256 _wantToInvest = Math.min(want.balanceOf(address(this)), maxSingleInvest); if (_wantToInvest > 0) { //add to curve (single sided) if(_checkSlip(_wantToInvest)){ uint256 expectedOut = _wantToInvest.mul(1e18).div(virtualPriceToWant()); uint256 maxSlip = expectedOut.mul(DENOMINATOR.sub(slippageProtectionIn)).div(DENOMINATOR); //pool size cannot be more than 4 or less than 2 if(poolSize == 2){ uint256[2] memory amounts; amounts[uint256(curveId)] = _wantToInvest; if(hasUnderlying){ curvePool.add_liquidity(amounts, maxSlip, true); }else{ curvePool.add_liquidity(amounts, maxSlip); } }else if (poolSize == 3){ uint256[3] memory amounts; amounts[uint256(curveId)] = _wantToInvest; if(hasUnderlying){ curvePool.add_liquidity(amounts, maxSlip, true); }else{ curvePool.add_liquidity(amounts, maxSlip); } }else{ uint256[4] memory amounts; amounts[uint256(curveId)] = _wantToInvest; if(hasUnderlying){ curvePool.add_liquidity(amounts, maxSlip, true); }else{ curvePool.add_liquidity(amounts, maxSlip); } } //now add to yearn yvToken.deposit(); lastInvest = block.timestamp; }else{ require(false, "quee"); } /*if(curveId == 0){ amounts = [_wantToInvest, 0]; }else{ amounts = [0, _wantToInvest]; }*/ } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 wantBal = want.balanceOf(address(this)); if(wantBal < _amountNeeded){ (_liquidatedAmount, _loss) = withdrawSome(_amountNeeded.sub(wantBal)); } _liquidatedAmount = Math.min(_amountNeeded, _liquidatedAmount.add(wantBal)); } //safe to enter more than we have function withdrawSome(uint256 _amount) internal returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 wantBalanceBefore = want.balanceOf(address(this)); //let's take the amount we need if virtual price is real. Let's add the uint256 virtualPrice = virtualPriceToWant(); uint256 amountWeNeedFromVirtualPrice = _amount.mul(1e18).div(virtualPrice); uint256 crvBeforeBalance = curveToken.balanceOf(address(this)); //should be zero but just incase... uint256 pricePerFullShare = yvToken.pricePerShare(); uint256 amountFromVault = amountWeNeedFromVirtualPrice.mul(1e18).div(pricePerFullShare); uint256 yBalance = yvToken.balanceOf(address(this)); if(amountFromVault > yBalance){ amountFromVault = yBalance; //this is not loss. so we amend amount uint256 _amountOfCrv = amountFromVault.mul(pricePerFullShare).div(1e18); _amount = _amountOfCrv.mul(virtualPrice).div(1e18); } yvToken.withdraw(amountFromVault); if(withdrawProtection){ //this tests that we liquidated all of the expected ytokens. Without it if we get back less then will mark it is loss require(yBalance.sub(yvToken.balanceOf(address(this))) >= amountFromVault.sub(1), "YVAULTWITHDRAWFAILED"); } uint256 toWithdraw = curveToken.balanceOf(address(this)).sub(crvBeforeBalance); //if we have less than 18 decimals we need to lower the amount out uint256 maxSlippage = toWithdraw.mul(DENOMINATOR.sub(slippageProtectionOut)).div(DENOMINATOR); if(want_decimals < 18){ maxSlippage = maxSlippage.div(10 ** (uint256(uint8(18) - want_decimals))); } if(hasUnderlying){ curvePool.remove_liquidity_one_coin(toWithdraw, curveId, maxSlippage, true); }else{ curvePool.remove_liquidity_one_coin(toWithdraw, curveId, maxSlippage); } uint256 diff = want.balanceOf(address(this)).sub(wantBalanceBefore); if(diff > _amount){ _liquidatedAmount = _amount; }else{ _liquidatedAmount = diff; _loss = _amount.sub(diff); } } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { yvToken.transfer(_newStrategy, yvToken.balanceOf(address(this))); } // Override this to add all tokens/tokenized positions this contract manages // on a *persistent* basis (e.g. not just for swapping back to want ephemerally) // NOTE: Do *not* include `want`, already included in `sweep` below // // Example: // // function protectedTokens() internal override view returns (address[] memory) { // address[] memory protected = new address[](3); // protected[0] = tokenA; // protected[1] = tokenB; // protected[2] = tokenC; // return protected; // } function protectedTokens() internal override view returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = address(yvToken); return protected; } }
sBTC pool bUSD pool stETH pool sBTC pool bUSD pool stETH pool
interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( uint256[4] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount, bool use_underlying ) external; function add_liquidity( uint256[4] calldata amounts, uint256 min_mint_amount, bool use_underlying ) external; function add_liquidity( uint256[2] calldata amounts, uint256 min_mint_amount, bool use_underlying ) external payable; function coins(uint256) external returns (address); function underlying_coins(uint256) external returns (address); function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function calc_withdraw_one_coin(uint256 _amount, int128 i) external view returns (uint256); function calc_withdraw_one_coin(uint256 _amount, int128 i, bool use_underlying) external view returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount, bool use_underlying ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external payable; function balances(int128) external view returns (uint256); function get_dy( int128 from, int128 to, uint256 _from_amount ) external view returns (uint256); function calc_token_amount( uint256[2] calldata amounts, bool is_deposit) external view returns (uint256); function calc_token_amount( uint256[3] calldata amounts, bool is_deposit) external view returns (uint256); function calc_token_amount( uint256[4] calldata amounts, bool is_deposit) external view returns (uint256); }
575,082
pragma solidity 0.5.16; 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 IBoostedVaultWithLockup { /** * @dev Stakes a given amount of the StakingToken for the sender * @param _amount Units of StakingToken */ function stake(uint256 _amount) external; /** * @dev Stakes a given amount of the StakingToken for a given beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function stake(address _beneficiary, uint256 _amount) external; /** * @dev Withdraws stake from pool and claims any unlocked rewards. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function exit() external; /** * @dev Withdraws stake from pool and claims any unlocked rewards. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function exit(uint256 _first, uint256 _last) external; /** * @dev Withdraws given stake amount from the pool * @param _amount Units of the staked token to withdraw */ function withdraw(uint256 _amount) external; /** * @dev Claims only the tokens that have been immediately unlocked, not including * those that are in the lockers. */ function claimReward() external; /** * @dev Claims all unlocked rewards for sender. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function claimRewards() external; /** * @dev Claims all unlocked rewards for sender. Both immediately unlocked * rewards and also locked rewards past their time lock. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function claimRewards(uint256 _first, uint256 _last) external; /** * @dev Pokes a given account to reset the boost */ function pokeBoost(address _account) external; /** * @dev Gets the RewardsToken */ function getRewardToken() external view returns (IERC20); /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() external view returns (uint256); /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @return 'Reward' per staked token */ function rewardPerToken() external view returns (uint256); /** * @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this * does NOT include the majority of rewards which will be locked up. * @param _account User address * @return Total reward amount earned */ function earned(address _account) external view returns (uint256); /** * @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards * and those that have passed their time lock. * @param _account User address * @return amount Total units of unclaimed rewards * @return first Index of the first userReward that has unlocked * @return last Index of the last userReward that has unlocked */ function unclaimedRewards(address _account) external view returns ( uint256 amount, uint256 first, uint256 last ); } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } contract InitializableModule2 is ModuleKeys { INexus public constant nexus = INexus(0xAFcE80b19A8cE13DEc0739a1aaB7A028d6845Eb3); /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { require(msg.sender == _governor(), "Only governor can execute"); _; } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } interface IRewardsDistributionRecipient { function notifyRewardAmount(uint256 reward) external; function getRewardToken() external view returns (IERC20); } contract InitializableRewardsDistributionRecipient is IRewardsDistributionRecipient, InitializableModule2 { // @abstract function notifyRewardAmount(uint256 reward) external; function getRewardToken() external view returns (IERC20); // This address has the ability to distribute the rewards address public rewardsDistributor; /** @dev Recipient is a module, governed by mStable governance */ function _initialize(address _rewardsDistributor) internal { rewardsDistributor = _rewardsDistributor; } /** * @dev Only the rewards distributor can notify about rewards */ modifier onlyRewardsDistributor() { require(msg.sender == rewardsDistributor, "Caller is not reward distributor"); _; } /** * @dev Change the rewardsDistributor - only called by mStable governor * @param _rewardsDistributor Address of the new distributor */ function setRewardsDistribution(address _rewardsDistributor) external onlyGovernor { rewardsDistributor = _rewardsDistributor; } } contract IERC20WithCheckpointing { function balanceOf(address _owner) public view returns (uint256); function balanceOfAt(address _owner, uint256 _blockNumber) public view returns (uint256); function totalSupply() public view returns (uint256); function totalSupplyAt(uint256 _blockNumber) public view returns (uint256); } contract IIncentivisedVotingLockup is IERC20WithCheckpointing { function getLastUserPoint(address _addr) external view returns ( int128 bias, int128 slope, uint256 ts ); function createLock(uint256 _value, uint256 _unlockTime) external; function withdraw() external; function increaseLockAmount(uint256 _value) external; function increaseLockLength(uint256 _unlockTime) external; function eject(address _user) external; function expireContract() external; function claimReward() public; function earned(address _account) public view returns (uint256); } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ /** * @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"); } } 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"); } } } contract InitializableReentrancyGuard { bool private _notEntered; function _initialize() 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; } } library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * @dev bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x.mul(FULL_SCALE); } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x.mul(ratio); // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled.add(RATIO_SCALE.sub(1)); // return 100..00.999e8 / 1e8 = 1e18 return ceil.div(RATIO_SCALE); } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 uint256 y = x.mul(RATIO_SCALE); // return 1e22 / 1e12 = 1e10 return y.div(ratio); } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } library Root { using SafeMath for uint256; /** * @dev Returns the square root of a given number * @param x Input * @return y Square root of Input */ function sqrt(uint256 x) internal pure returns (uint256 y) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; // Seven iterations should be enough uint256 r1 = x.div(r); return uint256(r < r1 ? r : r1); } } } interface IBoostDirector { function getBalance(address _user) external returns (uint256); function setDirection( address _old, address _new, bool _pokeNew ) external; function whitelistVaults(address[] calldata _vaults) external; } contract BoostedTokenWrapper is InitializableReentrancyGuard { using SafeMath for uint256; using StableMath for uint256; using SafeERC20 for IERC20; IERC20 public constant stakingToken = IERC20(0x30647a72Dc82d7Fbb1123EA74716aB8A317Eac19); // mStable MTA Staking contract via the BoostDirectorV2 IBoostDirector public constant boostDirector = IBoostDirector(0xBa05FD2f20AE15B0D3f20DDc6870FeCa6ACd3592); uint256 private _totalBoostedSupply; mapping(address => uint256) private _boostedBalances; mapping(address => uint256) private _rawBalances; // Vars for use in the boost calculations uint256 private constant MIN_DEPOSIT = 1e18; uint256 private constant MAX_VMTA = 600000e18; uint256 private constant MAX_BOOST = 3e18; uint256 private constant MIN_BOOST = 1e18; uint256 private constant FLOOR = 98e16; uint256 public constant boostCoeff = 9; uint256 public constant priceCoeff = 1e17; /** * @dev TokenWrapper constructor **/ function _initialize() internal { InitializableReentrancyGuard._initialize(); } /** * @dev Get the total boosted amount * @return uint256 total supply */ function totalSupply() public view returns (uint256) { return _totalBoostedSupply; } /** * @dev Get the boosted balance of a given account * @param _account User for which to retrieve balance */ function balanceOf(address _account) public view returns (uint256) { return _boostedBalances[_account]; } /** * @dev Get the RAW balance of a given account * @param _account User for which to retrieve balance */ function rawBalanceOf(address _account) public view returns (uint256) { return _rawBalances[_account]; } /** * @dev Read the boost for the given address * @param _account User for which to return the boost * @return boost where 1x == 1e18 */ function getBoost(address _account) public view returns (uint256) { return balanceOf(_account).divPrecisely(rawBalanceOf(_account)); } /** * @dev Deposits a given amount of StakingToken from sender * @param _amount Units of StakingToken */ function _stakeRaw(address _beneficiary, uint256 _amount) internal nonReentrant { _rawBalances[_beneficiary] = _rawBalances[_beneficiary].add(_amount); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); } /** * @dev Withdraws a given stake from sender * @param _amount Units of StakingToken */ function _withdrawRaw(uint256 _amount) internal nonReentrant { _rawBalances[msg.sender] = _rawBalances[msg.sender].sub(_amount); stakingToken.safeTransfer(msg.sender, _amount); } /** * @dev Updates the boost for the given address according to the formula * boost = min(0.5 + c * vMTA_balance / imUSD_locked^(7/8), 1.5) * If rawBalance <= MIN_DEPOSIT, boost is 0 * @param _account User for which to update the boost */ function _setBoost(address _account) internal { uint256 rawBalance = _rawBalances[_account]; uint256 boostedBalance = _boostedBalances[_account]; uint256 boost = MIN_BOOST; // Check whether balance is sufficient // is_boosted is used to minimize gas usage uint256 scaledBalance = (rawBalance * priceCoeff) / 1e18; if (rawBalance >= MIN_DEPOSIT) { uint256 votingWeight = boostDirector.getBalance(_account); boost = _computeBoost(scaledBalance, votingWeight); } uint256 newBoostedBalance = rawBalance.mulTruncate(boost); if (newBoostedBalance != boostedBalance) { _totalBoostedSupply = _totalBoostedSupply.sub(boostedBalance).add(newBoostedBalance); _boostedBalances[_account] = newBoostedBalance; } } /** * @dev Computes the boost for * boost = min(m, max(1, 0.95 + c * min(voting_weight, f) / deposit^(3/4))) * @param _scaledDeposit deposit amount in terms of USD */ function _computeBoost(uint256 _scaledDeposit, uint256 _votingWeight) private view returns (uint256 boost) { if (_votingWeight == 0) return MIN_BOOST; // Compute balance to the power 3/4 uint256 sqrt1 = Root.sqrt(_scaledDeposit * 1e6); uint256 sqrt2 = Root.sqrt(sqrt1); uint256 denominator = sqrt1 * sqrt2; boost = (((StableMath.min(_votingWeight, MAX_VMTA) * boostCoeff) / 10) * 1e18) / denominator; boost = StableMath.min(MAX_BOOST, StableMath.max(MIN_BOOST, FLOOR + boost)); } } contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require( initializing || isConstructor() || !initialized, "Contract instance has already been initialized" ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } } // Internal // Libs /** * @title BoostedSavingsVault * @author Stability Labs Pty. Ltd. * @notice Accrues rewards second by second, based on a users boosted balance * @dev Forked from rewards/staking/StakingRewards.sol * Changes: * - Lockup implemented in `updateReward` hook (20% unlock immediately, 80% locked for 6 months) * - `updateBoost` hook called after every external action to reset a users boost * - Struct packing of common data * - Searching for and claiming of unlocked rewards */ contract BoostedSavingsVault is IBoostedVaultWithLockup, Initializable, InitializableRewardsDistributionRecipient, BoostedTokenWrapper { using StableMath for uint256; using SafeCast for uint256; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount, address payer); event Withdrawn(address indexed user, uint256 amount); event Poked(address indexed user); event RewardPaid(address indexed user, uint256 reward); IERC20 public constant rewardsToken = IERC20(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2); uint64 public constant DURATION = 7 days; // Length of token lockup, after rewards are earned uint256 public constant LOCKUP = 26 weeks; // Percentage of earned tokens unlocked immediately uint64 public constant UNLOCK = 2e17; // Timestamp for current period finish uint256 public periodFinish; // RewardRate for the rest of the PERIOD uint256 public rewardRate; // Last time any user took action uint256 public lastUpdateTime; // Ever increasing rewardPerToken rate, based on % of total supply uint256 public rewardPerTokenStored; mapping(address => UserData) public userData; // Locked reward tracking mapping(address => Reward[]) public userRewards; mapping(address => uint64) public userClaim; struct UserData { uint128 rewardPerTokenPaid; uint128 rewards; uint64 lastAction; uint64 rewardCount; } struct Reward { uint64 start; uint64 finish; uint128 rate; } /** * @dev StakingRewards is a TokenWrapper and RewardRecipient * Constants added to bytecode at deployTime to reduce SLOAD cost */ function initialize(address _rewardsDistributor) external initializer { InitializableRewardsDistributionRecipient._initialize(_rewardsDistributor); BoostedTokenWrapper._initialize(); } /** * @dev Updates the reward for a given address, before executing function. * Locks 80% of new rewards up for 6 months, vesting linearly from (time of last action + 6 months) to * (now + 6 months). This allows rewards to be distributed close to how they were accrued, as opposed * to locking up for a flat 6 months from the time of this fn call (allowing more passive accrual). */ modifier updateReward(address _account) { _updateReward(_account); _; } function _updateReward(address _account) internal { uint256 currentTime = block.timestamp; uint64 currentTime64 = SafeCast.toUint64(currentTime); // Setting of global vars (uint256 newRewardPerToken, uint256 lastApplicableTime) = _rewardPerToken(); // If statement protects against loss in initialisation case if (newRewardPerToken > 0) { rewardPerTokenStored = newRewardPerToken; lastUpdateTime = lastApplicableTime; // Setting of personal vars based on new globals if (_account != address(0)) { UserData memory data = userData[_account]; uint256 earned = _earned(_account, data.rewardPerTokenPaid, newRewardPerToken); // If earned == 0, then it must either be the initial stake, or an action in the // same block, since new rewards unlock after each block. if (earned > 0) { uint256 unlocked = earned.mulTruncate(UNLOCK); uint256 locked = earned.sub(unlocked); userRewards[_account].push( Reward({ start: SafeCast.toUint64(LOCKUP.add(data.lastAction)), finish: SafeCast.toUint64(LOCKUP.add(currentTime)), rate: SafeCast.toUint128(locked.div(currentTime.sub(data.lastAction))) }) ); userData[_account] = UserData({ rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken), rewards: SafeCast.toUint128(unlocked.add(data.rewards)), lastAction: currentTime64, rewardCount: data.rewardCount + 1 }); } else { userData[_account] = UserData({ rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken), rewards: data.rewards, lastAction: currentTime64, rewardCount: data.rewardCount }); } } } else if (_account != address(0)) { // This should only be hit once, for first staker in initialisation case userData[_account].lastAction = currentTime64; } } /** @dev Updates the boost for a given address, after the rest of the function has executed */ modifier updateBoost(address _account) { _; _setBoost(_account); } /*************************************** ACTIONS - EXTERNAL ****************************************/ /** * @dev Stakes a given amount of the StakingToken for the sender * @param _amount Units of StakingToken */ function stake(uint256 _amount) external updateReward(msg.sender) updateBoost(msg.sender) { _stake(msg.sender, _amount); } /** * @dev Stakes a given amount of the StakingToken for a given beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function stake(address _beneficiary, uint256 _amount) external updateReward(_beneficiary) updateBoost(_beneficiary) { _stake(_beneficiary, _amount); } /** * @dev Withdraws stake from pool and claims any unlocked rewards. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function exit() external updateReward(msg.sender) updateBoost(msg.sender) { _withdraw(rawBalanceOf(msg.sender)); (uint256 first, uint256 last) = _unclaimedEpochs(msg.sender); _claimRewards(first, last); } /** * @dev Withdraws stake from pool and claims any unlocked rewards. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function exit(uint256 _first, uint256 _last) external updateReward(msg.sender) updateBoost(msg.sender) { _withdraw(rawBalanceOf(msg.sender)); _claimRewards(_first, _last); } /** * @dev Withdraws given stake amount from the pool * @param _amount Units of the staked token to withdraw */ function withdraw(uint256 _amount) external updateReward(msg.sender) updateBoost(msg.sender) { _withdraw(_amount); } /** * @dev Claims only the tokens that have been immediately unlocked, not including * those that are in the lockers. */ function claimReward() external updateReward(msg.sender) updateBoost(msg.sender) { uint256 unlocked = userData[msg.sender].rewards; userData[msg.sender].rewards = 0; if (unlocked > 0) { rewardsToken.safeTransfer(msg.sender, unlocked); emit RewardPaid(msg.sender, unlocked); } } /** * @dev Claims all unlocked rewards for sender. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function claimRewards() external updateReward(msg.sender) updateBoost(msg.sender) { (uint256 first, uint256 last) = _unclaimedEpochs(msg.sender); _claimRewards(first, last); } /** * @dev Claims all unlocked rewards for sender. Both immediately unlocked * rewards and also locked rewards past their time lock. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function claimRewards(uint256 _first, uint256 _last) external updateReward(msg.sender) updateBoost(msg.sender) { _claimRewards(_first, _last); } /** * @dev Pokes a given account to reset the boost */ function pokeBoost(address _account) external updateReward(_account) updateBoost(_account) { emit Poked(_account); } /*************************************** ACTIONS - INTERNAL ****************************************/ /** * @dev Claims all unlocked rewards for sender. Both immediately unlocked * rewards and also locked rewards past their time lock. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function _claimRewards(uint256 _first, uint256 _last) internal { (uint256 unclaimed, uint256 lastTimestamp) = _unclaimedRewards(msg.sender, _first, _last); userClaim[msg.sender] = uint64(lastTimestamp); uint256 unlocked = userData[msg.sender].rewards; userData[msg.sender].rewards = 0; uint256 total = unclaimed.add(unlocked); if (total > 0) { rewardsToken.safeTransfer(msg.sender, total); emit RewardPaid(msg.sender, total); } } /** * @dev Internally stakes an amount by depositing from sender, * and crediting to the specified beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function _stake(address _beneficiary, uint256 _amount) internal { require(_amount > 0, "Cannot stake 0"); require(_beneficiary != address(0), "Invalid beneficiary address"); _stakeRaw(_beneficiary, _amount); emit Staked(_beneficiary, _amount, msg.sender); } /** * @dev Withdraws raw units from the sender * @param _amount Units of StakingToken */ function _withdraw(uint256 _amount) internal { require(_amount > 0, "Cannot withdraw 0"); _withdrawRaw(_amount); emit Withdrawn(msg.sender, _amount); } /*************************************** GETTERS ****************************************/ /** * @dev Gets the RewardsToken */ function getRewardToken() external view returns (IERC20) { return rewardsToken; } /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() public view returns (uint256) { return StableMath.min(block.timestamp, periodFinish); } /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @return 'Reward' per staked token */ function rewardPerToken() public view returns (uint256) { (uint256 rewardPerToken_, ) = _rewardPerToken(); return rewardPerToken_; } function _rewardPerToken() internal view returns (uint256 rewardPerToken_, uint256 lastTimeRewardApplicable_) { uint256 lastApplicableTime = lastTimeRewardApplicable(); // + 1 SLOAD uint256 timeDelta = lastApplicableTime.sub(lastUpdateTime); // + 1 SLOAD // If this has been called twice in the same block, shortcircuit to reduce gas if (timeDelta == 0) { return (rewardPerTokenStored, lastApplicableTime); } // new reward units to distribute = rewardRate * timeSinceLastUpdate uint256 rewardUnitsToDistribute = rewardRate.mul(timeDelta); // + 1 SLOAD uint256 supply = totalSupply(); // + 1 SLOAD // If there is no StakingToken liquidity, avoid div(0) // If there is nothing to distribute, short circuit if (supply == 0 || rewardUnitsToDistribute == 0) { return (rewardPerTokenStored, lastApplicableTime); } // new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(supply); // return summed rate return (rewardPerTokenStored.add(unitsToDistributePerToken), lastApplicableTime); // + 1 SLOAD } /** * @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this * does NOT include the majority of rewards which will be locked up. * @param _account User address * @return Total reward amount earned */ function earned(address _account) public view returns (uint256) { uint256 newEarned = _earned( _account, userData[_account].rewardPerTokenPaid, rewardPerToken() ); uint256 immediatelyUnlocked = newEarned.mulTruncate(UNLOCK); return immediatelyUnlocked.add(userData[_account].rewards); } /** * @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards * and those that have passed their time lock. * @param _account User address * @return amount Total units of unclaimed rewards * @return first Index of the first userReward that has unlocked * @return last Index of the last userReward that has unlocked */ function unclaimedRewards(address _account) external view returns ( uint256 amount, uint256 first, uint256 last ) { (first, last) = _unclaimedEpochs(_account); (uint256 unlocked, ) = _unclaimedRewards(_account, first, last); amount = unlocked.add(earned(_account)); } /** @dev Returns only the most recently earned rewards */ function _earned( address _account, uint256 _userRewardPerTokenPaid, uint256 _currentRewardPerToken ) internal view returns (uint256) { // current rate per token - rate user previously received uint256 userRewardDelta = _currentRewardPerToken.sub(_userRewardPerTokenPaid); // + 1 SLOAD // Short circuit if there is nothing new to distribute if (userRewardDelta == 0) { return 0; } // new reward = staked tokens * difference in rate uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta); // + 1 SLOAD // add to previous rewards return userNewReward; } /** * @dev Gets the first and last indexes of array elements containing unclaimed rewards */ function _unclaimedEpochs(address _account) internal view returns (uint256 first, uint256 last) { uint64 lastClaim = userClaim[_account]; uint256 firstUnclaimed = _findFirstUnclaimed(lastClaim, _account); uint256 lastUnclaimed = _findLastUnclaimed(_account); return (firstUnclaimed, lastUnclaimed); } /** * @dev Sums the cumulative rewards from a valid range */ function _unclaimedRewards( address _account, uint256 _first, uint256 _last ) internal view returns (uint256 amount, uint256 latestTimestamp) { uint256 currentTime = block.timestamp; uint64 lastClaim = userClaim[_account]; // Check for no rewards unlocked uint256 totalLen = userRewards[_account].length; if (_first == 0 && _last == 0) { if (totalLen == 0 || currentTime <= userRewards[_account][0].start) { return (0, currentTime); } } // If there are previous unlocks, check for claims that would leave them untouchable if (_first > 0) { require( lastClaim >= userRewards[_account][_first.sub(1)].finish, "Invalid _first arg: Must claim earlier entries" ); } uint256 count = _last.sub(_first).add(1); for (uint256 i = 0; i < count; i++) { uint256 id = _first.add(i); Reward memory rwd = userRewards[_account][id]; require(currentTime >= rwd.start && lastClaim <= rwd.finish, "Invalid epoch"); uint256 endTime = StableMath.min(rwd.finish, currentTime); uint256 startTime = StableMath.max(rwd.start, lastClaim); uint256 unclaimed = endTime.sub(startTime).mul(rwd.rate); amount = amount.add(unclaimed); } // Calculate last relevant timestamp here to allow users to avoid issue of OOG errors // by claiming rewards in batches. latestTimestamp = StableMath.min(currentTime, userRewards[_account][_last].finish); } /** * @dev Uses binarysearch to find the unclaimed lockups for a given account */ function _findFirstUnclaimed(uint64 _lastClaim, address _account) internal view returns (uint256 first) { uint256 len = userRewards[_account].length; if (len == 0) return 0; // Binary search uint256 min = 0; uint256 max = len - 1; // Will be always enough for 128-bit numbers for (uint256 i = 0; i < 128; i++) { if (min >= max) break; uint256 mid = (min.add(max).add(1)).div(2); if (_lastClaim > userRewards[_account][mid].start) { min = mid; } else { max = mid.sub(1); } } return min; } /** * @dev Uses binarysearch to find the unclaimed lockups for a given account */ function _findLastUnclaimed(address _account) internal view returns (uint256 first) { uint256 len = userRewards[_account].length; if (len == 0) return 0; // Binary search uint256 min = 0; uint256 max = len - 1; // Will be always enough for 128-bit numbers for (uint256 i = 0; i < 128; i++) { if (min >= max) break; uint256 mid = (min.add(max).add(1)).div(2); if (now > userRewards[_account][mid].start) { min = mid; } else { max = mid.sub(1); } } return min; } /*************************************** ADMIN ****************************************/ /** * @dev Notifies the contract that new rewards have been added. * Calculates an updated rewardRate based on the rewards in period. * @param _reward Units of RewardToken that have been added to the pool */ function notifyRewardAmount(uint256 _reward) external onlyRewardsDistributor updateReward(address(0)) { require(_reward < 1e24, "Cannot notify with more than a million units"); uint256 currentTime = block.timestamp; // If previous period over, reset rewardRate if (currentTime >= periodFinish) { rewardRate = _reward.div(DURATION); } // If additional reward to existing period, calc sum else { uint256 remaining = periodFinish.sub(currentTime); uint256 leftover = remaining.mul(rewardRate); rewardRate = _reward.add(leftover).div(DURATION); } lastUpdateTime = currentTime; periodFinish = currentTime.add(DURATION); emit RewardAdded(_reward); } }
@abstract This address has the ability to distribute the rewards
{ function notifyRewardAmount(uint256 reward) external; function getRewardToken() external view returns (IERC20); address public rewardsDistributor; function _initialize(address _rewardsDistributor) internal { rewardsDistributor = _rewardsDistributor; } modifier onlyRewardsDistributor() { require(msg.sender == rewardsDistributor, "Caller is not reward distributor"); _; } function setRewardsDistribution(address _rewardsDistributor) external onlyGovernor { rewardsDistributor = _rewardsDistributor; } }
5,881,809
pragma solidity ^0.4.24; contract ERC20Interface { function name() public view returns(bytes32); function symbol() public view returns(bytes32); function balanceOf (address _owner) public view returns(uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (uint); event Transfer(address indexed _from, address indexed _to, uint256 _value); } contract AppCoins is ERC20Interface{ // Public variables of the token address public owner; bytes32 private token_name; bytes32 private token_symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); function AppCoins() public { owner = msg.sender; token_name = "AppCoins"; token_symbol = "APPC"; uint256 _totalSupply = 1000000; totalSupply = _totalSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balances[owner] = totalSupply; // Give the creator all initial tokens } function name() public view returns(bytes32) { return token_name; } function symbol() public view returns(bytes32) { return token_symbol; } function balanceOf (address _owner) public view returns(uint256 balance) { return balances[_owner]; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal returns (bool) { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); // Save this for an assertion in the future uint previousBalances = balances[_from] + balances[_to]; // Subtract from the sender balances[_from] -= _value; // Add the same to the recipient balances[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); } function transfer (address _to, uint256 _amount) public returns (bool success) { if( balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(msg.sender, _to, _amount); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public returns (uint) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return allowance[_from][msg.sender]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } interface ErrorThrower { event Error(string func, string message); } contract Ownable is ErrorThrower { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner(string _funcName) { if(msg.sender != owner){ emit Error(_funcName,"Operation can only be performed by contract owner"); return; } _; } function renounceOwnership() public onlyOwner("renounceOwnership") { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner("transferOwnership") { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { if(_newOwner == address(0)){ emit Error("transferOwnership","New owner's address needs to be different than 0x0"); return; } emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage _role, address _addr) internal { _role.bearer[_addr] = true; } function remove(Role storage _role, address _addr) internal { _role.bearer[_addr] = false; } function check(Role storage _role, address _addr) internal view { require(has(_role, _addr)); } function has(Role storage _role, address _addr) internal view returns (bool) { return _role.bearer[_addr]; } } contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); function checkRole(address _operator, string _role) public view { roles[_role].check(_operator); } function hasRole(address _operator, string _role) public view returns (bool) { return roles[_role].has(_operator); } function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } } contract Whitelist is Ownable, RBAC { string public constant ROLE_WHITELISTED = "whitelist"; modifier onlyIfWhitelisted(string _funcname, address _operator) { if(!hasRole(_operator, ROLE_WHITELISTED)){ emit Error(_funcname, "Operation can only be performed by Whitelisted Addresses"); return; } _; } function addAddressToWhitelist(address _operator) public onlyOwner("addAddressToWhitelist") { addRole(_operator, ROLE_WHITELISTED); } function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } function addAddressesToWhitelist(address[] _operators) public onlyOwner("addAddressesToWhitelist") { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } function removeAddressFromWhitelist(address _operator) public onlyOwner("removeAddressFromWhitelist") { removeRole(_operator, ROLE_WHITELISTED); } function removeAddressesFromWhitelist(address[] _operators) public onlyOwner("removeAddressesFromWhitelist") { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } contract AppCoinsCreditsBalance is Whitelist { // AppCoins token AppCoins private appc; // balance proof bytes private balanceProof; // balance uint private balance; event BalanceProof(bytes _merkleTreeHash); event Deposit(uint _amount); event Withdraw(uint _amount); constructor( address _addrAppc ) public { appc = AppCoins(_addrAppc); } function getBalance() public view returns(uint256) { return balance; } function getBalanceProof() public view returns(bytes) { return balanceProof; } function registerBalanceProof(bytes _merkleTreeHash) internal{ balanceProof = _merkleTreeHash; emit BalanceProof(_merkleTreeHash); } function depositFunds(uint _amount, bytes _merkleTreeHash) public onlyIfWhitelisted("depositFunds", msg.sender){ require(appc.allowance(msg.sender, address(this)) >= _amount); registerBalanceProof(_merkleTreeHash); appc.transferFrom(msg.sender, address(this), _amount); balance = balance + _amount; emit Deposit(_amount); } function withdrawFunds(uint _amount, bytes _merkleTreeHash) public onlyOwner("withdrawFunds"){ require(balance >= _amount); registerBalanceProof(_merkleTreeHash); appc.transfer(msg.sender, _amount); balance = balance - _amount; emit Withdraw(_amount); } }
Internal transfer, only can be called by this contract/ Prevent transfer to 0x0 address. Use burn() instead Check if the sender has enough Check for overflows Save this for an assertion in the future Subtract from the sender Add the same to the recipient Asserts are used to use static analysis to find bugs in your code. They should never fail
function _transfer(address _from, address _to, uint _value) internal returns (bool) { require(_to != 0x0); require(balances[_from] >= _value); require(balances[_to] + _value > balances[_to]); uint previousBalances = balances[_from] + balances[_to]; balances[_from] -= _value; balances[_to] += _value; emit Transfer(_from, _to, _value); assert(balances[_from] + balances[_to] == previousBalances); }
6,451,604
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../maker/Manager.sol"; import "./ISubscriptions.sol"; import "../saver_proxy/MCDSaverProxy.sol"; import "../../constants/ConstantAddresses.sol"; import "../maker/Vat.sol"; import "../maker/Spotter.sol"; /// @title Handles subscriptions for automatic monitoring contract Subscriptions is ISubscriptions, ConstantAddresses { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; } struct SubPosition { uint arrPos; bool subscribed; } CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; address public owner; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { owner = msg.sender; saverProxy = MCDSaverProxy(_saverProxy); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); require(checkParams(manager.ilks(_cdpId), _minRatio, _maxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: _maxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Gets CDP ratio, calls MCDSaverProxy for getting the ratio function getRatio(uint _cdpId) public override view returns (uint) { return saverProxy.getRatio(_cdpId, manager.ilks(_cdpId)) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId) public override view returns(bool, uint) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; if (getOwner(_cdpId) != subscriber.owner) return (false, 0); uint currRatio = getRatio(_cdpId); if (_method == Method.Repay) { return (currRatio < subscriber.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > subscriber.maxRatio, currRatio); } } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public override view returns(address) { return manager.owns(_cdpId); } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId) public override view returns(bool, uint) { SubPosition memory subInfo = subscribersPos[_cdpId]; CdpHolder memory subscriber = subscribers[subInfo.arrPos]; uint currRatio = getRatio(_cdpId); if (_method == Method.Repay) { return (currRatio < subscriber.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > subscriber.minRatio, currRatio); } } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public { require(msg.sender == owner, "Must be owner"); minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP if it's owner transfered to a different addr function unsubscribeIfMoved(uint _cdpId) public { require(msg.sender == owner, "Must be owner"); SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { if (getOwner(_cdpId) != subscribers[subInfo.arrPos].owner) { _unsubscribe(_cdpId); } } } }
Returns an address that owns the CDP _cdpId Id of the CDP
function getOwner(uint _cdpId) public override view returns(address) { return manager.owns(_cdpId); }
12,718,196
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/LiveMintTokyo.sol
Deauthorizes A Contract From Minting/
function ___DeauthorizeContract(address NewAddress) external onlyOwner { Role[NewAddress] = 0x0; emit DeauthorizedContract(NewAddress); }
8,470,954
pragma solidity ^0.5.0; import "./interface/RegistryInterface.sol"; import "./registry/RegistryContract.sol"; import "./UserFactory.sol"; import "./SigningLogicInitializable.sol"; /** @title Contract for Audius user replica set management */ contract UserReplicaSetManager is SigningLogicInitializable, RegistryContract { /// @notice Reference to data contract registry RegistryInterface private registry = RegistryInterface(0); /// @notice User factory key used to confirm valid users during reconfig operations bytes32 private userFactoryRegistryKey; /// @notice Address permissioned to update user replica sets address userReplicaSetBootstrapAddress; /// @notice Struct used to represent the ownerWallet,delegateOwnerWallet tuple /// for a given spID struct ContentNodeWallets { address ownerWallet; address delegateOwnerWallet; } /// @notice ServiceProvider ID to ServiceProvider delegateOwnerWallet, /// reflecting registered values on Audius Ethereum L1 contracts mapping (uint => ContentNodeWallets) spIdToContentNodeWallets; /// @notice Struct used to represent replica sets // Each uint represents the spID registered on eth-contracts struct ReplicaSet { uint primaryId; uint[] secondaryIds; } /// @notice Current uint userId to Replica Set mapping (uint => ReplicaSet) userReplicaSets; /// @notice Flag indicating whether bootstrap information has been configured bool seedComplete; /* Events */ event UpdateReplicaSet( uint _userId, uint _primaryId, uint[] _secondaryIds, address _signer ); event AddOrUpdateContentNode( uint _cnodeSpId, address _cnodeDelegateOwnerWallet, address _cnodeOwnerWallet, uint[3] _proposerSpIds, address _proposer1DelegateOwnerWallet, address _proposer2DelegateOwnerWallet, address _proposer3DelegateOwnerWallet ); /// @notice EIP-712 Typehash definitions // Used to validate identity with gasless transaction submission bytes32 constant PROPOSE_ADD_UPDATE_CNODE_REQUEST_TYPEHASH = keccak256( "ProposeAddOrUpdateContentNode(uint cnodeSpId,address cnodeDelegateOwnerWallet,address cnodeOwnerWallet,uint proposerSpId,bytes32 nonce)" ); bytes32 constant UPDATE_REPLICA_SET_REQUEST_TYPEHASH = keccak256( "UpdateReplicaSet(uint userId,uint primaryId,bytes32 secondaryIdsHash,uint oldPrimaryId,bytes32 oldSecondaryIdsHash,bytes32 nonce)" ); function initialize( address _registryAddress, bytes32 _userFactoryRegistryKey, address _userReplicaSetBootstrapAddress, uint _networkId ) public initializer { require( _registryAddress != address(0x00) && _userFactoryRegistryKey.length != 0, "Requires non-zero _registryAddress and registryKey" ); registry = RegistryInterface(_registryAddress); userFactoryRegistryKey = _userFactoryRegistryKey; userReplicaSetBootstrapAddress = _userReplicaSetBootstrapAddress; // Initialize base Signing Logic contract SigningLogicInitializable.initialize( "User Replica Set Manager", "1", _networkId ); seedComplete = false; } /** * @notice Function used to initialize bootstrap nodes * Prior to this function, the contract is effectively disabled */ function seedBootstrapNodes( uint[] calldata _bootstrapSPIds, address[] calldata _bootstrapNodeDelegateWallets, address[] calldata _bootstrapNodeOwnerWallets ) external { require( msg.sender == userReplicaSetBootstrapAddress, "Only callable by userReplicaSetBootstrapAddress" ); require(seedComplete == false, "Seed operation already completed"); uint256[3] memory emptyProposerIds = [uint256(0), uint256(0), uint256(0)]; require( (_bootstrapSPIds.length == _bootstrapNodeDelegateWallets.length) && (_bootstrapSPIds.length == _bootstrapNodeOwnerWallets.length), "Mismatched bootstrap array lengths" ); for (uint i = 0; i < _bootstrapSPIds.length; i++) { spIdToContentNodeWallets[_bootstrapSPIds[i]] = ContentNodeWallets({ delegateOwnerWallet: _bootstrapNodeDelegateWallets[i], ownerWallet: _bootstrapNodeOwnerWallets[i] }); emit AddOrUpdateContentNode( _bootstrapSPIds[i], _bootstrapNodeDelegateWallets[i], _bootstrapNodeOwnerWallets[i], emptyProposerIds, address(0x00), address(0x00), address(0x00) ); } seedComplete = true; } /** * @notice Chain of trust based authentication scheme * Nodes are required to have an identity in Audius L2 and this function enables * known entities to register other known entities on L2 contracts. * By requiring 3 distinct proposers that are already known on-chain, * a single compromised wallet will not be able to arbitrarily add * content node mappings to this contract. * @dev Multiple distinct parties must sign and submit signatures as part of this request * @param _cnodeSpId - Incoming spID * @param _cnodeWallets - Incoming wallets array - [0] = incoming delegateOwnerWallet, [1] = incoming ownerWallet * @param _proposerSpIds - Array of 3 spIDs proposing new node * @param _proposerNonces - Array of 3 nonces, each index corresponding to _proposerSpIds * @param _proposer1Sig - Signature from first proposing node * @param _proposer2Sig - Signature from second proposing node * @param _proposer3Sig - Signature from third proposing node */ function addOrUpdateContentNode( uint _cnodeSpId, address[2] calldata _cnodeWallets, uint[3] calldata _proposerSpIds, bytes32[3] calldata _proposerNonces, bytes calldata _proposer1Sig, bytes calldata _proposer2Sig, bytes calldata _proposer3Sig ) external { _requireSeed(); // For every entry in spIds/Nonces/Sigs // Recover signer using the signature for inner function // Confirm that the spId <-> recoveredSigner DOES exist and match what is stored on chain address proposer1DelegateOwnerWallet = _recoverProposeAddOrUpdateContentNodeSignerAddress( _cnodeSpId, _cnodeWallets[0], _cnodeWallets[1], _proposerSpIds[0], _proposerNonces[0], _proposer1Sig ); address proposer2DelegateOwnerWallet = _recoverProposeAddOrUpdateContentNodeSignerAddress( _cnodeSpId, _cnodeWallets[0], _cnodeWallets[1], _proposerSpIds[1], _proposerNonces[1], _proposer2Sig ); address proposer3DelegateOwnerWallet = _recoverProposeAddOrUpdateContentNodeSignerAddress( _cnodeSpId, _cnodeWallets[0], _cnodeWallets[1], _proposerSpIds[2], _proposerNonces[2], _proposer3Sig ); require( (proposer1DelegateOwnerWallet != proposer2DelegateOwnerWallet) && (proposer1DelegateOwnerWallet != proposer3DelegateOwnerWallet) && (proposer2DelegateOwnerWallet != proposer3DelegateOwnerWallet), "Distinct proposer delegateOwnerWallets required" ); require( spIdToContentNodeWallets[_proposerSpIds[0]].delegateOwnerWallet == proposer1DelegateOwnerWallet, "Invalid delegateOwnerWallet provided for 1st proposer" ); require( spIdToContentNodeWallets[_proposerSpIds[1]].delegateOwnerWallet == proposer2DelegateOwnerWallet, "Invalid delegateOwnerWallet provided for 2nd proposer" ); require( spIdToContentNodeWallets[_proposerSpIds[2]].delegateOwnerWallet == proposer3DelegateOwnerWallet, "Invalid delegateOwnerWallet provided for 3rd proposer" ); // Require distinct ownerWallet for each proposer require( (spIdToContentNodeWallets[_proposerSpIds[0]].ownerWallet != spIdToContentNodeWallets[_proposerSpIds[1]].ownerWallet) && (spIdToContentNodeWallets[_proposerSpIds[1]].ownerWallet != spIdToContentNodeWallets[_proposerSpIds[2]].ownerWallet) && (spIdToContentNodeWallets[_proposerSpIds[0]].ownerWallet != spIdToContentNodeWallets[_proposerSpIds[2]].ownerWallet), "Distinct proposer ownerWallets required" ); spIdToContentNodeWallets[_cnodeSpId] = ContentNodeWallets({ delegateOwnerWallet: _cnodeWallets[0], ownerWallet: _cnodeWallets[1] }); emit AddOrUpdateContentNode( _cnodeSpId, _cnodeWallets[0], _cnodeWallets[1], _proposerSpIds, proposer1DelegateOwnerWallet, proposer2DelegateOwnerWallet, proposer3DelegateOwnerWallet ); } /** * @notice Function used to perform updates to a given user's replica set * A valid updater can either be the user's wallet, an old primary * node delegateOwnerWallet, an old secondary node delegateOwnerWallet, * or the replica set bootstrap address. * By requiring an existing on-chain "old" replica or the user's wallet * directly, the contract can validate that the submitting entity is * known within the protocol. * @param _userId - User for whom this update operation is being performed * @param _primaryId - Incoming primary for _userId * @param _secondaryIds - Incoming array of n secondary spIDs for _userId * @param _oldPrimaryId - Current primary on chain for _userId * @param _oldSecondaryIds - Current array of secondaries on chain for _userId * @param _requestNonce - Nonce generated by signer * @param _subjectSig - Signature generated by signer */ function updateReplicaSet( uint _userId, uint _primaryId, uint[] calldata _secondaryIds, uint _oldPrimaryId, uint[] calldata _oldSecondaryIds, bytes32 _requestNonce, bytes calldata _subjectSig ) external { _requireSeed(); address signer = _recoverUserReplicaSetRequestSignerAddress( _userId, _primaryId, _secondaryIds, _oldPrimaryId, _oldSecondaryIds, _requestNonce, _subjectSig ); bool validUpdater = false; // Get user object from UserFactory (address userWallet, ) = UserFactory( registry.getContract(userFactoryRegistryKey) ).getUser(_userId); require(userWallet != address(0x00), "Valid user required"); // Valid updaters include userWallet (artist account), existing primary, existing secondary, or contract deployer if (signer == userWallet || signer == spIdToContentNodeWallets[_oldPrimaryId].delegateOwnerWallet || signer == userReplicaSetBootstrapAddress ) { validUpdater = true; } // Caller's notion of existing primary must match registered value on chain require( userReplicaSets[_userId].primaryId == _oldPrimaryId, "Invalid prior primary configuration" ); // Check if any of the old secondaries submitted this operation validUpdater = _compareUserSecondariesAndCheckSender( _userId, _oldSecondaryIds, signer, validUpdater ); require(validUpdater == true, "Invalid update operation"); // Confirm primary and every incoming secondary is valid require( spIdToContentNodeWallets[_primaryId].delegateOwnerWallet != address(0x00), "Primary must exist" ); for (uint i = 0; i < _secondaryIds.length; i++) { require( spIdToContentNodeWallets[_secondaryIds[i]].delegateOwnerWallet != address(0x00), "Secondary must exist" ); } // Confirm no duplicate entries are present between // primary, secondaryIds[0] and secondaryIds[1] // Guaranteeing at least 3 replicas require( (_primaryId != _secondaryIds[0]) && (_primaryId != _secondaryIds[1]) && (_secondaryIds[0] != _secondaryIds[1]), "Distinct replica IDs expected for primary, secondary1, secondary2" ); // Perform replica set update userReplicaSets[_userId] = ReplicaSet({ primaryId: _primaryId, secondaryIds: _secondaryIds }); emit UpdateReplicaSet(_userId, _primaryId, _secondaryIds, signer); } /// @notice Update configured userReplicaSetBootstrapAddress /// Only callable by currently configured address on chain /// Allows special address to renounce ability function updateUserReplicaBootstrapAddress ( address _newBootstrapAddress ) external { _requireSeed(); require( msg.sender == userReplicaSetBootstrapAddress, "Invalid sender, expect current userReplicaSetBootstrapAddress" ); userReplicaSetBootstrapAddress = _newBootstrapAddress; } /// @notice Return a users current replica set function getUserReplicaSet(uint _userId) external view returns (uint primaryId, uint[] memory secondaryIds) { return ( userReplicaSets[_userId].primaryId, userReplicaSets[_userId].secondaryIds ); } /// @notice Get wallet registered on chain corresponding to Content Node spID function getContentNodeWallets(uint _spID) external view returns (address delegateOwnerWallet, address ownerWallet) { return ( spIdToContentNodeWallets[_spID].delegateOwnerWallet, spIdToContentNodeWallets[_spID].ownerWallet ); } /// @notice Get userReplicaSetBootstrapAddress function getUserReplicaSetBootstrapAddress() external view returns (address) { return userReplicaSetBootstrapAddress; } /// @notice Get seedComplete function getSeedComplete() external view returns (bool) { return seedComplete; } /* EIP712 - Signer recovery */ function _recoverProposeAddOrUpdateContentNodeSignerAddress( uint _cnodeSpId, address _cnodeDelegateOwnerWallet, address _cnodeOwnerWallet, uint _proposerId, bytes32 _nonce, bytes memory _subjectSig ) internal returns (address) { bytes32 signatureDigest = generateSchemaHash( keccak256( abi.encode( PROPOSE_ADD_UPDATE_CNODE_REQUEST_TYPEHASH, _cnodeSpId, _cnodeDelegateOwnerWallet, _cnodeOwnerWallet, _proposerId, _nonce ) ) ); address signer = recoverSigner(signatureDigest, _subjectSig); burnSignatureDigest(signatureDigest, signer); return signer; } function _recoverUserReplicaSetRequestSignerAddress( uint _userId, uint _primaryId, uint[] memory _secondaryIds, uint _oldPrimaryId, uint[] memory _oldSecondaryIds, bytes32 _nonce, bytes memory _subjectSig ) internal returns (address) { bytes32 signatureDigest = generateSchemaHash( keccak256( abi.encode( UPDATE_REPLICA_SET_REQUEST_TYPEHASH, _userId, _primaryId, keccak256(abi.encode(_secondaryIds)), _oldPrimaryId, keccak256(abi.encode(_oldSecondaryIds)), _nonce ) ) ); address signer = recoverSigner(signatureDigest, _subjectSig); burnSignatureDigest(signatureDigest, signer); return signer; } // Compare old secondaries submitted by function caller // and the value stored on the contract - note that the order // does matter when comparing secondary replicas function _compareUserSecondariesAndCheckSender( uint _userId, uint[] memory _oldSecondaryIds, address signer, bool senderFound ) internal view returns (bool) { // Caller's notion of secondary values must match registered value on chain // A secondary node can also be considered a valid updater require( _oldSecondaryIds.length == userReplicaSets[_userId].secondaryIds.length, "Invalid prior secondary configuration" ); bool secondarySenderFound = senderFound; for (uint i = 0; i < _oldSecondaryIds.length; i++) { require( userReplicaSets[_userId].secondaryIds[i] == _oldSecondaryIds[i], "Invalid prior secondary configuration" ); if (signer == spIdToContentNodeWallets[_oldSecondaryIds[i]].delegateOwnerWallet) { secondarySenderFound = true; } } return secondarySenderFound; } function _requireSeed () internal view { require(seedComplete == true, "Must be initialized"); } }
Get userReplicaSetBootstrapAddress
function getUserReplicaSetBootstrapAddress() external view returns (address) { return userReplicaSetBootstrapAddress; }
7,304,023
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /** * @title Curious Addys' Trading Club Contract * @author Mai Akiyoshi & Ben Yu (https://twitter.com/mai_on_chain & https://twitter.com/intenex) * @notice This contract handles minting and refunding of First Edition Curious Addys' Trading Club tokens. */ contract CuriousAddys is ERC721Enumerable, ReentrancyGuard, Ownable, Pausable { using ECDSA for bytes32; using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIds; string public baseTokenURI; uint256 public constant price = 0.08 ether; uint256 public immutable maxSupply; uint256 public immutable firstSaleSupply; uint256 public immutable reserveSupply; /** * @notice Construct a Curious Addys instance * @param name Token name * @param symbol Token symbol * @param baseTokenURI_ Base URI for all tokens */ constructor( string memory name, string memory symbol, string memory baseTokenURI_, uint256 maxSupply_, uint256 firstSaleSupply_, uint256 reserveSupply_ ) ERC721(name, symbol) { require(maxSupply_ > 0, "INVALID_SUPPLY"); baseTokenURI = baseTokenURI_; maxSupply = maxSupply_; firstSaleSupply = firstSaleSupply_; reserveSupply = reserveSupply_; // Start token IDs at 1 _tokenIds.increment(); } // Used to validate authorized mint addresses address private signerAddress = 0xabcB40408a94E94f563d64ded69A75a3098cBf59; // The address where refunded tokens are returned to address private refundAddress = 0x52EA5F96f004d174470901Ba3F1984D349f0D3eF; mapping (address => uint256) public totalMintsPerAddress; uint256 public saleEndTime = block.timestamp; bool public isFirstSaleActive = false; bool public isSecondSaleActive = false; bool public reserveMintCompleted = false; function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); return string(abi.encodePacked(_baseURI(), tokenId.toString(), ".json")); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } /** * To be updated by contract owner to allow for the first tranche of members to mint */ function setFirstSaleState(bool _firstSaleActiveState) public onlyOwner { require(isFirstSaleActive != _firstSaleActiveState, "NEW_STATE_IDENTICAL_TO_OLD_STATE"); isFirstSaleActive = _firstSaleActiveState; } /** * To be updated once maxSupply equals totalSupply. This will deactivate minting. * Can also be activated by contract owner to begin public sale */ function setSecondSaleState(bool _secondSaleActiveState) public onlyOwner { require(isSecondSaleActive != _secondSaleActiveState, "NEW_STATE_IDENTICAL_TO_OLD_STATE"); isSecondSaleActive = _secondSaleActiveState; if (!isSecondSaleActive) { saleEndTime = block.timestamp; } } function setSignerAddress(address _signerAddress) external onlyOwner { require(_signerAddress != address(0)); signerAddress = _signerAddress; } function setRefundAddress(address _refundAddress) external onlyOwner { require(_refundAddress != address(0)); refundAddress = _refundAddress; } /** * Returns all the token ids owned by a given address */ function ownedTokensByAddress(address owner) external view returns (uint256[] memory) { uint256 totalTokensOwned = balanceOf(owner); uint256[] memory allTokenIds = new uint256[](totalTokensOwned); for (uint256 i = 0; i < totalTokensOwned; i++) { allTokenIds[i] = (tokenOfOwnerByIndex(owner, i)); } return allTokenIds; } /** * Update the base token URI */ function setBaseURI(string calldata _newBaseURI) external onlyOwner { baseTokenURI = _newBaseURI; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } /** * When the contract is paused, all token transfers are prevented in case of emergency. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal whenNotPaused override { super._beforeTokenTransfer(from, to, tokenId); } /** * Will return true if token holders can still return their tokens for a full mint price refund */ function refundGuaranteeActive() public view returns (bool) { return (block.timestamp < (saleEndTime + 100 days)); } function verifyAddressSigner(bytes32 messageHash, bytes memory signature) private view returns (bool) { return signerAddress == messageHash.toEthSignedMessageHash().recover(signature); } function hashMessage(address sender, uint256 maximumAllowedMints) private pure returns (bytes32) { return keccak256(abi.encode(sender, maximumAllowedMints)); } /** * @notice Allow for minting of tokens up to the maximum allowed for a given address. * The address of the sender and the number of mints allowed are hashed and signed * with the server's private key and verified here to prove whitelisting status. */ function mint( bytes32 messageHash, bytes calldata signature, uint256 mintNumber, uint256 maximumAllowedMints ) external payable virtual nonReentrant { require(isFirstSaleActive || isSecondSaleActive, "SALE_IS_NOT_ACTIVE"); require(totalMintsPerAddress[msg.sender] + mintNumber <= maximumAllowedMints, "MINT_TOO_LARGE"); require(hashMessage(msg.sender, maximumAllowedMints) == messageHash, "MESSAGE_INVALID"); require(verifyAddressSigner(messageHash, signature), "SIGNATURE_VALIDATION_FAILED"); // Imprecise floats are scary. Front-end should utilize BigNumber for safe precision, but adding margin just to be safe to not fail txs require(msg.value >= ((price * mintNumber) - 0.0001 ether) && msg.value <= ((price * mintNumber) + 0.0001 ether), "INVALID_PRICE"); uint256 currentSupply = totalSupply(); if (isFirstSaleActive) { require(currentSupply + mintNumber <= firstSaleSupply, "NOT_ENOUGH_MINTS_AVAILABLE"); } else { require(currentSupply + mintNumber <= maxSupply, "NOT_ENOUGH_MINTS_AVAILABLE"); } totalMintsPerAddress[msg.sender] += mintNumber; for (uint256 i = 0; i < mintNumber; i++) { _safeMint(msg.sender, _tokenIds.current()); _tokenIds.increment(); } // Update the saleEndTime at the end of the second sale so the refund guarantee starts from now if (isFirstSaleActive && (currentSupply + mintNumber >= firstSaleSupply)) { isFirstSaleActive = false; } else if (isSecondSaleActive && (currentSupply + mintNumber >= maxSupply)) { isSecondSaleActive = false; saleEndTime = block.timestamp; } } /** * @notice Allow owner to send `mintNumber` tokens without cost to multiple addresses */ function gift(address[] calldata receivers, uint256 mintNumber) external onlyOwner { require((totalSupply() + (receivers.length * mintNumber)) <= maxSupply, "MINT_TOO_LARGE"); for (uint256 i = 0; i < receivers.length; i++) { for (uint256 j = 0; j < mintNumber; j++) { _safeMint(receivers[i], _tokenIds.current()); _tokenIds.increment(); } } } /** * @notice Allow the owner to mint their reserved supply */ function mintReserveSupply() external virtual onlyOwner { require(!reserveMintCompleted, "RESERVE_MINT_ALREADY_COMPLETED"); // Start at first token after the public supply uint256 start = (maxSupply - reserveSupply) + 1; for (uint256 tokenId = start; tokenId <= maxSupply; tokenId++) { _safeMint(owner(), tokenId); } reserveMintCompleted = true; } /** * @notice Refund token and return the mint price to the token owner. * @param _tokenId The id of the token to refund. */ function refund(uint256 _tokenId) external nonReentrant { require(refundGuaranteeActive(), "REFUND_GUARANTEE_EXPIRED"); require(ownerOf(_tokenId) == msg.sender, "MUST_OWN_TOKEN"); // Transfer token to CATC wallet _transfer(msg.sender, refundAddress, _tokenId); // Refund the token owner 100% of the mint price. payable(msg.sender).transfer(price); } /** * @notice Allow contract owner to withdraw funds after the refund guarantee ends. */ function withdrawFundsAfterRefundExpires() external onlyOwner { require(!refundGuaranteeActive(), "REFUND_GUARANTEE_STILL_ACTIVE"); payable(owner()).transfer(address(this).balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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); }
Refund token and return the mint price to the token owner. _tokenId The id of the token to refund./ Transfer token to CATC wallet Refund the token owner 100% of the mint price.
function refund(uint256 _tokenId) external nonReentrant { require(refundGuaranteeActive(), "REFUND_GUARANTEE_EXPIRED"); require(ownerOf(_tokenId) == msg.sender, "MUST_OWN_TOKEN"); _transfer(msg.sender, refundAddress, _tokenId); payable(msg.sender).transfer(price); }
6,874,058
./full_match/1/0x60Fa954e22c42F52E8C815a9476f339BD38AEEf7/sources/contracts/core/defi/three-x/ThreeXBatchProcessing.sol
This function allows the owner to change the composition of underlying token of the 3X _components An array of addresses for the yToken needed to mint 3X _componentDependencies An array structs describing underlying yToken, curveMetapool (which is also the lpToken), swapPool and AngleRouter/
function setComponents(address[] memory _components, ComponentDependencies[] calldata _componentDependencies) external onlyRole(DAO_ROLE) { _setComponents(_components, _componentDependencies); }
4,889,303
pragma solidity ^0.4.23; 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; } } 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; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; emit OwnershipTransferred(owner, newOwner); } } 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; } function isOwnerOf(address _owner, uint256 _tokenId) public view returns (bool) { address owner = ownerOf(_tokenId); return owner == _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_ = "CryptoFlowers"; // Token symbol string internal symbol_ = "CF"; // 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; function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } /** * @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)); string memory infoUrl; infoUrl = strConcat('https://cryptoflowers.io/v/', uint2str(_tokenId)); return infoUrl; } /** * @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 - 1; } /** * @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 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 pure returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721) || (_interfaceID == InterfaceSignature_ERC721Enumerable) || (_interfaceID == InterfaceSignature_ERC721Metadata)); } function implementsERC721() public pure returns (bool) { return true; } } contract GenomeInterface { function isGenome() public pure returns (bool); function mixGenes(uint256 genes1, uint256 genes2) public returns (uint256); } contract FlowerAdminAccess { address public rootAddress; address public adminAddress; event ContractUpgrade(address newContract); address public gen0SellerAddress; bool public stopped = false; modifier onlyRoot() { require(msg.sender == rootAddress); _; } modifier onlyAdmin() { require(msg.sender == adminAddress); _; } modifier onlyAdministrator() { require(msg.sender == rootAddress || msg.sender == adminAddress); _; } function setRoot(address _newRoot) external onlyAdministrator { require(_newRoot != address(0)); rootAddress = _newRoot; } function setAdmin(address _newAdmin) external onlyRoot { require(_newAdmin != address(0)); adminAddress = _newAdmin; } modifier whenNotStopped() { require(!stopped); _; } modifier whenStopped { require(stopped); _; } function setStop() public onlyAdministrator whenNotStopped { stopped = true; } function setStart() public onlyAdministrator whenStopped { stopped = false; } } contract FlowerBase is ERC721Token { struct Flower { uint256 genes; uint64 birthTime; uint64 cooldownEndBlock; uint32 matronId; uint32 sireId; uint16 cooldownIndex; uint16 generation; } Flower[] flowers; mapping (uint256 => uint256) genomeFlowerIds; // Сooldown duration uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; event Birth(address owner, uint256 flowerId, uint256 matronId, uint256 sireId, uint256 genes); event Transfer(address from, address to, uint256 tokenId); event Money(address from, string actionType, uint256 sum, uint256 cut, uint256 tokenId, uint256 blockNumber); function _createFlower(uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); require(checkUnique(_genes)); uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Flower memory _flower = Flower({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newFlowerId = flowers.push(_flower) - 1; require(newFlowerId == uint256(uint32(newFlowerId))); genomeFlowerIds[_genes] = newFlowerId; emit Birth(_owner, newFlowerId, uint256(_flower.matronId), uint256(_flower.sireId), _flower.genes); _mint(_owner, newFlowerId); return newFlowerId; } function checkUnique(uint256 _genome) public view returns (bool) { uint256 _flowerId = uint256(genomeFlowerIds[_genome]); return !(_flowerId > 0); } } contract FlowerOwnership is FlowerBase, FlowerAdminAccess { SaleClockAuction public saleAuction; BreedingClockAuction public breedingAuction; uint256 public secondsPerBlock = 15; function setSecondsPerBlock(uint256 secs) external onlyAdministrator { require(secs < cooldowns[0]); secondsPerBlock = secs; } } contract ClockAuctionBase { struct Auction { address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; } ERC721Token public nonFungibleContract; uint256 public ownerCut; mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); event Money(address from, string actionType, uint256 sum, uint256 cut, uint256 tokenId, uint256 blockNumber); function isOwnerOf(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.transferFrom(_owner, this, _tokenId); } function _transfer(address _receiver, uint256 _tokenId) internal { nonFungibleContract.transferFrom(this, _receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal { require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated(uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration)); } function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } function _bid(uint256 _tokenId, uint256 _bidAmount, address _sender) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); emit Money(_sender, "AuctionSuccessful", price, auctioneerCut, _tokenId, block.number); } uint256 bidExcess = _bidAmount - price; _sender.transfer(bidExcess); emit AuctionSuccessful(_tokenId, price, _sender); return price; } function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0 && _auction.startedAt < now); } function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice(_auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed); } function _computeCurrentPrice(uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed) internal pure returns (uint256) { if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256) { return uint256(_price * ownerCut / 10000); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } contract ClockAuction is Pausable, ClockAuctionBase { bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd); constructor(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721Token candidateContract = ERC721Token(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require(msg.sender == owner || msg.sender == nftAddress); owner.transfer(address(this).balance); } function createAuction(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller, uint64 _startAt) external whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(isOwnerOf(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); uint64 startAt = _startAt; if (_startAt == 0) { startAt = uint64(now); } Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(startAt) ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId, address _sender) external payable whenNotPaused { _bid(_tokenId, msg.value, _sender); _transfer(_sender, _tokenId); } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionByAdmin(uint256 _tokenId) onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } function getAuction(uint256 _tokenId) external view returns (address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return (auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256){ Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } // TMP function getContractBalance() external view returns (uint256) { return address(this).balance; } } contract BreedingClockAuction is ClockAuction { bool public isBreedingClockAuction = true; constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} function bid(uint256 _tokenId, address _sender) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; _bid(_tokenId, msg.value, _sender); _transfer(seller, _tokenId); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } function createAuction(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller, uint64 _startAt) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 startAt = _startAt; if (_startAt == 0) { startAt = uint64(now); } Auction memory auction = Auction(_seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(startAt)); _addAuction(_tokenId, auction); } } contract SaleClockAuction is ClockAuction { bool public isSaleClockAuction = true; uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; constructor(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} address public gen0SellerAddress; function setGen0SellerAddress(address _newAddress) external { require(msg.sender == address(nonFungibleContract)); gen0SellerAddress = _newAddress; } function createAuction(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller, uint64 _startAt) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 startAt = _startAt; if (_startAt == 0) { startAt = uint64(now); } Auction memory auction = Auction(_seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(startAt)); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value, msg.sender); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(gen0SellerAddress)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function bidGift(uint256 _tokenId, address _to) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value, msg.sender); _transfer(_to, _tokenId); // If not a gen0 auction, exit if (seller == address(gen0SellerAddress)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } function computeCut(uint256 _price) public view returns (uint256) { return _computeCut(_price); } function getSeller(uint256 _tokenId) public view returns (address) { return address(tokenIdToAuction[_tokenId].seller); } } // Flowers crossing contract FlowerBreeding is FlowerOwnership { // Fee for breeding uint256 public autoBirthFee = 2 finney; GenomeInterface public geneScience; // Set Genome contract address function setGenomeContractAddress(address _address) external onlyAdministrator { geneScience = GenomeInterface(_address); } function _isReadyToAction(Flower _flower) internal view returns (bool) { return _flower.cooldownEndBlock <= uint64(block.number); } function isReadyToAction(uint256 _flowerId) public view returns (bool) { require(_flowerId > 0); Flower storage flower = flowers[_flowerId]; return _isReadyToAction(flower); } function _setCooldown(Flower storage _flower) internal { _flower.cooldownEndBlock = uint64((cooldowns[_flower.cooldownIndex]/secondsPerBlock) + block.number); if (_flower.cooldownIndex < 13) { _flower.cooldownIndex += 1; } } // Updates the minimum payment required for calling giveBirthAuto() function setAutoBirthFee(uint256 val) external onlyAdministrator { autoBirthFee = val; } // Check if a given sire and matron are a valid crossing pair function _isValidPair(Flower storage _matron, uint256 _matronId, Flower storage _sire, uint256 _sireId) private view returns(bool) { if (_matronId == _sireId) { return false; } // Generation zero can crossing if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Do not crossing with it parrents if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // Can't crossing with brothers and sisters if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } return true; } function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns (bool) { return _canBreedWith(_matronId, _sireId); } function _canBreedWith(uint256 _matronId, uint256 _sireId) internal view returns (bool) { require(_matronId > 0); require(_sireId > 0); Flower storage matron = flowers[_matronId]; Flower storage sire = flowers[_sireId]; return _isValidPair(matron, _matronId, sire, _sireId); } function born(uint256 _matronId, uint256 _sireId) external { _born(_matronId, _sireId); } function _born(uint256 _matronId, uint256 _sireId) internal { Flower storage sire = flowers[_sireId]; Flower storage matron = flowers[_matronId]; uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes); address owner = ownerOf(_matronId); uint256 flowerId = _createFlower(_matronId, _sireId, parentGen + 1, childGenes, owner); Flower storage child = flowers[flowerId]; _setCooldown(sire); _setCooldown(matron); _setCooldown(child); } // Crossing two of owner flowers function breedOwn(uint256 _matronId, uint256 _sireId) external payable whenNotStopped { require(msg.value >= autoBirthFee); require(isOwnerOf(msg.sender, _matronId)); require(isOwnerOf(msg.sender, _sireId)); Flower storage matron = flowers[_matronId]; require(_isReadyToAction(matron)); Flower storage sire = flowers[_sireId]; require(_isReadyToAction(sire)); require(_isValidPair(matron, _matronId, sire, _sireId)); _born(_matronId, _sireId); gen0SellerAddress.transfer(autoBirthFee); emit Money(msg.sender, "BirthFee-own", autoBirthFee, autoBirthFee, _sireId, block.number); } } // Handles creating auctions for sale and siring contract FlowerAuction is FlowerBreeding { // Set sale auction contract address function setSaleAuctionAddress(address _address) external onlyAdministrator { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } // Set siring auction contract address function setBreedingAuctionAddress(address _address) external onlyAdministrator { BreedingClockAuction candidateContract = BreedingClockAuction(_address); require(candidateContract.isBreedingClockAuction()); breedingAuction = candidateContract; } // Flower sale auction function createSaleAuction(uint256 _flowerId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external whenNotStopped { require(isOwnerOf(msg.sender, _flowerId)); require(isReadyToAction(_flowerId)); approve(saleAuction, _flowerId); saleAuction.createAuction(_flowerId, _startingPrice, _endingPrice, _duration, msg.sender, 0); } // Create siring auction function createBreedingAuction(uint256 _flowerId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external whenNotStopped { require(isOwnerOf(msg.sender, _flowerId)); require(isReadyToAction(_flowerId)); approve(breedingAuction, _flowerId); breedingAuction.createAuction(_flowerId, _startingPrice, _endingPrice, _duration, msg.sender, 0); } // Siring auction complete function bidOnBreedingAuction(uint256 _sireId, uint256 _matronId) external payable whenNotStopped { require(isOwnerOf(msg.sender, _matronId)); require(isReadyToAction(_matronId)); require(isReadyToAction(_sireId)); require(_canBreedWith(_matronId, _sireId)); uint256 currentPrice = breedingAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. breedingAuction.bid.value(msg.value - autoBirthFee)(_sireId, msg.sender); _born(uint32(_matronId), uint32(_sireId)); gen0SellerAddress.transfer(autoBirthFee); emit Money(msg.sender, "BirthFee-bid", autoBirthFee, autoBirthFee, _sireId, block.number); } // Transfers the balance of the sale auction contract to the Core contract function withdrawAuctionBalances() external onlyAdministrator { saleAuction.withdrawBalance(); breedingAuction.withdrawBalance(); } function sendGift(uint256 _flowerId, address _to) external payable whenNotStopped { require(isOwnerOf(msg.sender, _flowerId)); require(isReadyToAction(_flowerId)); transferFrom(msg.sender, _to, _flowerId); } } contract FlowerCore is FlowerAuction { // Limits the number of flowers the contract owner can ever create uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of cats the contract owner has created uint256 public promoCreatedCount; uint256 public gen0CreatedCount; // Create promo flower function createPromoFlower(uint256 _genes, address _owner) external onlyAdministrator { address flowerOwner = _owner; if (flowerOwner == address(0)) { flowerOwner = adminAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; gen0CreatedCount++; _createFlower(0, 0, 0, _genes, flowerOwner); } function createGen0Auction(uint256 _genes, uint64 _auctionStartAt) external onlyAdministrator { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 flowerId = _createFlower(0, 0, 0, _genes, address(gen0SellerAddress)); tokenApprovals[flowerId] = saleAuction; //approve(saleAuction, flowerId); gen0CreatedCount++; saleAuction.createAuction(flowerId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(gen0SellerAddress), _auctionStartAt); } // Computes the next gen0 auction starting price, given the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } function setGen0SellerAddress(address _newAddress) external onlyAdministrator { gen0SellerAddress = _newAddress; saleAuction.setGen0SellerAddress(_newAddress); } constructor() public { stopped = true; rootAddress = msg.sender; adminAddress = msg.sender; _createFlower(0, 0, 0, uint256(-1), address(0)); } // Get flower information function getFlower(uint256 _id) external view returns (bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes) { Flower storage flower = flowers[_id]; isReady = (flower.cooldownEndBlock <= block.number); cooldownIndex = uint256(flower.cooldownIndex); nextActionAt = uint256(flower.cooldownEndBlock); birthTime = uint256(flower.birthTime); matronId = uint256(flower.matronId); sireId = uint256(flower.sireId); generation = uint256(flower.generation); genes = flower.genes; } // Start the game function unstop() public onlyAdministrator whenStopped { require(geneScience != address(0)); super.setStart(); } }
Gets the token ID at a given index of the tokens list of the requested owner _owner address owning the tokens list to be accessed _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]; }
12,829,684
pragma solidity 0.4.24; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { UnlimitedAllowanceToken } from "./UnlimitedAllowanceToken.sol"; /** * @title VeilEther * @author Veil * * WETH-like token with the ability to deposit ETH and approve in a single transaction */ contract VeilEther is UnlimitedAllowanceToken { using SafeMath for uint256; /* ============ Constants ============ */ string constant public name = "Veil Ether"; // solium-disable-line uppercase string constant public symbol = "Veil ETH"; // solium-disable-line uppercase uint256 constant public decimals = 18; // solium-disable-line uppercase /* ============ Events ============ */ event Deposit(address indexed dest, uint256 amount); event Withdrawal(address indexed src, uint256 amount); /* ============ Constructor ============ */ constructor () public { } /* ============ Public functions ============ */ /** * @dev Fallback function can be used to buy tokens by proxying the call to deposit() */ function() public payable { deposit(); } /* ============ New functionality ============ */ /** * Buys tokens with Ether, exchanging them 1:1 and sets the spender allowance * * @param _spender Spender address for the allowance * @param _allowance Allowance amount */ function depositAndApprove(address _spender, uint256 _allowance) public payable returns (bool) { deposit(); approve(_spender, _allowance); return true; } /** * Buys tokens with Ether, exchanging them 1:1, and transfers them to a target address instead of msg.sender * * @param _target Address to send the tokens */ function depositAndTransfer(address _target) public payable returns (bool) { deposit(); transfer(_target, msg.value); return true; } /** * Withdraws from msg.sender's balance and transfers to a target address instead of msg.sender * * @param _amount Amount to withdraw * @param _target Address to send the withdrawn ETH */ function withdrawAndTransfer(uint256 _amount, address _target) public returns (bool) { require(balances[msg.sender] >= _amount, "Insufficient user balance"); require(_target != address(0), "Invalid target address"); balances[msg.sender] = balances[msg.sender].sub(_amount); totalSupply = totalSupply.sub(_amount); _target.transfer(_amount); emit Withdrawal(msg.sender, _amount); return true; } /* ============ Standard WETH functionality ============ */ function deposit() public payable returns (bool) { balances[msg.sender] = balances[msg.sender].add(msg.value); totalSupply = totalSupply.add(msg.value); emit Deposit(msg.sender, msg.value); return true; } function withdraw(uint256 _amount) public returns (bool) { require(balances[msg.sender] >= _amount, "Insufficient user balance"); balances[msg.sender] = balances[msg.sender].sub(_amount); totalSupply = totalSupply.sub(_amount); msg.sender.transfer(_amount); emit Withdrawal(msg.sender, _amount); return true; } }
Buys tokens with Ether, exchanging them 1:1 and sets the spender allowance _spender Spender address for the allowance _allowance Allowance amount/
function depositAndApprove(address _spender, uint256 _allowance) public payable returns (bool) { deposit(); approve(_spender, _allowance); return true; }
1,034,583
./full_match/4/0x1a2de9D65efD81Ba67467E0124972C1959d97A94/sources/contracts/Magi.sol
Claim Magi Gold for a given Adventure Cards ID tokenId The tokenId of the Adventure Cards NFT Follow the Checks-Effects-Interactions pattern to prevent reentrancy attacks Checks Check that the msgSender owns the token that is being claimed Further Checks, Effects, and Interactions are contained within the _claim() function
function claimById(uint256 tokenId) external { require( _msgSender() == adventureCardsContract.ownerOf(tokenId), "MUST_OWN_TOKEN_ID" ); _claim(tokenId, _msgSender()); }
12,326,300
./full_match/42/0x1cd45CcADda892956aa5d7C61167acdb4dAe8262/sources/browser/JCompound.sol
get Tranche A exchange rate _trancheNum tranche number return tranche A token current price/
function getTrancheAExchangeRate(uint256 _trancheNum) public view returns (uint256) { return trancheParameters[_trancheNum].currentTrancheAPrice; }
16,227,491
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "../../interfaces/ICampaignReward.sol"; library CampaignRewardLib { /** * @dev Assigns a reward to the user * @param _campaignReward Campaign reward interface */ function _assignReward( ICampaignReward _campaignReward, uint256 _rewardId, uint256 _amount, address _user ) internal returns (uint256) { return _campaignReward.assignReward(_rewardId, _amount, _user); } /** * @dev Renounces rewards owned by the specified user * @param _user Address of user who rewards are being renounced */ function _renounceRewards(ICampaignReward _campaignReward, address _user) internal { _campaignReward.renounceRewards(_user); } /** * @dev Transfers rewards from the old owner to a new owner * @param _campaignReward Campaign reward interface * @param _oldAddress Address of previous owner of rewards * @param _newAddress Address of new owner rewards are being transferred to */ function _transferRewards( ICampaignReward _campaignReward, address _oldAddress, address _newAddress ) internal { _campaignReward.transferRewards(_oldAddress, _newAddress); } }
Transfers rewards from the old owner to a new owner _campaignReward Campaign reward interface _oldAddress Address of previous owner of rewards _newAddress Address of new owner rewards are being transferred to/
function _transferRewards( ICampaignReward _campaignReward, address _oldAddress, address _newAddress ) internal { _campaignReward.transferRewards(_oldAddress, _newAddress); }
1,823,357
./partial_match/1/0xB0F720Baa5BD1715897d4790A59f5c7aa1377D79/sources/MateriaLiquidityAdder.sol
value now is for the possible dust
function addLiquidityItem( uint256 itemId, uint256 value, address from, bytes memory payload ) private returns (uint256 itemAmount, uint256 bridgeAmount) { address erc20Wrapper = address(IMateriaOrchestrator(address(this)).erc20Wrapper()); address bridgeToken = address(IMateriaOrchestrator(address(this)).bridgeToken()); uint256 bridgeAmountDesired; address to; uint256 deadline; address token; (bridgeAmountDesired, itemAmount, bridgeAmount, to, deadline) = abi.decode( payload, (uint256, uint256, uint256, address, uint256) ); _ensure(deadline); (itemAmount, bridgeAmount) = _addLiquidity( (token = address(IERC20WrapperV1(erc20Wrapper).asInteroperable(itemId))), bridgeToken, value, bridgeAmountDesired, itemAmount, bridgeAmount ); address pair = MateriaLibrary.pairFor(address(IMateriaOrchestrator(address(this)).factory()), token, bridgeToken); TransferHelper.safeTransfer(token, pair, itemAmount); TransferHelper.safeTransferFrom(bridgeToken, from, pair, bridgeAmount); IMateriaPair(pair).mint(to); if ((value = value - itemAmount) > 0) TransferHelper.safeTransfer(token, from, value); if ((value = bridgeAmountDesired - bridgeAmount) > 0) TransferHelper.safeTransfer(bridgeToken, from, value); }
3,922,590
pragma solidity ^0.5.0; //Importing openzeppelin-solidity ERC-721 implemented Standard import "@openzeppelin/contracts/token/ERC721/ERC721Full.sol"; import "@openzeppelin/contracts/drafts/Counters.sol"; // StarNotary Contract declaration inheritance the ERC721 openzeppelin implementation contract StarNotary is ERC721Full { using Counters for Counters.Counter; Counters.Counter private _tokenIds; // Star data struct Star { string name; } // Implement Task 1 Add a name and symbol properties // name: Is a short name to your token // symbol: Is a short string like 'USD' -> 'American Dollar' constructor() ERC721Full("StarItem", "STAR") public { } // mapping the Star with the Owner Address mapping(uint256 => Star) public tokenIdToStarInfo; // mapping the TokenId and price mapping(uint256 => uint256) public starsForSale; event ReturnUintValue(address indexed _from, uint256 _value); // Create Star using the Struct function createStar(string calldata _name) external returns (uint256) { // Passing the name as a parameter _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); Star memory newStar = Star(_name); // Star is an struct so we are creating a new Star _mint(msg.sender, newItemId); // _mint assign the the star with newItemId to the sender address (ownership) tokenIdToStarInfo[newItemId] = newStar; // Creating in memory the Star -> newItemId mapping emit ReturnUintValue(msg.sender, newItemId); return newItemId; } // Putting an Star for sale (Adding the star tokenid into the mapping starsForSale, first verify that the sender is the owner) function putStarUpForSale(uint256 _tokenId, uint256 _price) public { require(ownerOf(_tokenId) == msg.sender, "You can't sell Star you don't own"); starsForSale[_tokenId] = _price; } // Function that allows you to convert an address into a payable address function _make_payable(address x) internal pure returns (address payable) { return address(uint160(x)); } function buyStar(uint256 _tokenId) public payable { require(starsForSale[_tokenId] > 0, "The Star should be up for sale"); uint256 starCost = starsForSale[_tokenId]; address ownerAddress = ownerOf(_tokenId); require(msg.value >= starCost, "You need to have enough Ether"); _transferFrom(ownerAddress, msg.sender, _tokenId); // We can't use _addTokenTo or_removeTokenFrom functions, now we have to use _transferFrom address payable ownerAddressPayable = _make_payable(ownerAddress); // We need to make this conversion to be able to use transfer() function to transfer ethers ownerAddressPayable.transfer(starCost); if(msg.value > starCost) { msg.sender.transfer(msg.value - starCost); } starsForSale[_tokenId] = 0; } // Implement Task 1 lookUptokenIdToStarInfo function lookUptokenIdToStarInfo(uint _tokenId) public view returns (string memory) { require(_exists(_tokenId), "The Star does not exist"); //1. You should return the Star saved in tokenIdToStarInfo mapping return tokenIdToStarInfo[_tokenId].name; } // Implement Task 1 Exchange Stars function function exchangeStars(uint256 _tokenId1, uint256 _tokenId2) public { require( _exists(_tokenId1) && _exists(_tokenId2), "In order to exchange Stars, they must exist" ); //3. Get the owner of the two tokens (ownerOf(_tokenId1), ownerOf(_tokenId1) address ownerTokenId1 = ownerOf(_tokenId1); address ownerTokenId2 = ownerOf(_tokenId2); require(ownerTokenId1 != ownerTokenId2, "Both Stars are owned by the same owner"); //1. Passing to star tokenId you will need to check if the owner of _tokenId1 or _tokenId2 is the sender //2. You don't have to check for the price of the token (star) require( msg.sender == ownerTokenId1 || msg.sender == ownerTokenId2, "You can't exchange Star you don't own" ); //4. Use _transferFrom function to exchange the tokens. if(msg.sender == ownerTokenId1) { _transferFrom(msg.sender, ownerTokenId2, _tokenId1); _transferFrom(ownerTokenId2, msg.sender, _tokenId2); } else { _transferFrom(msg.sender, ownerTokenId1, _tokenId2); _transferFrom(ownerTokenId1, msg.sender, _tokenId1); } } // Implement Task 1 Transfer Stars function transferStar(address _to1, uint256 _tokenId) public { //1. Check if the sender is the ownerOf(_tokenId) require(ownerOf(_tokenId) == msg.sender, "You can't transfer Star you don't own"); //2. Use the transferFrom(from, to, tokenId); function to transfer the Star transferFrom(msg.sender, _to1, _tokenId); } }
Implement Task 1 lookUptokenIdToStarInfo1. You should return the Star saved in tokenIdToStarInfo mapping
function lookUptokenIdToStarInfo(uint _tokenId) public view returns (string memory) { require(_exists(_tokenId), "The Star does not exist"); return tokenIdToStarInfo[_tokenId].name; }
6,455,807
./full_match/80001/0xd99115AF3c77B846B95C8d421B3779351912A381/sources/project_/contracts/Platform/XG_Game_ERC721A.sol
Bulk mint tokens for `gameTokenIds_` Mint `amount_` tokens to_ (address) Mint address gameTokenIds_ (uint256[] calldata) GameToken IDs feeNumerators_ (uint96[] calldata) Fee numerators
function bulkMintToken( address to_, uint256[] calldata gameTokenIds_, uint96[] calldata feeNumerators_ ) external onlyOwner { if (gameTokenIds_.length != feeNumerators_.length) { revert InvalidArrayLength(); } unchecked { uint256 currentId = _nextTokenId(); uint256 gameTokenIdsAmount = gameTokenIds_.length; for (uint256 i; i < gameTokenIdsAmount; ++i) { _totalSupplyPerGameToken[gameTokenIds_[i]] = _totalSupplyPerGameToken[gameTokenIds_[i]] + 1; _tokenIdPerGameToken[currentId] = gameTokenIds_[i]; _setTokenRoyalty(currentId, treasury(), feeNumerators_[i]); ++currentId; } _mint(to_, gameTokenIdsAmount); } }
5,575,365
pragma solidity ^0.4.18; /** * @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 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 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) { 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; 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); 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function _burn(address _burner, uint256 _value) internal { require(_value <= balances[_burner]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_burner] = balances[_burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(_burner, _value); Transfer(_burner, address(0), _value); } } contract DividendPayoutToken is BurnableToken, MintableToken { // Dividends already claimed by investor mapping(address => uint256) public dividendPayments; // Total dividends claimed by all investors uint256 public totalDividendPayments; // invoke this function after each dividend payout function increaseDividendPayments(address _investor, uint256 _amount) onlyOwner public { dividendPayments[_investor] = dividendPayments[_investor].add(_amount); totalDividendPayments = totalDividendPayments.add(_amount); } //When transfer tokens decrease dividendPayments for sender and increase for receiver function transfer(address _to, uint256 _value) public returns (bool) { // balance before transfer uint256 oldBalanceFrom = balances[msg.sender]; // invoke super function with requires bool isTransferred = super.transfer(_to, _value); uint256 transferredClaims = dividendPayments[msg.sender].mul(_value).div(oldBalanceFrom); dividendPayments[msg.sender] = dividendPayments[msg.sender].sub(transferredClaims); dividendPayments[_to] = dividendPayments[_to].add(transferredClaims); return isTransferred; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { // balance before transfer uint256 oldBalanceFrom = balances[_from]; // invoke super function with requires bool isTransferred = super.transferFrom(_from, _to, _value); uint256 transferredClaims = dividendPayments[_from].mul(_value).div(oldBalanceFrom); dividendPayments[_from] = dividendPayments[_from].sub(transferredClaims); dividendPayments[_to] = dividendPayments[_to].add(transferredClaims); return isTransferred; } function burn() public { address burner = msg.sender; // balance before burning tokens uint256 oldBalance = balances[burner]; super._burn(burner, oldBalance); uint256 burnedClaims = dividendPayments[burner]; dividendPayments[burner] = dividendPayments[burner].sub(burnedClaims); totalDividendPayments = totalDividendPayments.sub(burnedClaims); SaleInterface(owner).refund(burner); } } contract RicoToken is DividendPayoutToken { string public constant name = "Rico"; string public constant symbol = "Rico"; uint8 public constant decimals = 18; } // Interface for PreSale and CrowdSale contracts with refund function contract SaleInterface { function refund(address _to) public; } contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancy_lock); reentrancy_lock = true; _; reentrancy_lock = false; } } contract PreSale is Ownable, ReentrancyGuard { using SafeMath for uint256; // The token being sold RicoToken public token; address tokenContractAddress; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // Address where funds are transferred after success end of PreSale address public wallet; // How many token units a buyer gets per wei uint256 public rate; uint256 public minimumInvest; // in wei uint256 public softCap; // in wei uint256 public hardCap; // in wei // investors => amount of money mapping(address => uint) public balances; // Amount of wei raised uint256 public weiRaised; // PreSale bonus in percent uint256 bonusPercent; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function PreSale( address _token) public { startTime = 1525251600; endTime = startTime + 60 minutes; wallet = 0x2c9660f30B65dbBfd6540d252f6Fa07B5854a40f; token = RicoToken(_token); tokenContractAddress = _token; // minimumInvest in wei minimumInvest = 1000000000000; // 1 token for approximately 0.00015 eth rate = 1000; softCap = 150 * 0.000001 ether; hardCap = 1500 * 0.000001 ether; bonusPercent = 50; } // @return true if the transaction can buy tokens modifier saleIsOn() { bool withinPeriod = now >= startTime && now <= endTime; require(withinPeriod); _; } modifier isUnderHardCap() { require(weiRaised < hardCap); _; } modifier refundAllowed() { require(weiRaised < softCap && now > endTime); _; } // @return true if PreSale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // Refund ether to the investors (invoke from only token) function refund(address _to) public refundAllowed { require(msg.sender == tokenContractAddress); uint256 valueToReturn = balances[_to]; // update states balances[_to] = 0; weiRaised = weiRaised.sub(valueToReturn); _to.transfer(valueToReturn); } // Get amount of tokens // @param value weis paid for tokens function getTokenAmount(uint256 _value) internal view returns (uint256) { return _value.mul(rate); } // Send weis to the wallet function forwardFunds(uint256 _value) internal { wallet.transfer(_value); } // Success finish of PreSale function finishPreSale() public onlyOwner { require(weiRaised >= softCap); require(weiRaised >= hardCap || now > endTime); if (now < endTime) { endTime = now; } forwardFunds(this.balance); token.transferOwnership(owner); } // Change owner of token after end of PreSale if Soft Cap has not raised function changeTokenOwner() public onlyOwner { require(now > endTime && weiRaised < softCap); token.transferOwnership(owner); } // low level token purchase function function buyTokens(address _beneficiary) saleIsOn isUnderHardCap nonReentrant public payable { require(_beneficiary != address(0)); require(msg.value >= minimumInvest); uint256 weiAmount = msg.value; uint256 tokens = getTokenAmount(weiAmount); tokens = tokens.add(tokens.mul(bonusPercent).div(100)); token.mint(_beneficiary, tokens); // update states weiRaised = weiRaised.add(weiAmount); balances[_beneficiary] = balances[_beneficiary].add(weiAmount); TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); } function() external payable { buyTokens(msg.sender); } }
Function to mint tokens _to The address that will receive the minted tokens. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; }
111,676
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPosition Contract /// @author Enzyme Council <[email protected]> interface IExternalPosition { function getDebtAssets() external returns (address[] memory, uint256[] memory); function getManagedAssets() external returns (address[] memory, uint256[] memory); function init(bytes memory) external; function receiveCallFromVault(bytes memory) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionVault interface /// @author Enzyme Council <[email protected]> /// Provides an interface to get the externalPositionLib for a given type from the Vault interface IExternalPositionVault { function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFreelyTransferableSharesVault Interface /// @author Enzyme Council <[email protected]> /// @notice Provides the interface for determining whether a vault's shares /// are guaranteed to be freely transferable. /// @dev DO NOT EDIT CONTRACT interface IFreelyTransferableSharesVault { function sharesAreFreelyTransferable() external view returns (bool sharesAreFreelyTransferable_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/dispatcher/IMigrationHookHandler.sol"; import "../../extensions/IExtension.sol"; import "../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../infrastructure/protocol-fees/IProtocolFeeTracker.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler, GasRelayRecipientMixin { event BuySharesOnBehalfCallerDeregistered(address caller); event BuySharesOnBehalfCallerRegistered(address caller); event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock ); event GasLimitsForDestructCallSet( uint256 nextDeactivateFeeManagerGasLimit, uint256 nextPayProtocolFeeGasLimit ); event MigrationRequestCreated( address indexed creator, address indexed vaultProxy, address comptrollerProxy ); event NewFundCreated(address indexed creator, address vaultProxy, address comptrollerProxy); event ProtocolFeeTrackerSet(address protocolFeeTracker); event ReconfigurationRequestCancelled( address indexed vaultProxy, address indexed nextComptrollerProxy ); event ReconfigurationRequestCreated( address indexed creator, address indexed vaultProxy, address comptrollerProxy, uint256 executableTimestamp ); event ReconfigurationRequestExecuted( address indexed vaultProxy, address indexed prevComptrollerProxy, address indexed nextComptrollerProxy ); event ReconfigurationTimelockSet(uint256 nextTimelock); event ReleaseIsLive(); event VaultCallDeregistered( address indexed contractAddress, bytes4 selector, bytes32 dataHash ); event VaultCallRegistered(address indexed contractAddress, bytes4 selector, bytes32 dataHash); event VaultLibSet(address vaultLib); struct ReconfigurationRequest { address nextComptrollerProxy; uint256 executableTimestamp; } // Constants // keccak256(abi.encodePacked("mln.vaultCall.any") bytes32 private constant ANY_VAULT_CALL = 0x5bf1898dd28c4d29f33c4c1bb9b8a7e2f6322847d70be63e8f89de024d08a669; address private immutable CREATOR; address private immutable DISPATCHER; // Pseudo-constants (can only be set once) address private comptrollerLib; address private protocolFeeTracker; address private vaultLib; // Storage uint32 private gasLimitForDestructCallToDeactivateFeeManager; // Can reduce to uint16 uint32 private gasLimitForDestructCallToPayProtocolFee; // Can reduce to uint16 bool private isLive; uint256 private reconfigurationTimelock; mapping(address => bool) private acctToIsAllowedBuySharesOnBehalfCaller; mapping(bytes32 => mapping(bytes32 => bool)) private vaultCallToPayloadToIsAllowed; mapping(address => ReconfigurationRequest) private vaultProxyToReconfigurationRequest; modifier onlyDispatcher() { require(msg.sender == DISPATCHER, "Only Dispatcher can call this function"); _; } modifier onlyLiveRelease() { require(releaseIsLive(), "Release is not yet live"); _; } modifier onlyMigrator(address _vaultProxy) { __assertIsMigrator(_vaultProxy, __msgSender()); _; } modifier onlyMigratorNotRelayable(address _vaultProxy) { __assertIsMigrator(_vaultProxy, msg.sender); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier pseudoConstant(address _storageValue) { require(_storageValue == address(0), "This value can only be set once"); _; } function __assertIsMigrator(address _vaultProxy, address _who) private view { require( IVault(_vaultProxy).canMigrate(_who), "Only a permissioned migrator can call this function" ); } constructor(address _dispatcher, address _gasRelayPaymasterFactory) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { // Validate constants require( ANY_VAULT_CALL == keccak256(abi.encodePacked("mln.vaultCall.any")), "constructor: Incorrect ANY_VAULT_CALL" ); CREATOR = msg.sender; DISPATCHER = _dispatcher; // Estimated base call cost: 17k // Per fee that uses shares outstanding (default recipient): 33k // 300k accommodates up to 8 such fees gasLimitForDestructCallToDeactivateFeeManager = 300000; // Estimated cost: 50k gasLimitForDestructCallToPayProtocolFee = 200000; reconfigurationTimelock = 2 days; } ////////////////////////////////////// // PSEUDO-CONSTANTS (only set once) // ////////////////////////////////////// /// @notice Sets the ComptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address function setComptrollerLib(address _comptrollerLib) external onlyOwner pseudoConstant(getComptrollerLib()) { comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the ProtocolFeeTracker /// @param _protocolFeeTracker The ProtocolFeeTracker contract address function setProtocolFeeTracker(address _protocolFeeTracker) external onlyOwner pseudoConstant(getProtocolFeeTracker()) { protocolFeeTracker = _protocolFeeTracker; emit ProtocolFeeTrackerSet(_protocolFeeTracker); } /// @notice Sets the VaultLib /// @param _vaultLib The VaultLib contract address function setVaultLib(address _vaultLib) external onlyOwner pseudoConstant(getVaultLib()) { vaultLib = _vaultLib; emit VaultLibSet(_vaultLib); } ///////////// // GENERAL // ///////////// /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev The owner is initially the contract's creator, for convenience in setting up configuration. /// Ownership is handed-off when the creator calls setReleaseLive(). function getOwner() public view override returns (address owner_) { if (!releaseIsLive()) { return getCreator(); } return IDispatcher(getDispatcher()).getOwner(); } /// @notice Sets the amounts of gas to forward to each of the ComptrollerLib.destructActivated() external calls /// @param _nextDeactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager /// @param _nextPayProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee function setGasLimitsForDestructCall( uint32 _nextDeactivateFeeManagerGasLimit, uint32 _nextPayProtocolFeeGasLimit ) external onlyOwner { require( _nextDeactivateFeeManagerGasLimit > 0 && _nextPayProtocolFeeGasLimit > 0, "setGasLimitsForDestructCall: Zero value not allowed" ); gasLimitForDestructCallToDeactivateFeeManager = _nextDeactivateFeeManagerGasLimit; gasLimitForDestructCallToPayProtocolFee = _nextPayProtocolFeeGasLimit; emit GasLimitsForDestructCallSet( _nextDeactivateFeeManagerGasLimit, _nextPayProtocolFeeGasLimit ); } /// @notice Sets the release as live /// @dev A live release allows funds to be created and migrated once this contract /// is set as the Dispatcher.currentFundDeployer function setReleaseLive() external { require( msg.sender == getCreator(), "setReleaseLive: Only the creator can call this function" ); require(!releaseIsLive(), "setReleaseLive: Already live"); // All pseudo-constants should be set require(getComptrollerLib() != address(0), "setReleaseLive: comptrollerLib is not set"); require( getProtocolFeeTracker() != address(0), "setReleaseLive: protocolFeeTracker is not set" ); require(getVaultLib() != address(0), "setReleaseLive: vaultLib is not set"); isLive = true; emit ReleaseIsLive(); } /// @dev Helper to call ComptrollerProxy.destructActivated() with the correct params function __destructActivatedComptrollerProxy(address _comptrollerProxy) private { ( uint256 deactivateFeeManagerGasLimit, uint256 payProtocolFeeGasLimit ) = getGasLimitsForDestructCall(); IComptroller(_comptrollerProxy).destructActivated( deactivateFeeManagerGasLimit, payProtocolFeeGasLimit ); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy instance for a VaultProxy and signals the migration process /// @param _vaultProxy The VaultProxy to migrate /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while signaling migration /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigrationRequest( address _vaultProxy, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData, bool _bypassPrevReleaseFailure ) external onlyLiveRelease onlyMigratorNotRelayable(_vaultProxy) returns (address comptrollerProxy_) { // Bad _vaultProxy value is validated by Dispatcher.signalMigration() require( !IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy), "createMigrationRequest: A MigrationRequest already exists" ); comptrollerProxy_ = __deployComptrollerProxy( msg.sender, _denominationAsset, _sharesActionTimelock ); IComptroller(comptrollerProxy_).setVaultProxy(_vaultProxy); __configureExtensions( comptrollerProxy_, _vaultProxy, _feeManagerConfigData, _policyManagerConfigData ); IDispatcher(getDispatcher()).signalMigration( _vaultProxy, comptrollerProxy_, getVaultLib(), _bypassPrevReleaseFailure ); emit MigrationRequestCreated(msg.sender, _vaultProxy, comptrollerProxy_); return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund's shares token /// @param _fundSymbol The symbol of the fund's shares token /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, string calldata _fundSymbol, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { // _fundOwner is validated by VaultLib.__setOwner() address canonicalSender = __msgSender(); comptrollerProxy_ = __deployComptrollerProxy( canonicalSender, _denominationAsset, _sharesActionTimelock ); vaultProxy_ = __deployVaultProxy(_fundOwner, comptrollerProxy_, _fundName, _fundSymbol); IComptroller comptrollerContract = IComptroller(comptrollerProxy_); comptrollerContract.setVaultProxy(vaultProxy_); __configureExtensions( comptrollerProxy_, vaultProxy_, _feeManagerConfigData, _policyManagerConfigData ); comptrollerContract.activate(false); IProtocolFeeTracker(getProtocolFeeTracker()).initializeForVault(vaultProxy_); emit NewFundCreated(canonicalSender, vaultProxy_, comptrollerProxy_); return (comptrollerProxy_, vaultProxy_); } /// @notice Creates a fully-configured ComptrollerProxy instance for a VaultProxy and signals the reconfiguration process /// @param _vaultProxy The VaultProxy to reconfigure /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createReconfigurationRequest( address _vaultProxy, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external returns (address comptrollerProxy_) { address canonicalSender = __msgSender(); __assertIsMigrator(_vaultProxy, canonicalSender); require( IDispatcher(getDispatcher()).getFundDeployerForVaultProxy(_vaultProxy) == address(this), "createReconfigurationRequest: VaultProxy not on this release" ); require( !hasReconfigurationRequest(_vaultProxy), "createReconfigurationRequest: VaultProxy has a pending reconfiguration request" ); comptrollerProxy_ = __deployComptrollerProxy( canonicalSender, _denominationAsset, _sharesActionTimelock ); IComptroller(comptrollerProxy_).setVaultProxy(_vaultProxy); __configureExtensions( comptrollerProxy_, _vaultProxy, _feeManagerConfigData, _policyManagerConfigData ); uint256 executableTimestamp = block.timestamp + getReconfigurationTimelock(); vaultProxyToReconfigurationRequest[_vaultProxy] = ReconfigurationRequest({ nextComptrollerProxy: comptrollerProxy_, executableTimestamp: executableTimestamp }); emit ReconfigurationRequestCreated( canonicalSender, _vaultProxy, comptrollerProxy_, executableTimestamp ); return comptrollerProxy_; } /// @dev Helper function to configure the Extensions for a given ComptrollerProxy function __configureExtensions( address _comptrollerProxy, address _vaultProxy, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private { // Since fees can only be set in this step, if there are no fees, there is no need to set the validated VaultProxy if (_feeManagerConfigData.length > 0) { IExtension(IComptroller(_comptrollerProxy).getFeeManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, _feeManagerConfigData ); } // For all other extensions, we call to cache the validated VaultProxy, for simplicity. // In the future, we can consider caching conditionally. IExtension(IComptroller(_comptrollerProxy).getExternalPositionManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, "" ); IExtension(IComptroller(_comptrollerProxy).getIntegrationManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, "" ); IExtension(IComptroller(_comptrollerProxy).getPolicyManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, _policyManagerConfigData ); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _canonicalSender, address _denominationAsset, uint256 _sharesActionTimelock ) private returns (address comptrollerProxy_) { // _denominationAsset is validated by ComptrollerLib.init() bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, getComptrollerLib())); emit ComptrollerProxyDeployed( _canonicalSender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock ); return comptrollerProxy_; } /// @dev Helper to deploy a new VaultProxy instance during fund creation. /// Avoids stack-too-deep error. function __deployVaultProxy( address _fundOwner, address _comptrollerProxy, string calldata _fundName, string calldata _fundSymbol ) private returns (address vaultProxy_) { vaultProxy_ = IDispatcher(getDispatcher()).deployVaultProxy( getVaultLib(), _fundOwner, _comptrollerProxy, _fundName ); if (bytes(_fundSymbol).length != 0) { IVault(vaultProxy_).setSymbol(_fundSymbol); } return vaultProxy_; } /////////////////////////////////////////////// // RECONFIGURATION (INTRA-RELEASE MIGRATION) // /////////////////////////////////////////////// /// @notice Cancels a pending reconfiguration request /// @param _vaultProxy The VaultProxy contract for which to cancel the reconfiguration request function cancelReconfiguration(address _vaultProxy) external onlyMigrator(_vaultProxy) { address nextComptrollerProxy = vaultProxyToReconfigurationRequest[_vaultProxy] .nextComptrollerProxy; require( nextComptrollerProxy != address(0), "cancelReconfiguration: No reconfiguration request exists for _vaultProxy" ); // Destroy the nextComptrollerProxy IComptroller(nextComptrollerProxy).destructUnactivated(); // Remove the reconfiguration request delete vaultProxyToReconfigurationRequest[_vaultProxy]; emit ReconfigurationRequestCancelled(_vaultProxy, nextComptrollerProxy); } /// @notice Executes a pending reconfiguration request /// @param _vaultProxy The VaultProxy contract for which to execute the reconfiguration request /// @dev ProtocolFeeTracker.initializeForVault() does not need to be included in a reconfiguration, /// as it refers to the vault and not the new ComptrollerProxy function executeReconfiguration(address _vaultProxy) external onlyMigrator(_vaultProxy) { ReconfigurationRequest memory request = getReconfigurationRequestForVaultProxy( _vaultProxy ); require( request.nextComptrollerProxy != address(0), "executeReconfiguration: No reconfiguration request exists for _vaultProxy" ); require( block.timestamp >= request.executableTimestamp, "executeReconfiguration: The reconfiguration timelock has not elapsed" ); // Not technically necessary, but a nice assurance require( IDispatcher(getDispatcher()).getFundDeployerForVaultProxy(_vaultProxy) == address(this), "executeReconfiguration: _vaultProxy is no longer on this release" ); // Unwind and destroy the prevComptrollerProxy before setting the nextComptrollerProxy as the VaultProxy.accessor address prevComptrollerProxy = IVault(_vaultProxy).getAccessor(); address paymaster = IComptroller(prevComptrollerProxy).getGasRelayPaymaster(); __destructActivatedComptrollerProxy(prevComptrollerProxy); // Execute the reconfiguration IVault(_vaultProxy).setAccessorForFundReconfiguration(request.nextComptrollerProxy); // Activate the new ComptrollerProxy IComptroller(request.nextComptrollerProxy).activate(true); if (paymaster != address(0)) { IComptroller(request.nextComptrollerProxy).setGasRelayPaymaster(paymaster); } // Remove the reconfiguration request delete vaultProxyToReconfigurationRequest[_vaultProxy]; emit ReconfigurationRequestExecuted( _vaultProxy, prevComptrollerProxy, request.nextComptrollerProxy ); } /// @notice Sets a new reconfiguration timelock /// @param _nextTimelock The number of seconds for the new timelock function setReconfigurationTimelock(uint256 _nextTimelock) external onlyOwner { reconfigurationTimelock = _nextTimelock; emit ReconfigurationTimelockSet(_nextTimelock); } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration /// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while canceling migration function cancelMigration(address _vaultProxy, bool _bypassPrevReleaseFailure) external onlyMigratorNotRelayable(_vaultProxy) { IDispatcher(getDispatcher()).cancelMigration(_vaultProxy, _bypassPrevReleaseFailure); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration /// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while executing migration function executeMigration(address _vaultProxy, bool _bypassPrevReleaseFailure) external onlyMigratorNotRelayable(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(getDispatcher()); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassPrevReleaseFailure); IComptroller(comptrollerProxy).activate(true); IProtocolFeeTracker(getProtocolFeeTracker()).initializeForVault(_vaultProxy); } /// @notice Executes logic when a migration is canceled on the Dispatcher /// @param _nextComptrollerProxy The ComptrollerProxy created on this release function invokeMigrationInCancelHook( address, address, address _nextComptrollerProxy, address ) external override onlyDispatcher { IComptroller(_nextComptrollerProxy).destructUnactivated(); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override onlyDispatcher { if (_hook != MigrationOutHook.PreMigrate) { return; } // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config __destructActivatedComptrollerProxy(comptrollerProxy); } ////////////// // REGISTRY // ////////////// // BUY SHARES CALLERS /// @notice Deregisters allowed callers of ComptrollerProxy.buySharesOnBehalf() /// @param _callers The callers to deregister function deregisterBuySharesOnBehalfCallers(address[] calldata _callers) external onlyOwner { for (uint256 i; i < _callers.length; i++) { require( isAllowedBuySharesOnBehalfCaller(_callers[i]), "deregisterBuySharesOnBehalfCallers: Caller not registered" ); acctToIsAllowedBuySharesOnBehalfCaller[_callers[i]] = false; emit BuySharesOnBehalfCallerDeregistered(_callers[i]); } } /// @notice Registers allowed callers of ComptrollerProxy.buySharesOnBehalf() /// @param _callers The allowed callers /// @dev Validate that each registered caller only forwards requests to buy shares that /// originate from the same _buyer passed into buySharesOnBehalf(). This is critical /// to the integrity of VaultProxy.freelyTransferableShares. function registerBuySharesOnBehalfCallers(address[] calldata _callers) external onlyOwner { for (uint256 i; i < _callers.length; i++) { require( !isAllowedBuySharesOnBehalfCaller(_callers[i]), "registerBuySharesOnBehalfCallers: Caller already registered" ); acctToIsAllowedBuySharesOnBehalfCaller[_callers[i]] = true; emit BuySharesOnBehalfCallerRegistered(_callers[i]); } } // VAULT CALLS /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register /// @param _dataHashes The keccak call data hashes of the calls to de-register /// @dev ANY_VAULT_CALL is a wildcard that allows any payload function deregisterVaultCalls( address[] calldata _contracts, bytes4[] calldata _selectors, bytes32[] memory _dataHashes ) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length && _contracts.length == _dataHashes.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i], _dataHashes[i]), "deregisterVaultCalls: Call not registered" ); vaultCallToPayloadToIsAllowed[keccak256( abi.encodePacked(_contracts[i], _selectors[i]) )][_dataHashes[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i], _dataHashes[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register /// @param _dataHashes The keccak call data hashes of the calls to register /// @dev ANY_VAULT_CALL is a wildcard that allows any payload function registerVaultCalls( address[] calldata _contracts, bytes4[] calldata _selectors, bytes32[] memory _dataHashes ) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length && _contracts.length == _dataHashes.length, "registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i], _dataHashes[i]), "registerVaultCalls: Call already registered" ); vaultCallToPayloadToIsAllowed[keccak256( abi.encodePacked(_contracts[i], _selectors[i]) )][_dataHashes[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i], _dataHashes[i]); } } /////////////////// // STATE GETTERS // /////////////////// // EXTERNAL FUNCTIONS /// @notice Checks if a contract call is allowed /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @param _dataHash The keccak call data hash of the call to check /// @return isAllowed_ True if the call is allowed /// @dev A vault call is allowed if the _dataHash is specifically allowed, /// or if any _dataHash is allowed function isAllowedVaultCall( address _contract, bytes4 _selector, bytes32 _dataHash ) external view override returns (bool isAllowed_) { bytes32 contractFunctionHash = keccak256(abi.encodePacked(_contract, _selector)); return vaultCallToPayloadToIsAllowed[contractFunctionHash][_dataHash] || vaultCallToPayloadToIsAllowed[contractFunctionHash][ANY_VAULT_CALL]; } // PUBLIC FUNCTIONS /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() public view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() public view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the amounts of gas to forward to each of the ComptrollerLib.destructActivated() external calls /// @return deactivateFeeManagerGasLimit_ The amount of gas to forward to deactivate the FeeManager /// @return payProtocolFeeGasLimit_ The amount of gas to forward to pay the protocol fee function getGasLimitsForDestructCall() public view returns (uint256 deactivateFeeManagerGasLimit_, uint256 payProtocolFeeGasLimit_) { return ( gasLimitForDestructCallToDeactivateFeeManager, gasLimitForDestructCallToPayProtocolFee ); } /// @notice Gets the `protocolFeeTracker` variable value /// @return protocolFeeTracker_ The `protocolFeeTracker` variable value function getProtocolFeeTracker() public view returns (address protocolFeeTracker_) { return protocolFeeTracker; } /// @notice Gets the pending ReconfigurationRequest for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return reconfigurationRequest_ The pending ReconfigurationRequest function getReconfigurationRequestForVaultProxy(address _vaultProxy) public view returns (ReconfigurationRequest memory reconfigurationRequest_) { return vaultProxyToReconfigurationRequest[_vaultProxy]; } /// @notice Gets the amount of time that must pass before executing a ReconfigurationRequest /// @return reconfigurationTimelock_ The timelock value (in seconds) function getReconfigurationTimelock() public view returns (uint256 reconfigurationTimelock_) { return reconfigurationTimelock; } /// @notice Gets the `vaultLib` variable value /// @return vaultLib_ The `vaultLib` variable value function getVaultLib() public view returns (address vaultLib_) { return vaultLib; } /// @notice Checks whether a ReconfigurationRequest exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasReconfigurationRequest_ True if a ReconfigurationRequest exists function hasReconfigurationRequest(address _vaultProxy) public view override returns (bool hasReconfigurationRequest_) { return vaultProxyToReconfigurationRequest[_vaultProxy].nextComptrollerProxy != address(0); } /// @notice Checks if an account is an allowed caller of ComptrollerProxy.buySharesOnBehalf() /// @param _who The account to check /// @return isAllowed_ True if the account is an allowed caller function isAllowedBuySharesOnBehalfCaller(address _who) public view override returns (bool isAllowed_) { return acctToIsAllowedBuySharesOnBehalfCaller[_who]; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @param _dataHash The keccak call data hash of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall( address _contract, bytes4 _selector, bytes32 _dataHash ) public view returns (bool isRegistered_) { return vaultCallToPayloadToIsAllowed[keccak256( abi.encodePacked(_contract, _selector) )][_dataHash]; } /// @notice Gets the `isLive` variable value /// @return isLive_ The `isLive` variable value function releaseIsLive() public view returns (bool isLive_) { return isLive; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/external-positions/IExternalPosition.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback); event BuyBackMaxProtocolFeeSharesFailed( bytes indexed failureReturnData, uint256 sharesAmount, uint256 buybackValueInMln, uint256 gav ); event DeactivateFeeManagerFailed(); event GasRelayPaymasterSet(address gasRelayPaymaster); event MigratedSharesDuePaid(uint256 sharesDue); event PayProtocolFeeDuringDestructFailed(); event PreRedeemSharesHookFailed( bytes indexed failureReturnData, address indexed redeemer, uint256 sharesAmount ); event RedeemSharesInKindCalcGavFailed(); event SharesBought( address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, address indexed recipient, uint256 sharesAmount, address[] receivedAssets, uint256[] receivedAssetAmounts ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant ONE_HUNDRED_PERCENT = 10000; uint256 private constant SHARES_UNIT = 10**18; address private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa; address private immutable DISPATCHER; address private immutable EXTERNAL_POSITION_MANAGER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable MLN_TOKEN; address private immutable POLICY_MANAGER; address private immutable PROTOCOL_FEE_RESERVE; address private immutable VALUE_INTERPRETER; address private immutable WETH_TOKEN; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Attempts to buy back protocol fee shares immediately after collection bool internal autoProtocolFeeSharesBuyback; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock after the last time shares were bought for an account // that must expire before that account transfers or redeems their shares uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesBoughtTimestamp; // The contract which manages paying gas relayers address private gasRelayPaymaster; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyFundDeployer() { __assertIsFundDeployer(); _; } modifier onlyGasRelayPaymaster() { __assertIsGasRelayPaymaster(); _; } modifier onlyOwner() { __assertIsOwner(__msgSender()); _; } modifier onlyOwnerNotRelayable() { __assertIsOwner(msg.sender); _; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. function __assertIsFundDeployer() private view { require(msg.sender == getFundDeployer(), "Only FundDeployer callable"); } function __assertIsGasRelayPaymaster() private view { require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _vaultProxy, address _account) private view { uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account); require( lastSharesBoughtTimestamp == 0 || block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() || __hasPendingMigrationOrReconfiguration(_vaultProxy), "Shares action timelocked" ); } constructor( address _dispatcher, address _protocolFeeReserve, address _fundDeployer, address _valueInterpreter, address _externalPositionManager, address _feeManager, address _integrationManager, address _policyManager, address _gasRelayPaymasterFactory, address _mlnToken, address _wethToken ) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { DISPATCHER = _dispatcher; EXTERNAL_POSITION_MANAGER = _externalPositionManager; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; MLN_TOKEN = _mlnToken; POLICY_MANAGER = _policyManager; PROTOCOL_FEE_RESERVE = _protocolFeeReserve; VALUE_INTERPRETER = _valueInterpreter; WETH_TOKEN = _wethToken; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override locksReentrance allowsPermissionedVaultAction { require( _extension == getFeeManager() || _extension == getIntegrationManager() || _extension == getExternalPositionManager(), "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call /// @return returnData_ The data returned by the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyOwner returns (bytes memory returnData_) { require( IFundDeployer(getFundDeployer()).isAllowedVaultCall( _contract, _selector, keccak256(_encodedArgs) ), "vaultCallOnContract: Not allowed" ); return IVault(getVaultProxy()).callOnContract( _contract, abi.encodePacked(_selector, _encodedArgs) ); } /// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request function __hasPendingMigrationOrReconfiguration(address _vaultProxy) private view returns (bool hasPendingMigrationOrReconfiguration) { return IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) || IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy); } ////////////////// // PROTOCOL FEE // ////////////////// /// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN /// @param _sharesAmount The amount of shares to buy back function buyBackProtocolFeeShares(uint256 _sharesAmount) external { address vaultProxyCopy = vaultProxy; require( IVault(vaultProxyCopy).canManageAssets(__msgSender()), "buyBackProtocolFeeShares: Unauthorized" ); uint256 gav = calcGav(); IVault(vaultProxyCopy).buyBackProtocolFeeShares( _sharesAmount, __getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav), gav ); } /// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected /// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted /// to be bought back immediately when collected function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback) external onlyOwner { autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback; emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback); } /// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private { uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve()); uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav); try IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav) {} catch (bytes memory reason) { emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav); } } /// @dev Helper to buyback the max available protocol fee shares function __getBuybackValueInMln( address _vaultProxy, uint256 _sharesAmount, uint256 _gav ) private returns (uint256 buybackValueInMln_) { address denominationAssetCopy = getDenominationAsset(); uint256 grossShareValue = __calcGrossShareValue( _gav, ERC20(_vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div( SHARES_UNIT ); return IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, buybackValueInDenominationAsset, getMlnToken() ); } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData) external override { __assertPermissionedVaultAction(msg.sender, _action); // Validate action as needed if (_action == IVault.VaultAction.RemoveTrackedAsset) { require( abi.decode(_actionData, (address)) != getDenominationAsset(), "permissionedVaultAction: Cannot untrack denomination asset" ); } IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData); } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction. /// Uses this pattern rather than multiple `require` statements to save on contract size. function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action) private view { bool validAction; if (permissionedVaultActionAllowed) { // Calls are roughly ordered by likely frequency if (_caller == getIntegrationManager()) { if ( _action == IVault.VaultAction.AddTrackedAsset || _action == IVault.VaultAction.RemoveTrackedAsset || _action == IVault.VaultAction.WithdrawAssetTo || _action == IVault.VaultAction.ApproveAssetSpender ) { validAction = true; } } else if (_caller == getFeeManager()) { if ( _action == IVault.VaultAction.MintShares || _action == IVault.VaultAction.BurnShares || _action == IVault.VaultAction.TransferShares ) { validAction = true; } } else if (_caller == getExternalPositionManager()) { if ( _action == IVault.VaultAction.CallOnExternalPosition || _action == IVault.VaultAction.AddExternalPosition || _action == IVault.VaultAction.RemoveExternalPosition ) { validAction = true; } } } require(validAction, "__assertPermissionedVaultAction: Action not allowed"); } /////////////// // LIFECYCLE // /////////////// // Ordered by execution in the lifecycle /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(getDenominationAsset() == address(0), "init: Already initialized"); require( IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Sets the VaultProxy /// @param _vaultProxy The VaultProxy contract /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerProxy has been deployed. function setVaultProxy(address _vaultProxy) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); } /// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor` /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(bool _isMigration) external override onlyFundDeployer { address vaultProxyCopy = getVaultProxy(); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy); if (sharesDue > 0) { IVault(vaultProxyCopy).transferShares( vaultProxyCopy, IVault(vaultProxyCopy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset()); // Activate extensions IExtension(getFeeManager()).activateForFund(_isMigration); IExtension(getPolicyManager()).activateForFund(_isMigration); } /// @notice Wind down and destroy a ComptrollerProxy that is active /// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager /// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee /// @dev No need to assert anything beyond FundDeployer access. /// Uses the try/catch pattern throughout out of an abundance of caution for the function's success. /// All external calls must use limited forwarded gas to ensure that a migration to another release /// does not get bricked by logic that consumes too much gas for the block limit. function destructActivated( uint256 _deactivateFeeManagerGasLimit, uint256 _payProtocolFeeGasLimit ) external override onlyFundDeployer allowsPermissionedVaultAction { // Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic // will run in the next function call try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch { emit PayProtocolFeeDuringDestructFailed(); } // Do not attempt to auto-buyback protocol fee shares in this case, // as the call is gav-dependent and can consume too much gas // Deactivate extensions only as-necessary // Pays out shares outstanding for fees try IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}() {} catch { emit DeactivateFeeManagerFailed(); } __selfDestruct(); } /// @notice Destroy a ComptrollerProxy that has not been activated function destructUnactivated() external override onlyFundDeployer { __selfDestruct(); } /// @dev Helper to self-destruct the contract. /// There should never be ETH in the ComptrollerLib, /// so no need to waste gas to get the fund owner function __selfDestruct() private { // Not necessary, but failsafe to protect the lib against selfdestruct require(!isLib, "__selfDestruct: Only delegate callable"); selfdestruct(payable(address(this))); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @return gav_ The fund GAV function calcGav() public override returns (uint256 gav_) { address vaultProxyAddress = getVaultProxy(); address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); address[] memory externalPositions = IVault(vaultProxyAddress) .getActiveExternalPositions(); if (assets.length == 0 && externalPositions.length == 0) { return 0; } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress); } gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( assets, balances, getDenominationAsset() ); if (externalPositions.length > 0) { for (uint256 i; i < externalPositions.length; i++) { uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]); gav_ = gav_.add(externalPositionValue); } } return gav_; } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @return grossShareValue_ The amount of the denomination asset per share /// @dev Does not account for any fees outstanding. function calcGrossShareValue() external override returns (uint256 grossShareValue_) { uint256 gav = calcGav(); grossShareValue_ = __calcGrossShareValue( gav, ERC20(getVaultProxy()).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); return grossShareValue_; } // @dev Helper for calculating a external position value. Prevents from stack too deep function __calcExternalPositionValue(address _externalPosition) private returns (uint256 value_) { (address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition( _externalPosition ) .getManagedAssets(); uint256 managedValue = IValueInterpreter(getValueInterpreter()) .calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset()); (address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition( _externalPosition ) .getDebtAssets(); uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( debtAssets, debtAmounts, getDenominationAsset() ); if (managedValue > debtValue) { value_ = managedValue.sub(debtValue); } return value_; } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares on behalf of another user /// @param _buyer The account on behalf of whom to buy shares /// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received /// @dev This function is freely callable if there is no sharesActionTimelock set, but it is /// limited to a list of trusted callers otherwise, in order to prevent a griefing attack /// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value. function buySharesOnBehalf( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); require( !hasSharesActionTimelock || IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender), "buySharesOnBehalf: Unauthorized" ); return __buyShares( _buyer, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @notice Buys shares /// @param _investmentAmount The amount of the fund's denomination asset /// with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); return __buyShares( canonicalSender, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @dev Helper for buy shares logic function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, bool _hasSharesActionTimelock, address _canonicalSender ) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) { // Enforcing a _minSharesQuantity also validates `_investmentAmount > 0` // and guarantees the function cannot succeed while minting 0 shares require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0"); address vaultProxyCopy = getVaultProxy(); require( !_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy), "__buyShares: Pending migration or reconfiguration" ); uint256 gav = calcGav(); // Gives Extensions a chance to run logic prior to the minting of bought shares. // Fees implementing this hook should be aware that // it might be the case that _investmentAmount != actualInvestmentAmount, // if the denomination asset charges a transfer fee, for example. __preBuySharesHook(_buyer, _investmentAmount, gav); // Pay the protocol fee after running other fees, but before minting new shares IVault(vaultProxyCopy).payProtocolFee(); if (doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(vaultProxyCopy, gav); } // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is necessary to // do this delta balance calculation before calculating shares to mint. uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount( getDenominationAsset(), _canonicalSender, vaultProxyCopy, _investmentAmount ); // Calculate the amount of shares to issue with the investment amount uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer); IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); if (_hasSharesActionTimelock) { acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp; } emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions immediately prior to issuing shares function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _gav ) private { IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount), _gav ); } /// @dev Helper for Extension actions immediately after issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } /// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received function __transferFromWithReceivedAmount( address _asset, address _sender, address _recipient, uint256 _transferAmount ) private returns (uint256 receivedAmount_) { uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient); ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount); return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance); } // REDEEM SHARES /// @notice Redeems a specified amount of the sender's shares for specified asset proportions /// @param _recipient The account that will receive the specified assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _payoutAssets The assets to payout /// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the /// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego. /// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption. function redeemSharesForSpecificAssets( address _recipient, uint256 _sharesQuantity, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages ) external locksReentrance returns (uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _payoutAssets.length == _payoutAssetPercentages.length, "redeemSharesForSpecificAssets: Unequal arrays" ); require( _payoutAssets.isUniqueSet(), "redeemSharesForSpecificAssets: Duplicate payout asset" ); uint256 gav = calcGav(); IVault vaultProxyContract = IVault(getVaultProxy()); (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( vaultProxyContract, canonicalSender, _sharesQuantity, true, gav ); payoutAmounts_ = __payoutSpecifiedAssetPercentages( vaultProxyContract, _recipient, _payoutAssets, _payoutAssetPercentages, gav.mul(sharesToRedeem).div(sharesSupply) ); // Run post-redemption in order to have access to the payoutAmounts __postRedeemSharesForSpecificAssetsHook( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_, gav ); emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_ ); return payoutAmounts_; } /// @notice Redeems a specified amount of the sender's shares /// for a proportionate slice of the vault's assets /// @param _recipient The account that will receive the proportionate slice of assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the _recipient /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function redeemSharesInKind( address _recipient, uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _additionalAssets.isUniqueSet(), "redeemSharesInKind: _additionalAssets contains duplicates" ); require( _assetsToSkip.isUniqueSet(), "redeemSharesInKind: _assetsToSkip contains duplicates" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( IVault(vaultProxy).getTrackedAssets(), _additionalAssets, _assetsToSkip ); // If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees, // as we will require GAV later during the buyback. uint256 gavOrZero; if (doesAutoProtocolFeeSharesBuyback()) { // Since GAV calculation can fail with a revering price or a no-longer-supported asset, // we must try/catch GAV calculation to ensure that in-kind redemption can still succeed try this.calcGav() returns (uint256 gav) { gavOrZero = gav; } catch { emit RedeemSharesInKindCalcGavFailed(); } } (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( IVault(vaultProxy), canonicalSender, _sharesQuantity, false, gavOrZero ); // Calculate and transfer payout asset amounts due to _recipient payoutAmounts_ = new uint256[](payoutAssets_.length); for (uint256 i; i < payoutAssets_.length; i++) { payoutAmounts_[i] = ERC20(payoutAssets_[i]) .balanceOf(vaultProxy) .mul(sharesToRedeem) .div(sharesSupply); // Transfer payout asset to _recipient if (payoutAmounts_[i] > 0) { IVault(vaultProxy).withdrawAssetTo( payoutAssets_[i], _recipient, payoutAmounts_[i] ); } } emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, payoutAssets_, payoutAmounts_ ); return (payoutAssets_, payoutAmounts_); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets() function __payoutSpecifiedAssetPercentages( IVault vaultProxyContract, address _recipient, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages, uint256 _owedGav ) private returns (uint256[] memory payoutAmounts_) { address denominationAssetCopy = getDenominationAsset(); uint256 percentagesTotal; payoutAmounts_ = new uint256[](_payoutAssets.length); for (uint256 i; i < _payoutAssets.length; i++) { percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]); // Used to explicitly specify less than 100% in total _payoutAssetPercentages if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) { continue; } payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, _owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT), _payoutAssets[i] ); // Guards against corner case of primitive-to-derivative asset conversion that floors to 0, // or redeeming a very low shares amount and/or percentage where asset value owed is 0 require( payoutAmounts_[i] > 0, "__payoutSpecifiedAssetPercentages: Zero amount for asset" ); vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]); } require( percentagesTotal == ONE_HUNDRED_PERCENT, "__payoutSpecifiedAssetPercentages: Percents must total 100%" ); return payoutAmounts_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook( address _redeemer, uint256 _sharesToRedeem, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private allowsPermissionedVaultAction { try IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets), _gavIfCalculated ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem); } } /// @dev Helper to run policy validation after other logic for redeeming shares for specific assets. /// Avoids stack-too-deep error. function __postRedeemSharesForSpecificAssetsHook( address _redeemer, address _recipient, uint256 _sharesToRedeemPostFees, address[] memory _assets, uint256[] memory _assetAmounts, uint256 _gavPreRedeem ) private { IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets, abi.encode( _redeemer, _recipient, _sharesToRedeemPostFees, _assets, _assetAmounts, _gavPreRedeem ) ); } /// @dev Helper to execute common pre-shares redemption logic function __redeemSharesSetup( IVault vaultProxyContract, address _redeemer, uint256 _sharesQuantityInput, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) { __assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer); ERC20 sharesContract = ERC20(address(vaultProxyContract)); uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = preFeesRedeemerSharesBalance; } else { sharesToRedeem_ = _sharesQuantityInput; } require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem"); __preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated); // Update the redemption amount if fees were charged (or accrued) to the redeemer uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = postFeesRedeemerSharesBalance; } else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) { sharesToRedeem_ = sharesToRedeem_.sub( preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance) ); } // Pay the protocol fee after running other fees, but before burning shares vaultProxyContract.payProtocolFee(); if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated); } // Destroy the shares after getting the shares supply sharesSupply_ = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, sharesToRedeem_); return (sharesToRedeem_, sharesSupply_); } // TRANSFER SHARES /// @notice Runs logic prior to transferring shares that are not freely transferable /// @param _sender The sender of the shares /// @param _recipient The recipient of the shares /// @param _amount The amount of shares function preTransferSharesHook( address _sender, address _recipient, uint256 _amount ) external override { address vaultProxyCopy = getVaultProxy(); require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable"); __assertSharesActionNotTimelocked(vaultProxyCopy, _sender); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PreTransferShares, abi.encode(_sender, _recipient, _amount) ); } /// @notice Runs logic prior to transferring shares that are freely transferable /// @param _sender The sender of the shares /// @dev No need to validate caller, as policies are not run function preTransferSharesHookFreelyTransferable(address _sender) external view override { __assertSharesActionNotTimelocked(getVaultProxy(), _sender); } ///////////////// // GAS RELAYER // ///////////////// /// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying function deployGasRelayPaymaster() external onlyOwnerNotRelayable { require( getGasRelayPaymaster() == address(0), "deployGasRelayPaymaster: Paymaster already deployed" ); bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy()); address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy( constructData ); __setGasRelayPaymaster(paymaster); __depositToGasRelayPaymaster(paymaster); } /// @notice Tops up the gas relay paymaster deposit function depositToGasRelayPaymaster() external onlyOwner { __depositToGasRelayPaymaster(getGasRelayPaymaster()); } /// @notice Pull WETH from vault to gas relay paymaster /// @param _amount Amount of the WETH to pull from the vault function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster { IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount); } /// @notice Sets the gasRelayPaymaster variable value /// @param _nextGasRelayPaymaster The next gasRelayPaymaster value function setGasRelayPaymaster(address _nextGasRelayPaymaster) external override onlyFundDeployer { __setGasRelayPaymaster(_nextGasRelayPaymaster); } /// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance /// and disabling gas relaying function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable { IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance(); IVault(vaultProxy).addTrackedAsset(getWethToken()); delete gasRelayPaymaster; emit GasRelayPaymasterSet(address(0)); } /// @dev Helper to deposit to the gas relay paymaster function __depositToGasRelayPaymaster(address _paymaster) private { IGasRelayPaymaster(_paymaster).deposit(); } /// @dev Helper to set the next `gasRelayPaymaster` variable function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private { gasRelayPaymaster = _nextGasRelayPaymaster; emit GasRelayPaymasterSet(_nextGasRelayPaymaster); } /////////////////// // STATE GETTERS // /////////////////// // LIB IMMUTABLES /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable /// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value function getExternalPositionManager() public view override returns (address externalPositionManager_) { return EXTERNAL_POSITION_MANAGER; } /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() public view override returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view override returns (address fundDeployer_) { return FUND_DEPLOYER; } /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() public view override returns (address integrationManager_) { return INTEGRATION_MANAGER; } /// @notice Gets the `MLN_TOKEN` variable /// @return mlnToken_ The `MLN_TOKEN` variable value function getMlnToken() public view returns (address mlnToken_) { return MLN_TOKEN; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() public view override returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PROTOCOL_FEE_RESERVE` variable /// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) { return PROTOCOL_FEE_RESERVE; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() public view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } // PROXY STORAGE /// @notice Checks if collected protocol fee shares are automatically bought back /// while buying or redeeming shares /// @return doesAutoBuyback_ True if shares are automatically bought back function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) { return autoProtocolFeeSharesBuyback; } /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() public view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the `gasRelayPaymaster` variable /// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) { return gasRelayPaymaster; } /// @notice Gets the timestamp of the last time shares were bought for a given account /// @param _who The account for which to get the timestamp /// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought function getLastSharesBoughtTimestampForAccount(address _who) public view returns (uint256 lastSharesBoughtTimestamp_) { return acctToLastSharesBoughtTimestamp[_who]; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() public view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/NonUpgradableProxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is NonUpgradableProxy { constructor(bytes memory _constructData, address _comptrollerLib) public NonUpgradableProxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../vault/IVault.sol"; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { function activate(bool) external; function calcGav() external returns (uint256); function calcGrossShareValue() external returns (uint256); function callOnExtension( address, uint256, bytes calldata ) external; function destructActivated(uint256, uint256) external; function destructUnactivated() external; function getDenominationAsset() external view returns (address); function getExternalPositionManager() external view returns (address); function getFeeManager() external view returns (address); function getFundDeployer() external view returns (address); function getGasRelayPaymaster() external view returns (address); function getIntegrationManager() external view returns (address); function getPolicyManager() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(IVault.VaultAction, bytes calldata) external; function preTransferSharesHook( address, address, uint256 ) external; function preTransferSharesHookFreelyTransferable(address) external view; function setGasRelayPaymaster(address) external; function setVaultProxy(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol"; import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol"; import "../../../../persistent/vault/interfaces/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault { enum VaultAction { None, // Shares management BurnShares, MintShares, TransferShares, // Asset management AddTrackedAsset, ApproveAssetSpender, RemoveTrackedAsset, WithdrawAssetTo, // External position management AddExternalPosition, CallOnExternalPosition, RemoveExternalPosition } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares} enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function canDisable() external pure returns (bool canDisable_); function identifier() external pure returns (string memory identifier_); function implementedHooks() external pure returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { // When updating PolicyHook, also update these functions in PolicyManager: // 1. __getAllPolicyHooks() // 2. __policyHookRestrictsCurrentInvestorActions() enum PolicyHook { PostBuyShares, PostCallOnIntegration, PreTransferShares, RedeemSharesForSpecificAssets, AddTrackedAssets, RemoveTrackedAssets, CreateExternalPosition, PostCallOnExternalPosition, RemoveExternalPosition, ReactivateExternalPosition } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds /// @dev Any arbitrary fee is allowed by default, so all participants must be aware of /// their fund's configuration, especially whether they use official policies only. /// Policies that restrict current investors can only be added upon fund setup, migration, or reconfiguration. /// Policies that restrict new investors or asset management actions can be added at any time. /// Policies themselves specify whether or not they are allowed to be updated or removed. contract PolicyManager is IPolicyManager, ExtensionBase, GasRelayRecipientMixin { using AddressArrayLib for address[]; event PolicyDisabledOnHookForFund( address indexed comptrollerProxy, address indexed policy, PolicyHook indexed hook ); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); uint256 private constant POLICY_HOOK_COUNT = 10; mapping(address => mapping(PolicyHook => address[])) private comptrollerProxyToHookToPolicies; modifier onlyFundOwner(address _comptrollerProxy) { require( __msgSender() == IVault(getVaultProxyForFund(_comptrollerProxy)).getOwner(), "Only the fund owner can call this function" ); _; } constructor(address _fundDeployer, address _gasRelayPaymasterFactory) public ExtensionBase(_fundDeployer) GasRelayRecipientMixin(_gasRelayPaymasterFactory) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev There will be no enabledPolicies if the caller is not a valid ComptrollerProxy function activateForFund(bool _isMigratedFund) external override { address comptrollerProxy = msg.sender; // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(comptrollerProxy); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(comptrollerProxy, enabledPolicies[i]); } } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable /// @dev If an arbitrary policy changes its `implementedHooks()` return values after it is /// already enabled on a fund, then this will not correctly disable the policy from any /// removed hook values. function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyFundOwner(_comptrollerProxy) { require(IPolicy(_policy).canDisable(), "disablePolicyForFund: _policy cannot be disabled"); PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks(); for (uint256 i; i < implementedHooks.length; i++) { bool disabled = comptrollerProxyToHookToPolicies[_comptrollerProxy][implementedHooks[i]] .removeStorageItem(_policy); if (disabled) { emit PolicyDisabledOnHookForFund(_comptrollerProxy, _policy, implementedHooks[i]); } } } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyFundOwner(_comptrollerProxy) { PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks(); for (uint256 i; i < implementedHooks.length; i++) { require( !__policyHookRestrictsCurrentInvestorActions(implementedHooks[i]), "enablePolicyForFund: _policy restricts actions of current investors" ); } __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData, implementedHooks); __activatePolicyForFund(_comptrollerProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _configData Encoded config data function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external override onlyFundDeployer { __setValidatedVaultProxy(_comptrollerProxy, _vaultProxy); // In case there are no policies yet if (_configData.length == 0) { return; } (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund( _comptrollerProxy, policies[i], settingsData[i], IPolicy(policies[i]).implementedHooks() ); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyFundOwner(_comptrollerProxy) { IPolicy(_policy).updateFundSettings(_comptrollerProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { // Return as quickly as possible if no policies to run address[] memory policies = getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook); if (policies.length == 0) { return; } // Limit calls to trusted components, in case policies update local storage upon runs require( msg.sender == _comptrollerProxy || msg.sender == IComptroller(_comptrollerProxy).getIntegrationManager() || msg.sender == IComptroller(_comptrollerProxy).getExternalPositionManager(), "validatePolicies: Caller not allowed" ); for (uint256 i; i < policies.length; i++) { require( IPolicy(policies[i]).validateRule(_comptrollerProxy, _hook, _validationData), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund(address _comptrollerProxy, address _policy) private { IPolicy(_policy).activateForFund(_comptrollerProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData, PolicyHook[] memory _hooks ) private { // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy for (uint256 i; i < _hooks.length; i++) { require( !policyIsEnabledOnHookForFund(_comptrollerProxy, _hooks[i], _policy), "__enablePolicyForFund: Policy is already enabled" ); comptrollerProxyToHookToPolicies[_comptrollerProxy][_hooks[i]].push(_policy); } emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to get all the hooks available to policies function __getAllPolicyHooks() private pure returns (PolicyHook[POLICY_HOOK_COUNT] memory hooks_) { return [ PolicyHook.PostBuyShares, PolicyHook.PostCallOnIntegration, PolicyHook.PreTransferShares, PolicyHook.RedeemSharesForSpecificAssets, PolicyHook.AddTrackedAssets, PolicyHook.RemoveTrackedAssets, PolicyHook.CreateExternalPosition, PolicyHook.PostCallOnExternalPosition, PolicyHook.RemoveExternalPosition, PolicyHook.ReactivateExternalPosition ]; } /// @dev Helper to check if a policy hook restricts the actions of current investors. /// These hooks should not allow policy additions post-deployment or post-migration. function __policyHookRestrictsCurrentInvestorActions(PolicyHook _hook) private pure returns (bool restrictsActions_) { return _hook == PolicyHook.PreTransferShares || _hook == PolicyHook.RedeemSharesForSpecificAssets; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled policies for the given fund /// @param _comptrollerProxy The ComptrollerProxy /// @return enabledPolicies_ The array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { PolicyHook[POLICY_HOOK_COUNT] memory hooks = __getAllPolicyHooks(); for (uint256 i; i < hooks.length; i++) { enabledPolicies_ = enabledPolicies_.mergeArray( getEnabledPoliciesOnHookForFund(_comptrollerProxy, hooks[i]) ); } return enabledPolicies_; } /// @notice Get a list of enabled policies that run on a given hook for the given fund /// @param _comptrollerProxy The ComptrollerProxy /// @param _hook The PolicyHook /// @return enabledPolicies_ The array of enabled policy addresses function getEnabledPoliciesOnHookForFund(address _comptrollerProxy, PolicyHook _hook) public view returns (address[] memory enabledPolicies_) { return comptrollerProxyToHookToPolicies[_comptrollerProxy][_hook]; } /// @notice Check whether a given policy runs on a given hook for a given fund /// @param _comptrollerProxy The ComptrollerProxy /// @param _hook The PolicyHook /// @param _policy The policy /// @return isEnabled_ True if the policy is enabled function policyIsEnabledOnHookForFund( address _comptrollerProxy, PolicyHook _hook, address _policy ) public view returns (bool isEnabled_) { return getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook).contains(_policy); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]e.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/FundDeployerOwnerMixin.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension, FundDeployerOwnerMixin { event ValidatedVaultProxySetForFund( address indexed comptrollerProxy, address indexed vaultProxy ); mapping(address => address) internal comptrollerProxyToVaultProxy; modifier onlyFundDeployer() { require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call"); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund( address, address, bytes calldata ) external virtual override { return; } /// @dev Helper to store the validated ComptrollerProxy-VaultProxy relation function __setValidatedVaultProxy(address _comptrollerProxy, address _vaultProxy) internal { comptrollerProxyToVaultProxy[_comptrollerProxy] = _vaultProxy; emit ValidatedVaultProxySetForFund(_comptrollerProxy, _vaultProxy); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../interfaces/IGsnRelayHub.sol"; import "../../interfaces/IGsnTypes.sol"; import "../../interfaces/IWETH.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/IVault.sol"; import "../../core/fund-deployer/FundDeployer.sol"; import "../../extensions/policy-manager/PolicyManager.sol"; import "./bases/GasRelayPaymasterLibBase1.sol"; import "./IGasRelayPaymaster.sol"; import "./IGasRelayPaymasterDepositor.sol"; /// @title GasRelayPaymasterLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library for the "paymaster" contract which refunds GSN relayers contract GasRelayPaymasterLib is IGasRelayPaymaster, GasRelayPaymasterLibBase1 { using SafeMath for uint256; // Immutable and constants // Sane defaults, subject to change after gas profiling uint256 private constant CALLDATA_SIZE_LIMIT = 10500; // Deposit in wei uint256 private constant DEPOSIT = 0.2 ether; // Sane defaults, subject to change after gas profiling uint256 private constant PRE_RELAYED_CALL_GAS_LIMIT = 100000; uint256 private constant POST_RELAYED_CALL_GAS_LIMIT = 110000; // FORWARDER_HUB_OVERHEAD = 50000; // PAYMASTER_ACCEPTANCE_BUDGET = FORWARDER_HUB_OVERHEAD + PRE_RELAYED_CALL_GAS_LIMIT uint256 private constant PAYMASTER_ACCEPTANCE_BUDGET = 150000; address private immutable RELAY_HUB; address private immutable TRUSTED_FORWARDER; address private immutable WETH_TOKEN; modifier onlyComptroller() { require( msg.sender == getParentComptroller(), "Can only be called by the parent comptroller" ); _; } modifier relayHubOnly() { require(msg.sender == getHubAddr(), "Can only be called by RelayHub"); _; } constructor( address _wethToken, address _relayHub, address _trustedForwarder ) public { RELAY_HUB = _relayHub; TRUSTED_FORWARDER = _trustedForwarder; WETH_TOKEN = _wethToken; } // INIT /// @notice Initializes a paymaster proxy /// @param _vault The VaultProxy associated with the paymaster proxy /// @dev Used to set the owning vault function init(address _vault) external { require(getParentVault() == address(0), "init: Paymaster already initialized"); parentVault = _vault; } // EXTERNAL FUNCTIONS /// @notice Pull deposit from the vault and reactivate relaying function deposit() external override onlyComptroller { __depositMax(); } /// @notice Checks whether the paymaster will pay for a given relayed tx /// @param _relayRequest The full relay request structure /// @return context_ The tx signer and the fn sig, encoded so that it can be passed to `postRelayCall` /// @return rejectOnRecipientRevert_ Always false function preRelayedCall( IGsnTypes.RelayRequest calldata _relayRequest, bytes calldata, bytes calldata, uint256 ) external override relayHubOnly returns (bytes memory context_, bool rejectOnRecipientRevert_) { address vaultProxy = getParentVault(); require( IVault(vaultProxy).canRelayCalls(_relayRequest.request.from), "preRelayedCall: Unauthorized caller" ); bytes4 selector = __parseTxDataFunctionSelector(_relayRequest.request.data); require( __isAllowedCall( vaultProxy, _relayRequest.request.to, selector, _relayRequest.request.data ), "preRelayedCall: Function call not permitted" ); return (abi.encode(_relayRequest.request.from, selector), false); } /// @notice Called by the relay hub after the relayed tx is executed, tops up deposit if flag passed through paymasterdata is true /// @param _context The context constructed by preRelayedCall (used to pass data from pre to post relayed call) /// @param _success Whether or not the relayed tx succeed /// @param _relayData The relay params of the request. can be used by relayHub.calculateCharge() function postRelayedCall( bytes calldata _context, bool _success, uint256, IGsnTypes.RelayData calldata _relayData ) external override relayHubOnly { bool shouldTopUpDeposit = abi.decode(_relayData.paymasterData, (bool)); if (shouldTopUpDeposit) { __depositMax(); } (address spender, bytes4 selector) = abi.decode(_context, (address, bytes4)); emit TransactionRelayed(spender, selector, _success); } /// @notice Send any deposited ETH back to the vault function withdrawBalance() external override { address vaultProxy = getParentVault(); require( msg.sender == IVault(vaultProxy).getOwner() || msg.sender == __getComptrollerForVault(vaultProxy), "withdrawBalance: Only owner or comptroller is authorized" ); IGsnRelayHub(getHubAddr()).withdraw(getRelayHubDeposit(), payable(address(this))); uint256 amount = address(this).balance; Address.sendValue(payable(vaultProxy), amount); emit Withdrawn(amount); } // PUBLIC FUNCTIONS /// @notice Gets the current ComptrollerProxy of the VaultProxy associated with this contract /// @return parentComptroller_ The ComptrollerProxy function getParentComptroller() public view returns (address parentComptroller_) { return __getComptrollerForVault(parentVault); } // PRIVATE FUNCTIONS /// @dev Helper to pull WETH from the associated vault to top up to the max ETH deposit in the relay hub function __depositMax() private { uint256 prevDeposit = getRelayHubDeposit(); if (prevDeposit < DEPOSIT) { uint256 amount = DEPOSIT.sub(prevDeposit); IGasRelayPaymasterDepositor(getParentComptroller()).pullWethForGasRelayer(amount); IWETH(getWethToken()).withdraw(amount); IGsnRelayHub(getHubAddr()).depositFor{value: amount}(address(this)); emit Deposited(amount); } } /// @dev Helper to get the ComptrollerProxy for a given VaultProxy function __getComptrollerForVault(address _vaultProxy) private view returns (address comptrollerProxy_) { return IVault(_vaultProxy).getAccessor(); } /// @dev Helper to check if a contract call is allowed to be relayed using this paymaster /// Allowed contracts are: /// - VaultProxy /// - ComptrollerProxy /// - PolicyManager /// - FundDeployer function __isAllowedCall( address _vaultProxy, address _contract, bytes4 _selector, bytes calldata _txData ) private view returns (bool allowed_) { if (_contract == _vaultProxy) { // All calls to the VaultProxy are allowed return true; } address parentComptroller = __getComptrollerForVault(_vaultProxy); if (_contract == parentComptroller) { if ( _selector == ComptrollerLib.callOnExtension.selector || _selector == ComptrollerLib.vaultCallOnContract.selector || _selector == ComptrollerLib.buyBackProtocolFeeShares.selector || _selector == ComptrollerLib.depositToGasRelayPaymaster.selector || _selector == ComptrollerLib.setAutoProtocolFeeSharesBuyback.selector ) { return true; } } else if (_contract == ComptrollerLib(parentComptroller).getPolicyManager()) { if ( _selector == PolicyManager.updatePolicySettingsForFund.selector || _selector == PolicyManager.enablePolicyForFund.selector || _selector == PolicyManager.disablePolicyForFund.selector ) { return __parseTxDataFirstParameterAsAddress(_txData) == getParentComptroller(); } } else if (_contract == ComptrollerLib(parentComptroller).getFundDeployer()) { if ( _selector == FundDeployer.createReconfigurationRequest.selector || _selector == FundDeployer.executeReconfiguration.selector || _selector == FundDeployer.cancelReconfiguration.selector ) { return __parseTxDataFirstParameterAsAddress(_txData) == getParentVault(); } } return false; } /// @notice Parses the first parameter of tx data as an address /// @param _txData The tx data to retrieve the address from /// @return retrievedAddress_ The extracted address function __parseTxDataFirstParameterAsAddress(bytes calldata _txData) private pure returns (address retrievedAddress_) { require( _txData.length >= 36, "__parseTxDataFirstParameterAsAddress: _txData is not a valid length" ); return abi.decode(_txData[4:36], (address)); } /// @notice Parses the function selector from tx data /// @param _txData The tx data /// @return functionSelector_ The extracted function selector function __parseTxDataFunctionSelector(bytes calldata _txData) private pure returns (bytes4 functionSelector_) { /// convert bytes[:4] to bytes4 require( _txData.length >= 4, "__parseTxDataFunctionSelector: _txData is not a valid length" ); functionSelector_ = _txData[0] | (bytes4(_txData[1]) >> 8) | (bytes4(_txData[2]) >> 16) | (bytes4(_txData[3]) >> 24); return functionSelector_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets gas limits used by the relay hub for the pre and post relay calls /// @return limits_ `GasAndDataLimits(PAYMASTER_ACCEPTANCE_BUDGET, PRE_RELAYED_CALL_GAS_LIMIT, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT)` function getGasAndDataLimits() external view override returns (IGsnPaymaster.GasAndDataLimits memory limits_) { return IGsnPaymaster.GasAndDataLimits( PAYMASTER_ACCEPTANCE_BUDGET, PRE_RELAYED_CALL_GAS_LIMIT, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT ); } /// @notice Gets the `RELAY_HUB` variable value /// @return relayHub_ The `RELAY_HUB` value function getHubAddr() public view override returns (address relayHub_) { return RELAY_HUB; } /// @notice Gets the `parentVault` variable value /// @return parentVault_ The `parentVault` value function getParentVault() public view returns (address parentVault_) { return parentVault; } /// @notice Look up amount of ETH deposited on the relay hub /// @return depositBalance_ amount of ETH deposited on the relay hub function getRelayHubDeposit() public view override returns (uint256 depositBalance_) { return IGsnRelayHub(getHubAddr()).balanceOf(address(this)); } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the `TRUSTED_FORWARDER` variable value /// @return trustedForwarder_ The forwarder contract which is trusted to validated the relayed tx signature function trustedForwarder() external view override returns (address trustedForwarder_) { return TRUSTED_FORWARDER; } /// @notice Gets the string representation of the contract version (fulfills interface) /// @return versionString_ The version string function versionPaymaster() external view override returns (string memory versionString_) { return "2.2.3+opengsn.enzymefund.ipaymaster"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "./IGasRelayPaymaster.sol"; pragma solidity 0.6.12; /// @title GasRelayRecipientMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin that enables receiving GSN-relayed calls /// @dev IMPORTANT: Do not use storage var in this contract, /// unless it is no longer inherited by the VaultLib abstract contract GasRelayRecipientMixin { address internal immutable GAS_RELAY_PAYMASTER_FACTORY; constructor(address _gasRelayPaymasterFactory) internal { GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory; } /// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed function __msgSender() internal view returns (address payable canonicalSender_) { if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) { assembly { canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20))) } return canonicalSender_; } return msg.sender; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable /// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value function getGasRelayPaymasterFactory() public view returns (address gasRelayPaymasterFactory_) { return GAS_RELAY_PAYMASTER_FACTORY; } /// @notice Gets the trusted forwarder for GSN relaying /// @return trustedForwarder_ The trusted forwarder function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) { return IGasRelayPaymaster( IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib() ) .trustedForwarder(); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../interfaces/IGsnPaymaster.sol"; /// @title IGasRelayPaymaster Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymaster is IGsnPaymaster { function deposit() external; function withdrawBalance() external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGasRelayPaymasterDepositor Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymasterDepositor { function pullWethForGasRelayer(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title GasRelayPaymasterLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and events /// for a GasRelayPaymasterLib /// @dev DO NOT EDIT CONTRACT ONCE DEPLOYED. If new events or storage are necessary, /// they should be added to a numbered GasRelayPaymasterLibBaseXXX that inherits the previous base. /// e.g., `GasRelayPaymasterLibBase2 is GasRelayPaymasterLibBase1` abstract contract GasRelayPaymasterLibBase1 { event Deposited(uint256 amount); event TransactionRelayed(address indexed authorizer, bytes4 invokedSelector, bool successful); event Withdrawn(uint256 amount); // Pseudo-constants address internal parentVault; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IProtocolFeeTracker Interface /// @author Enzyme Council <[email protected]> interface IProtocolFeeTracker { function initializeForVault(address) external; function payFee() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256); function isSupportedAsset(address) external view returns (bool); function isSupportedDerivativeAsset(address) external view returns (bool); function isSupportedPrimitiveAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGsnForwarder interface /// @author Enzyme Council <[email protected]> interface IGsnForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnPaymaster interface /// @author Enzyme Council <[email protected]> interface IGsnPaymaster { struct GasAndDataLimits { uint256 acceptanceBudget; uint256 preRelayedCallGasLimit; uint256 postRelayedCallGasLimit; uint256 calldataSizeLimit; } function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits); function getHubAddr() external view returns (address); function getRelayHubDeposit() external view returns (uint256); function preRelayedCall( IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external returns (bytes memory context, bool rejectOnRecipientRevert); function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, IGsnTypes.RelayData calldata relayData ) external; function trustedForwarder() external view returns (address); function versionPaymaster() external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnRelayHub Interface /// @author Enzyme Council <[email protected]> interface IGsnRelayHub { function balanceOf(address target) external view returns (uint256); function calculateCharge(uint256 gasUsed, IGsnTypes.RelayData calldata relayData) external view returns (uint256); function depositFor(address target) external payable; function relayCall( uint256 maxAcceptanceBudget, IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 externalGasLimit ) external returns (bool paymasterAccepted, bytes memory returnValue); function withdraw(uint256 amount, address payable dest) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnForwarder.sol"; /// @title IGsnTypes Interface /// @author Enzyme Council <[email protected]> interface IGsnTypes { struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; address forwarder; bytes paymasterData; uint256 clientId; } struct RelayRequest { IGsnForwarder.ForwardRequest request; RelayData relayData; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title NonUpgradableProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for use with non-upgradable libs /// @dev The recommended constructor-fallback pattern of a proxy in EIP-1822, updated for solc 0.6.12, /// and using an immutable lib value to save on gas (since not upgradable). /// The EIP-1967 storage slot for the lib is still assigned, /// for ease of referring to UIs that understand the pattern, i.e., Etherscan. abstract contract NonUpgradableProxy { address private immutable CONTRACT_LOGIC; constructor(bytes memory _constructData, address _contractLogic) public { CONTRACT_LOGIC = _contractLogic; assembly { // EIP-1967 slot: `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)` sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } // solhint-disable-next-line no-complex-fallback fallback() external payable { address contractLogic = CONTRACT_LOGIC; assembly { calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[email protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
Registers allowed callers of ComptrollerProxy.buySharesOnBehalf() _callers The allowed callers Validate that each registered caller only forwards requests to buy shares that originate from the same _buyer passed into buySharesOnBehalf(). This is critical to the integrity of VaultProxy.freelyTransferableShares.
function registerBuySharesOnBehalfCallers(address[] calldata _callers) external onlyOwner { for (uint256 i; i < _callers.length; i++) { require( !isAllowedBuySharesOnBehalfCaller(_callers[i]), "registerBuySharesOnBehalfCallers: Caller already registered" ); acctToIsAllowedBuySharesOnBehalfCaller[_callers[i]] = true; emit BuySharesOnBehalfCallerRegistered(_callers[i]); } }
355,355
pragma solidity ^0.5.0; library Pairing { uint256 constant PRIME_Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; struct G1Point { uint256 X; uint256 Y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint256[2] X; uint256[2] Y; } /* * @return The negation of p, i.e. p.plus(p.negate()) should be zero. */ function negate(G1Point memory p) internal pure returns (G1Point memory) { // The prime q in the base field F_q for G1 if (p.X == 0 && p.Y == 0) { return G1Point(0, 0); } else { return G1Point(p.X, PRIME_Q - (p.Y % PRIME_Q)); } } /* * @return The sum of two points of G1 */ function plus( G1Point memory p1, G1Point memory p2 ) internal view returns (G1Point memory r) { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success,"pairing-add-failed"); } /* * @return The product of a point on G1 and a scalar, i.e. * p == p.scalar_mul(1) and p.plus(p) == p.scalar_mul(2) for all * points p. */ function scalar_mul(G1Point memory p, uint256 s) internal view returns (G1Point memory r) { uint256[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require (success,"pairing-mul-failed"); } /* @return The result of computing the pairing check * e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 * For example, * pairing([P1(), P1().negate()], [P2(), P2()]) should return true. */ function pairing( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2, G1Point memory d1, G2Point memory d2 ) internal view returns (bool) { G1Point[4] memory p1 = [a1, b1, c1, d1]; G2Point[4] memory p2 = [a2, b2, c2, d2]; uint256 inputSize = 24; uint256[] memory input = new uint256[](inputSize); for (uint256 i = 0; i < 4; i++) { uint256 j = i * 6; input[j + 0] = p1[i].X; input[j + 1] = p1[i].Y; input[j + 2] = p2[i].X[0]; input[j + 3] = p2[i].X[1]; input[j + 4] = p2[i].Y[0]; input[j + 5] = p2[i].Y[1]; } uint256[1] memory out; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success,"pairing-opcode-failed"); return out[0] != 0; } }
return The result of computing the pairing check e(p1[0], p2[0]) .... e(p1[n], p2[n]) == 1 For example, pairing([P1(), P1().negate()], [P2(), P2()]) should return true./ solium-disable-next-line security/no-inline-assembly Use "invalid" to make gas estimation work
function pairing( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2, G1Point memory d1, G2Point memory d2 ) internal view returns (bool) { G1Point[4] memory p1 = [a1, b1, c1, d1]; G2Point[4] memory p2 = [a2, b2, c2, d2]; uint256 inputSize = 24; uint256[] memory input = new uint256[](inputSize); for (uint256 i = 0; i < 4; i++) { uint256 j = i * 6; input[j + 0] = p1[i].X; input[j + 1] = p1[i].Y; input[j + 2] = p2[i].X[0]; input[j + 3] = p2[i].X[1]; input[j + 4] = p2[i].Y[0]; input[j + 5] = p2[i].Y[1]; } uint256[1] memory out; bool success; assembly { success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success,"pairing-opcode-failed"); return out[0] != 0; }
12,633,128
./full_match/1/0x2e3e05ac7537aa55EAb9625631360D55ae8edCb2/sources/contracts/ClickBotGame.sol
Private function to swap tokens for ETH./ Generate the uniswap pair path of token -> weth make the swap
function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(token); path[1] = uniswap.WETH(); token.approve(address(uniswap), tokenAmount); uniswap.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); }
4,922,499
pragma solidity ^0.4.23; import "../math/SafeMath.sol"; import "../tokens/ERC20.sol"; import "../tokens/ERC721.sol"; import "./TokenTransferProxy.sol"; import "./NFTokenTransferProxy.sol"; import "../tokens/ERC165implementation.sol"; /* * @dev based on: https://github.com/0xProject/contracts/blob/master/contracts/Exchange.sol */ contract Swapper is ERC165implementation { using SafeMath for uint256; /* * @dev Enum of possible errors. */ enum Errors { SWAP_ALREADY_PERFORMED, // Transfer has already beed performed. SWAP_CANCELLED, // Transfer was cancelled. INSUFFICIENT_BALANCE_OR_ALLOWANCE, // Insufficient balance or allowance for XCT transfer. NFTOKEN_NOT_ALLOWED // Proxy does not have the Permission to transfer all the NFTokens. } /* * @dev contract addresses */ address TOKEN_CONTRACT; address TOKEN_TRANSFER_PROXY_CONTRACT; address NFTOKEN_TRANSFER_PROXY_CONTRACT; /* * @dev Changes to state require at least 5000 gas. */ uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; /* * @dev Mapping of all canceled transfers. */ mapping(bytes32 => bool) public swapCancelled; /* * @dev Mapping of all performed transfers. */ mapping(bytes32 => bool) public swapPerformed; /* * @dev This event emmits when NFToken changes ownership. */ event PerformSwap(address indexed _from, address _to, bytes32 _swapClaim); /* * @dev This event emmits when NFToken transfer order is canceled. */ event CancelSwap(address indexed _from, address _to, bytes32 _swapClaim); /* * @dev Structure of data needed for a swap. */ struct SwapData{ address from; address to; address[] nfTokensFrom; uint256[] idsFrom; address[] nfTokensTo; uint256[] idsTo; address[] feeAddresses; uint256[] feeAmounts; uint256 seed; uint256 expirationTimestamp; bytes32 claim; } /* * @dev Sets XCT token address, Token proxy address and NFToken Proxy address. * @param _nfTokenToken Address pointing to XCT Token contract. * @param _tokenTransferProxy Address pointing to TokenTransferProxy contract. * @param _nfTokenTransferProxy Address pointing to none-fungible token transfer proxy contract. */ constructor(address _xctToken, address _tokenTransferProxy, address _nfTokenTransferProxy) public { TOKEN_CONTRACT = _xctToken; TOKEN_TRANSFER_PROXY_CONTRACT = _tokenTransferProxy; NFTOKEN_TRANSFER_PROXY_CONTRACT = _nfTokenTransferProxy; supportedInterfaces[0xe20524dd] = true; // Swapper } /* * @dev Get address of token used in exchange. */ function getTokenAddress() external view returns (address) { return TOKEN_CONTRACT; } /* * @dev Get address of token transfer proxy used in exchange. */ function getTokenTransferProxyAddress() external view returns (address) { return TOKEN_TRANSFER_PROXY_CONTRACT; } /* * @dev Get address of none-fundgible token transfer proxy used in exchange. */ function getNFTokenTransferProxyAddress() external view returns (address) { return NFTOKEN_TRANSFER_PROXY_CONTRACT; } /* * @dev Performs the NFToken swap.. * * @param _addresses Array of all addresses that go as following: 0 = Address of NFToken swap * maker, 1 = Address of NFToken taker, then an array of NFToken contract addresses for every * NFToken id of the maker, after an array of NFToken contract addresses for every NFToken id of * the taker, and array of addresses to whom the taker has to pay fees. * @param _uints Array of all uints that go as following: 0 = _seed Timestamp that represents the * salt, 1 = Timestamp of when the transfer claim expires, 2 = numbers of tokens to transfer from * maker to taker, 3 = numbers of tokens to transfer from taker to maker, then an Array of ids * that maker is sending, array of ids that taker is sending, array of fee amounts that have to be * paid. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @param _throwIfNotSwappable Test the swap before performing. * @return Success of the swap. */ function performSwap(address[] _addresses, uint256[] _uints, uint8 _v, bytes32 _r, bytes32 _s, bool _throwIfNotSwappable) public { require(_addresses.length.add(2) == _uints.length); require(_uints[2] > 0); require(_uints[3] > 0); SwapData memory swapData = SwapData({ from: _addresses[0], to: _addresses[1], nfTokensFrom: _getAddressSubArrayTo(_addresses, 2, _uints[2].add(2)), idsFrom: _getUintSubArrayTo(_uints, 4, _uints[2].add(4)), nfTokensTo: _getAddressSubArrayTo(_addresses, _uints[2].add(2), (_uints[2].add(2)).add(_uints[3])), idsTo: _getUintSubArrayTo(_uints, _uints[2].add(4), (_uints[2].add(4)).add(_uints[3])), feeAddresses: _getAddressSubArrayTo(_addresses, (_uints[2].add(2)).add(_uints[3]), _addresses.length), feeAmounts: _getUintSubArrayTo(_uints,(_uints[2].add(4)).add(_uints[3]), _uints.length), seed: _uints[0], expirationTimestamp: _uints[1], claim: getSwapDataClaim( _addresses, _uints ) }); require(swapData.to == msg.sender); require(swapData.from != swapData.to); require(swapData.expirationTimestamp >= now); require(isValidSignature( swapData.from, swapData.claim, _v, _r, _s )); require(!swapPerformed[swapData.claim], "Swap already performed."); require(!swapCancelled[swapData.claim], "Swap canceled."); if (_throwIfNotSwappable) { require(_canPayFee(swapData.to, swapData.feeAmounts), "Insufficient balance or allowance."); require(_areTransfersAllowed(swapData), "NFToken transfer not approved"); } swapPerformed[swapData.claim] = true; _makeNFTokenTransfers(swapData); _payfeeAmounts(swapData.feeAddresses, swapData.feeAmounts, swapData.to); emit PerformSwap( swapData.from, swapData.to, swapData.claim ); } /* * @dev Cancels NFToken transfer. * * @param _addresses Array of all addresses that go as following: 0 = Address of NFToken swap * maker, 1 = Address of NFToken taker, then an array of NFToken contract addresses for every * NFToken id of the maker, after an array of NFToken contract addresses for every NFToken id of * the taker, and array of addresses to whom the taker has to pay fees. * @param _uints Array of all uints that go as following: 0 = _seed Timestamp that represents the * salt, 1 = Timestamp of when the transfer claim expires, 2 = numbers of tokens to transfer from * maker to taker, 3 = numbers of tokens to transfer from taker to maker, then an Array of ids * that maker is sending, array of ids that taker is sending, array of fee amounts that have to be * paid. */ function cancelSwap(address[] _addresses, uint256[] _uints) public { require(msg.sender == _addresses[0]); bytes32 claim = getSwapDataClaim( _addresses, _uints ); require(!swapPerformed[claim]); emit CancelSwap( _addresses[0], _addresses[1], claim ); } /* * @dev Calculates keccak-256 hlaim of mint data from parameters. * @param _addresses Array of all addresses that go as following: 0 = Address of NFToken swap * maker, 1 = Address of NFToken taker, then an array of NFToken contract addresses for every * NFToken id of the maker, after an array of NFToken contract addresses for every NFToken id of * the taker, and array of addresses to whom the taker has to pay fees. * @param _uints Array of all uints that go as following: 0 = _seed Timestamp that represents the * salt, 1 = Timestamp of when the transfer claim expires, 2 = numbers of tokens to transfer from * maker to taker, 3 = numbers of tokens to transfer from taker to maker, then an Array of ids * that maker is sending, array of ids that taker is sending, array of fee amounts that have to be * paid. * @returns keccak-hash of transfer data. */ function getSwapDataClaim(address[] _addresses, uint256[] _uints) public constant returns (bytes32) { return keccak256( address(this), _addresses[0], _addresses[1], _getAddressSubArrayTo(_addresses, 2, _uints[2].add(2)), _getUintSubArrayTo(_uints, 4, _uints[2].add(4)), _getAddressSubArrayTo(_addresses, _uints[2].add(2), (_uints[2].add(2)).add(_uints[3])), _getUintSubArrayTo(_uints, _uints[2].add(4), (_uints[2].add(4)).add(_uints[3])), _getAddressSubArrayTo(_addresses, (_uints[2].add(2)).add(_uints[3]), _addresses.length), _getUintSubArrayTo(_uints,(_uints[2].add(4)).add(_uints[3]), _uints.length), _uints[0], _uints[1] ); } /* * @dev Verifies if NFToken signature is valid. * @param _signer address of signer. * @param _claim Signed Keccak-256 hash. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return Validity of signature. */ function isValidSignature(address _signer, bytes32 _claim, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (bool) { return _signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", _claim), _v, _r, _s ); } /* * @dev Check is payer can pay the feeAmounts. * @param _to Address of the payer. * @param_ feeAmounts All the feeAmounts to be payed. * @return Confirmation if feeAmounts can be payed. */ function _canPayFee(address _to, uint256[] _feeAmounts) internal returns (bool) { uint256 feeAmountsum = 0; for(uint256 i; i < _feeAmounts.length; i++) { feeAmountsum = feeAmountsum.add(_feeAmounts[i]); } if(_getBalance(TOKEN_CONTRACT, _to) < feeAmountsum || _getAllowance(TOKEN_CONTRACT, _to) < feeAmountsum ) { return false; } return true; } /* * @dev check if we can transfer all the NFTokens. * @param _swapData Data of all the NFToken transfers. */ function _areTransfersAllowed(SwapData _swapData) internal constant returns (bool) { for(uint i = 0; i < _swapData.nfTokensFrom.length; i++) { if(!_isAllowed( _swapData.from, _swapData.nfTokensFrom[i], _swapData.idsFrom[i] )) { return false; } } for(i = 0; i < _swapData.nfTokensTo.length; i++) { if(!_isAllowed( _swapData.to, _swapData.nfTokensTo[i], _swapData.idsTo[i] )) { return false; } } return true; } /* * @dev Transfers XCT tokens via TokenTransferProxy using transferFrom function. * @param _token Address of token to transferFrom. * @param _from Address transfering token. * @param _to Address receiving token. * @param _value Amount of token to transfer. * @return Success of token transfer. */ function _transferViaTokenTransferProxy(address _token, address _from, address _to, uint _value) internal returns (bool) { return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom( _token, _from, _to, _value ); } /* * @dev Transfers NFToken via NFTokenProxy using transfer function. * @param _nfToken Address of NFToken to transfer. * @param _from Address sending NFToken. * @param _to Address receiving NFToken. * @param _id Id of transfering NFToken. */ function _transferViaNFTokenTransferProxy(address _nfToken, address _from, address _to, uint256 _id) internal { NFTokenTransferProxy(NFTOKEN_TRANSFER_PROXY_CONTRACT) .transferFrom(_nfToken, _from, _to, _id); } /* * @dev Get token balance of an address. * The called token contract may attempt to change state, but will not be able to due to an added * gas limit. Gas is limited to prevent reentrancy. * @param _token Address of token. * @param _owner Address of owner. * @return Token balance of owner. */ function _getBalance(address _token, address _owner) internal returns (uint) { return ERC20(_token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(_owner); } /* * @dev Get allowance of token given to TokenTransferProxy by an address. * The called token contract may attempt to change state, but will not be able to due to an added * gas limit. Gas is limited to prevent reentrancy. * @param _token Address of token. * @param _owner Address of owner. * @return Allowance of token given to TokenTransferProxy by owner. */ function _getAllowance(address _token, address _owner) internal returns (uint) { return ERC20(_token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)( _owner, TOKEN_TRANSFER_PROXY_CONTRACT ); } /* * @dev Checks if we can transfer NFToken. * @param _from Address of NFToken sender. * @param _nfToken Address of NFToken contract. * @param _nfTokenId Id of NFToken (hashed certificate data that is transformed into uint256). + @return Permission if we can transfer NFToken. */ function _isAllowed(address _from, address _nfToken, uint256 _nfTokenId) internal constant returns (bool) { if(ERC721(_nfToken).getApproved(_nfTokenId) == NFTOKEN_TRANSFER_PROXY_CONTRACT) { return true; } if(ERC721(_nfToken).isApprovedForAll(_from, NFTOKEN_TRANSFER_PROXY_CONTRACT)) { return true; } return false; } /* * @dev Creates a sub array from address array. * @param _array Array from which we will make a sub array. * @param _index Index from which our sub array will be made. */ function _getAddressSubArrayTo(address[] _array, uint256 _index, uint256 _to) internal pure returns (address[]) { require(_to >= _index); require(_array.length >= _to); address[] memory subArray = new address[](_to.sub(_index)); uint256 j = 0; for(uint256 i = _index; i < _to; i++) { subArray[j] = _array[i]; j++; } return subArray; } /* * @dev Creates a sub array from uint256 array. * @param _array Array from which we will make a sub array. * @param _index Index from which our sub array will be made. */ function _getUintSubArrayTo(uint256[] _array, uint256 _index, uint256 _to) internal pure returns (uint256[]) { require(_to >= _index); require(_array.length >= _to); uint256[] memory subArray = new uint256[](_to.sub(_index)); uint256 j = 0; for(uint256 i = _index; i < _to; i++) { subArray[j] = _array[i]; j++; } return subArray; } /** * @dev Helper function that pays all the feeAmounts. * @param _feeAddresses Addresses of all parties that need to get feeAmounts paid. * @param _feeAmounts Fee amounts of all the _feeAddresses (length of both have to be the same). * @param _to Address of the fee payer. * @return Success of payments. */ function _payfeeAmounts(address[] _feeAddresses, uint256[] _feeAmounts, address _to) internal { for(uint256 i; i < _feeAddresses.length; i++) { if(_feeAddresses[i] != address(0) && _feeAmounts[i] > 0) { require(_transferViaTokenTransferProxy( TOKEN_CONTRACT, _to, _feeAddresses[i], _feeAmounts[i] )); } } } /* * @dev Helper function that performes all the transfers. * @param _swapData Structure of all the neecesary data. */ function _makeNFTokenTransfers(SwapData _swapData) internal { for(uint i = 0; i < _swapData.nfTokensFrom.length; i++) { _transferViaNFTokenTransferProxy( _swapData.nfTokensFrom[i], _swapData.from, _swapData.to, _swapData.idsFrom[i] ); } for(i = 0; i < _swapData.nfTokensTo.length; i++) { _transferViaNFTokenTransferProxy( _swapData.nfTokensTo[i], _swapData.to, _swapData.from, _swapData.idsTo[i] ); } } }
Get address of none-fundgible token transfer proxy used in exchange./
function getNFTokenTransferProxyAddress() external view returns (address) { return NFTOKEN_TRANSFER_PROXY_CONTRACT; }
6,479,377
pragma solidity 0.4.24; /** * Safe unsigned safe math. * * https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli * * Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol * * Maintained here until merged to mainline zeppelin-solidity. * */ library SafeMathLibExt { function times(uint a, uint b) public pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function divides(uint a, uint b) public pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function minus(uint a, uint b) public pure returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) public pure returns (uint) { uint 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; } } /* * Haltable * * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * * * Originally envisioned in FirstBlood ICO contract. */ contract Haltable is Ownable { bool public halted; modifier stopInEmergency { if (halted) revert(); _; } modifier stopNonOwnersInEmergency { if (halted && msg.sender != owner) revert(); _; } modifier onlyInEmergency { if (!halted) revert(); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } /** * Interface for defining crowdsale pricing. */ contract PricingStrategy { address public tier; /** Interface declaration. */ function isPricingStrategy() public pure returns (bool) { return true; } /** Self check if all references are correctly set. * * Checks that pricing strategy matches crowdsale parameters. */ function isSane() public pure returns (bool) { return true; } /** * @dev Pricing tells if this is a presale purchase or not. @return False by default, true if a presale purchaser */ function isPresalePurchase() public pure returns (bool) { return false; } /* How many weis one token costs */ function updateRate(uint oneTokenInCents) public; /** * When somebody tries to buy tokens for X eth, calculate how many tokens they get. * * * @param value - What is the value of the transaction send in as wei * @param tokensSold - how much tokens have been sold this far * @param decimals - how many decimal units the token has * @return Amount of tokens the investor receives */ function calculatePrice(uint value, uint tokensSold, uint decimals) public view returns (uint tokenAmount); function oneTokenInWei(uint tokensSold, uint decimals) public view returns (uint); } /** * Finalize agent defines what happens at the end of succeseful crowdsale. * * - Allocate tokens for founders, bounties and community * - Make tokens transferable * - etc. */ contract FinalizeAgent { bool public reservedTokensAreDistributed = false; function isFinalizeAgent() public pure returns(bool) { return true; } /** Return true if we can run finalizeCrowdsale() properly. * * This is a safety check function that doesn't allow crowdsale to begin * unless the finalizer has been set up properly. */ function isSane() public view returns (bool); function distributeReservedTokens(uint reservedTokensDistributionBatch) public; /** Called once by crowdsale finalize() if the sale was success. */ function finalizeCrowdsale() public; /** * Allow to (re)set Token. */ function setCrowdsaleTokenExtv1(address _token) public; } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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); } /** * A token that defines fractional units as decimals. */ contract FractionalERC20Ext is ERC20 { uint public decimals; uint public minCap; } contract Allocatable is Ownable { /** List of agents that are allowed to allocate new tokens */ mapping (address => bool) public allocateAgents; event AllocateAgentChanged(address addr, bool state ); /** * Owner can allow a crowdsale contract to allocate new tokens. */ function setAllocateAgent(address addr, bool state) public onlyOwner { allocateAgents[addr] = state; emit AllocateAgentChanged(addr, state); } modifier onlyAllocateAgent() { //Only crowdsale contracts are allowed to allocate new tokens require(allocateAgents[msg.sender]); _; } } /** * Contract to enforce Token Vesting */ contract TokenVesting is Allocatable { using SafeMathLibExt for uint; address public crowdSaleTokenAddress; /** keep track of total tokens yet to be released, * this should be less than or equal to UTIX tokens held by this contract. */ uint256 public totalUnreleasedTokens; // default vesting parameters uint256 private startAt = 0; uint256 private cliff = 1; uint256 private duration = 4; uint256 private step = 300; //15778463; //2592000; bool private changeFreezed = false; struct VestingSchedule { uint256 startAt; uint256 cliff; uint256 duration; uint256 step; uint256 amount; uint256 amountReleased; bool changeFreezed; } mapping (address => VestingSchedule) public vestingMap; event VestedTokensReleased(address _adr, uint256 _amount); constructor(address _tokenAddress) public { crowdSaleTokenAddress = _tokenAddress; } /** Modifier to check if changes to vesting is freezed */ modifier changesToVestingFreezed(address _adr) { require(vestingMap[_adr].changeFreezed); _; } /** Modifier to check if changes to vesting is not freezed yet */ modifier changesToVestingNotFreezed(address adr) { require(!vestingMap[adr].changeFreezed); // if vesting not set then also changeFreezed will be false _; } /** Function to set default vesting schedule parameters. */ function setDefaultVestingParameters( uint256 _startAt, uint256 _cliff, uint256 _duration, uint256 _step, bool _changeFreezed) public onlyAllocateAgent { // data validation require(_step != 0); require(_duration != 0); require(_cliff <= _duration); startAt = _startAt; cliff = _cliff; duration = _duration; step = _step; changeFreezed = _changeFreezed; } /** Function to set vesting with default schedule. */ function setVestingWithDefaultSchedule(address _adr, uint256 _amount) public changesToVestingNotFreezed(_adr) onlyAllocateAgent { setVesting(_adr, startAt, cliff, duration, step, _amount, changeFreezed); } /** Function to set/update vesting schedule. PS - Amount cannot be changed once set */ function setVesting( address _adr, uint256 _startAt, uint256 _cliff, uint256 _duration, uint256 _step, uint256 _amount, bool _changeFreezed) public changesToVestingNotFreezed(_adr) onlyAllocateAgent { VestingSchedule storage vestingSchedule = vestingMap[_adr]; // data validation require(_step != 0); require(_amount != 0 || vestingSchedule.amount > 0); require(_duration != 0); require(_cliff <= _duration); //if startAt is zero, set current time as start time. if (_startAt == 0) _startAt = block.timestamp; vestingSchedule.startAt = _startAt; vestingSchedule.cliff = _cliff; vestingSchedule.duration = _duration; vestingSchedule.step = _step; // special processing for first time vesting setting if (vestingSchedule.amount == 0) { // check if enough tokens are held by this contract ERC20 token = ERC20(crowdSaleTokenAddress); require(token.balanceOf(this) >= totalUnreleasedTokens.plus(_amount)); totalUnreleasedTokens = totalUnreleasedTokens.plus(_amount); vestingSchedule.amount = _amount; } vestingSchedule.amountReleased = 0; vestingSchedule.changeFreezed = _changeFreezed; } function isVestingSet(address adr) public view returns (bool isSet) { return vestingMap[adr].amount != 0; } function freezeChangesToVesting(address _adr) public changesToVestingNotFreezed(_adr) onlyAllocateAgent { require(isVestingSet(_adr)); // first check if vesting is set vestingMap[_adr].changeFreezed = true; } /** Release tokens as per vesting schedule, called by contributor */ function releaseMyVestedTokens() public changesToVestingFreezed(msg.sender) { releaseVestedTokens(msg.sender); } /** Release tokens as per vesting schedule, called by anyone */ function releaseVestedTokens(address _adr) public changesToVestingFreezed(_adr) { VestingSchedule storage vestingSchedule = vestingMap[_adr]; // check if all tokens are not vested require(vestingSchedule.amount.minus(vestingSchedule.amountReleased) > 0); // calculate total vested tokens till now uint256 totalTime = block.timestamp - vestingSchedule.startAt; uint256 totalSteps = totalTime / vestingSchedule.step; // check if cliff is passed require(vestingSchedule.cliff <= totalSteps); uint256 tokensPerStep = vestingSchedule.amount / vestingSchedule.duration; // check if amount is divisble by duration if (tokensPerStep * vestingSchedule.duration != vestingSchedule.amount) tokensPerStep++; uint256 totalReleasableAmount = tokensPerStep.times(totalSteps); // handle the case if user has not claimed even after vesting period is over or amount was not divisible if (totalReleasableAmount > vestingSchedule.amount) totalReleasableAmount = vestingSchedule.amount; uint256 amountToRelease = totalReleasableAmount.minus(vestingSchedule.amountReleased); vestingSchedule.amountReleased = vestingSchedule.amountReleased.plus(amountToRelease); // transfer vested tokens ERC20 token = ERC20(crowdSaleTokenAddress); token.transfer(_adr, amountToRelease); // decrement overall unreleased token count totalUnreleasedTokens = totalUnreleasedTokens.minus(amountToRelease); emit VestedTokensReleased(_adr, amountToRelease); } /** * Allow to (re)set Token. */ function setCrowdsaleTokenExtv1(address _token) public onlyAllocateAgent { crowdSaleTokenAddress = _token; } } /** * Abstract base contract for token sales. * * Handle * - start and end dates * - accepting investments * - minimum funding goal and refund * - various statistics during the crowdfund * - different pricing strategies * - different investment policies (require server side customer id, allow only whitelisted addresses) * */ contract CrowdsaleExt is Allocatable, Haltable { /* Max investment count when we are still allowed to change the multisig address */ uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; using SafeMathLibExt for uint; /* The token we are selling */ FractionalERC20Ext public token; /* How we are going to price our offering */ PricingStrategy public pricingStrategy; /* Post-success callback */ FinalizeAgent public finalizeAgent; TokenVesting public tokenVesting; /* name of the crowdsale tier */ string public name; /* tokens will be transfered from this address */ address public multisigWallet; /* if the funding goal is not reached, investors may withdraw their funds */ uint public minimumFundingGoal; /* the UNIX timestamp start date of the crowdsale */ uint public startsAt; /* the UNIX timestamp end date of the crowdsale */ uint public endsAt; /* the number of tokens already sold through this contract*/ uint public tokensSold = 0; /* How many wei of funding we have raised */ uint public weiRaised = 0; /* How many distinct addresses have invested */ uint public investorCount = 0; /* Has this crowdsale been finalized */ bool public finalized; bool public isWhiteListed; /* Token Vesting Contract */ address public tokenVestingAddress; address[] public joinedCrowdsales; uint8 public joinedCrowdsalesLen = 0; uint8 public joinedCrowdsalesLenMax = 50; struct JoinedCrowdsaleStatus { bool isJoined; uint8 position; } mapping (address => JoinedCrowdsaleStatus) public joinedCrowdsaleState; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) public investedAmountOf; /** How much tokens this crowdsale has credited for each investor address */ mapping (address => uint256) public tokenAmountOf; struct WhiteListData { bool status; uint minCap; uint maxCap; } //is crowdsale updatable bool public isUpdatable; /** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */ mapping (address => WhiteListData) public earlyParticipantWhitelist; /** List of whitelisted addresses */ address[] public whitelistedParticipants; /** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */ uint public ownerTestValue; /** State machine * * - Preparing: All contract initialization calls and variables have not been set yet * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Success: Minimum funding goal reached * - Failure: Minimum funding goal not reached before ending time * - Finalized: The finalized has been called and succesfully executed */ enum State { Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized } // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId); // Address early participation whitelist status changed event Whitelisted(address addr, bool status, uint minCap, uint maxCap); event WhitelistItemChanged(address addr, bool status, uint minCap, uint maxCap); // Crowdsale start time has been changed event StartsAtChanged(uint newStartsAt); // Crowdsale end time has been changed event EndsAtChanged(uint newEndsAt); constructor(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed, address _tokenVestingAddress) public { owner = msg.sender; name = _name; tokenVestingAddress = _tokenVestingAddress; token = FractionalERC20Ext(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if (multisigWallet == 0) { revert(); } if (_start == 0) { revert(); } startsAt = _start; if (_end == 0) { revert(); } endsAt = _end; // Don't mess the dates if (startsAt >= endsAt) { revert(); } // Minimum funding goal can be zero minimumFundingGoal = _minimumFundingGoal; isUpdatable = _isUpdatable; isWhiteListed = _isWhiteListed; } /** * Don't expect to just send in money and get tokens. */ function() external payable { buy(); } /** * The basic entry point to participate the crowdsale process. * * Pay for funding, get invested tokens back in the sender address. */ function buy() public payable { invest(msg.sender); } /** * Allow anonymous contributions to this crowdsale. */ function invest(address addr) public payable { investInternal(addr, 0); } /** * Make an investment. * * Crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * @param customerId (optional) UUID v4 to track the successful payments on the server side * */ function investInternal(address receiver, uint128 customerId) private stopInEmergency { // Determine if it's a good time to accept investment from this participant if (getState() == State.PreFunding) { // Are we whitelisted for early deposit revert(); } else if (getState() == State.Funding) { // Retail participants can only come in when the crowdsale is running // pass if (isWhiteListed) { if (!earlyParticipantWhitelist[receiver].status) { revert(); } } } else { // Unwanted state revert(); } uint weiAmount = msg.value; // Account presale sales separately, so that they do not count against pricing tranches uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, tokensSold, token.decimals()); if (tokenAmount == 0) { // Dust transaction revert(); } if (isWhiteListed) { if (weiAmount < earlyParticipantWhitelist[receiver].minCap && tokenAmountOf[receiver] == 0) { // weiAmount < minCap for investor revert(); } // Check that we did not bust the investor's cap if (isBreakingInvestorCap(receiver, weiAmount)) { revert(); } updateInheritedEarlyParticipantWhitelist(receiver, weiAmount); } else { if (weiAmount < token.minCap() && tokenAmountOf[receiver] == 0) { revert(); } } if (investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); // Update totals weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); // Check that we did not bust the cap if (isBreakingCap(tokensSold)) { revert(); } assignTokens(receiver, tokenAmount); // Pocket the money if (!multisigWallet.send(weiAmount)) revert(); // Tell us invest was success emit Invested(receiver, weiAmount, tokenAmount, customerId); } /** * allocate tokens for the early investors. * * Preallocated tokens have been sold before the actual crowdsale opens. * This function mints the tokens and moves the crowdsale needle. * * Investor count is not handled; it is assumed this goes for multiple investors * and the token distribution happens outside the smart contract flow. * * No money is exchanged, as the crowdsale team already have received the payment. * * param weiPrice Price of a single full token in wei * */ function allocate(address receiver, uint256 tokenAmount, uint128 customerId, uint256 lockedTokenAmount) public onlyAllocateAgent { // cannot lock more than total tokens require(lockedTokenAmount <= tokenAmount); uint weiPrice = pricingStrategy.oneTokenInWei(tokensSold, token.decimals()); // This can be also 0, we give out tokens for free uint256 weiAmount = (weiPrice * tokenAmount)/10**uint256(token.decimals()); weiRaised = weiRaised.plus(weiAmount); tokensSold = tokensSold.plus(tokenAmount); investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount); // assign locked token to Vesting contract if (lockedTokenAmount > 0) { tokenVesting = TokenVesting(tokenVestingAddress); // to prevent minting of tokens which will be useless as vesting amount cannot be updated require(!tokenVesting.isVestingSet(receiver)); assignTokens(tokenVestingAddress, lockedTokenAmount); // set vesting with default schedule tokenVesting.setVestingWithDefaultSchedule(receiver, lockedTokenAmount); } // assign remaining tokens to contributor if (tokenAmount - lockedTokenAmount > 0) { assignTokens(receiver, tokenAmount - lockedTokenAmount); } // Tell us invest was success emit Invested(receiver, weiAmount, tokenAmount, customerId); } // // Modifiers // /** Modified allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { if (getState() != state) revert(); _; } function distributeReservedTokens(uint reservedTokensDistributionBatch) public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if (finalized) { revert(); } // Finalizing is optional. We only call it if we are given a finalizing agent. if (address(finalizeAgent) != address(0)) { finalizeAgent.distributeReservedTokens(reservedTokensDistributionBatch); } } function areReservedTokensDistributed() public view returns (bool) { return finalizeAgent.reservedTokensAreDistributed(); } function canDistributeReservedTokens() public view returns(bool) { CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if ((lastTierCntrct.getState() == State.Success) && !lastTierCntrct.halted() && !lastTierCntrct.finalized() && !lastTierCntrct.areReservedTokensDistributed()) return true; return false; } /** * Finalize a succcesful crowdsale. * * The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if (finalized) { revert(); } // Finalizing is optional. We only call it if we are given a finalizing agent. if (address(finalizeAgent) != address(0)) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } /** * Allow to (re)set finalize agent. * * Design choice: no state restrictions on setting this, so that we can fix fat finger mistakes. */ function setFinalizeAgent(FinalizeAgent addr) public onlyOwner { assert(address(addr) != address(0)); assert(address(finalizeAgent) == address(0)); finalizeAgent = addr; // Don't allow setting bad agent if (!finalizeAgent.isFinalizeAgent()) { revert(); } } /** * Allow addresses to do early participation. */ function setEarlyParticipantWhitelist(address addr, bool status, uint minCap, uint maxCap) public onlyOwner { if (!isWhiteListed) revert(); assert(addr != address(0)); assert(maxCap > 0); assert(minCap <= maxCap); assert(now <= endsAt); if (!isAddressWhitelisted(addr)) { whitelistedParticipants.push(addr); emit Whitelisted(addr, status, minCap, maxCap); } else { emit WhitelistItemChanged(addr, status, minCap, maxCap); } earlyParticipantWhitelist[addr] = WhiteListData({status:status, minCap:minCap, maxCap:maxCap}); } function setEarlyParticipantWhitelistMultiple(address[] addrs, bool[] statuses, uint[] minCaps, uint[] maxCaps) public onlyOwner { if (!isWhiteListed) revert(); assert(now <= endsAt); assert(addrs.length == statuses.length); assert(statuses.length == minCaps.length); assert(minCaps.length == maxCaps.length); for (uint iterator = 0; iterator < addrs.length; iterator++) { setEarlyParticipantWhitelist(addrs[iterator], statuses[iterator], minCaps[iterator], maxCaps[iterator]); } } function updateEarlyParticipantWhitelist(address addr, uint weiAmount) public { if (!isWhiteListed) revert(); assert(addr != address(0)); assert(now <= endsAt); assert(isTierJoined(msg.sender)); if (weiAmount < earlyParticipantWhitelist[addr].minCap && tokenAmountOf[addr] == 0) revert(); //if (addr != msg.sender && contractAddr != msg.sender) throw; uint newMaxCap = earlyParticipantWhitelist[addr].maxCap; newMaxCap = newMaxCap.minus(weiAmount); earlyParticipantWhitelist[addr] = WhiteListData({status:earlyParticipantWhitelist[addr].status, minCap:0, maxCap:newMaxCap}); } function updateInheritedEarlyParticipantWhitelist(address reciever, uint weiAmount) private { if (!isWhiteListed) revert(); if (weiAmount < earlyParticipantWhitelist[reciever].minCap && tokenAmountOf[reciever] == 0) revert(); uint8 tierPosition = getTierPosition(this); for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); crowdsale.updateEarlyParticipantWhitelist(reciever, weiAmount); } } function isAddressWhitelisted(address addr) public view returns(bool) { for (uint i = 0; i < whitelistedParticipants.length; i++) { if (whitelistedParticipants[i] == addr) { return true; break; } } return false; } function whitelistedParticipantsLength() public view returns (uint) { return whitelistedParticipants.length; } function isTierJoined(address addr) public view returns(bool) { return joinedCrowdsaleState[addr].isJoined; } function getTierPosition(address addr) public view returns(uint8) { return joinedCrowdsaleState[addr].position; } function getLastTier() public view returns(address) { if (joinedCrowdsalesLen > 0) return joinedCrowdsales[joinedCrowdsalesLen - 1]; else return address(0); } function setJoinedCrowdsales(address addr) private onlyOwner { assert(addr != address(0)); assert(joinedCrowdsalesLen <= joinedCrowdsalesLenMax); assert(!isTierJoined(addr)); joinedCrowdsales.push(addr); joinedCrowdsaleState[addr] = JoinedCrowdsaleStatus({ isJoined: true, position: joinedCrowdsalesLen }); joinedCrowdsalesLen++; } function updateJoinedCrowdsalesMultiple(address[] addrs) public onlyOwner { assert(addrs.length > 0); assert(joinedCrowdsalesLen == 0); assert(addrs.length <= joinedCrowdsalesLenMax); for (uint8 iter = 0; iter < addrs.length; iter++) { setJoinedCrowdsales(addrs[iter]); } } function setStartsAt(uint time) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= time); // Don't change past assert(time <= endsAt); assert(now <= startsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if (lastTierCntrct.finalized()) revert(); uint8 tierPosition = getTierPosition(this); //start time should be greater then end time of previous tiers for (uint8 j = 0; j < tierPosition; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); assert(time >= crowdsale.endsAt()); } startsAt = time; emit StartsAtChanged(startsAt); } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setEndsAt(uint time) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= time);// Don't change past assert(startsAt <= time); assert(now <= endsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); if (lastTierCntrct.finalized()) revert(); uint8 tierPosition = getTierPosition(this); for (uint8 j = tierPosition + 1; j < joinedCrowdsalesLen; j++) { CrowdsaleExt crowdsale = CrowdsaleExt(joinedCrowdsales[j]); assert(time <= crowdsale.startsAt()); } endsAt = time; emit EndsAtChanged(endsAt); } /** * Allow to (re)set pricing strategy. * * Design choice: no state restrictions on the set, so that we can fix fat finger mistakes. */ function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner { assert(address(_pricingStrategy) != address(0)); assert(address(pricingStrategy) == address(0)); pricingStrategy = _pricingStrategy; // Don't allow setting bad agent if (!pricingStrategy.isPricingStrategy()) { revert(); } } /** * Allow to (re)set Token. * @param _token upgraded token address */ function setCrowdsaleTokenExtv1(address _token) public onlyOwner { assert(_token != address(0)); token = FractionalERC20Ext(_token); if (address(finalizeAgent) != address(0)) { finalizeAgent.setCrowdsaleTokenExtv1(_token); } } /** * Allow to change the team multisig address in the case of emergency. * * This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun * (we have done only few test transactions). After the crowdsale is going * then multisig address stays locked for the safety reasons. */ function setMultisig(address addr) public onlyOwner { // Change if (investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { revert(); } multisigWallet = addr; } /** * @return true if the crowdsale has raised enough money to be a successful. */ function isMinimumGoalReached() public view returns (bool reached) { return weiRaised >= minimumFundingGoal; } /** * Check if the contract relationship looks good. */ function isFinalizerSane() public view returns (bool sane) { return finalizeAgent.isSane(); } /** * Check if the contract relationship looks good. */ function isPricingSane() public view returns (bool sane) { return pricingStrategy.isSane(); } /** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, * so there is no chance of the variable being stale. */ function getState() public view returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane()) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else return State.Failure; } /** Interface marker. */ function isCrowdsale() public pure returns (bool) { return true; } // // Abstract functions // /** * Check if the current invested breaks our cap rules. * * * The child contract must define their own cap setting rules. * We allow a lot of flexibility through different capping strategies (ETH, token count) * Called from invest(). * * @param tokensSoldTotal What would be our total sold tokens count after this transaction * * @return true if taking this investment would break our cap rules */ function isBreakingCap(uint tokensSoldTotal) public view returns (bool limitBroken); function isBreakingInvestorCap(address receiver, uint tokenAmount) public view returns (bool limitBroken); /** * Check if the current crowdsale is full and we can no longer sell any tokens. */ function isCrowdsaleFull() public view returns (bool); /** * Create new tokens or transfer issued tokens to the investor depending on the cap model. */ function assignTokens(address receiver, uint tokenAmount) private; } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMathLibExt for uint; /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) public balances; /* approve() allowances */ mapping (address => mapping (address => uint)) public allowed; /* Interface declaration */ function isToken() public pure returns (bool weAre) { return true; } function transfer(address _to, uint _value) public returns (bool success) { balances[msg.sender] = balances[msg.sender].minus(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { uint _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].plus(_value); balances[_from] = balances[_from].minus(_value); allowed[_from][msg.sender] = _allowance.minus(_value); emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } /** * A token that can increase its supply by another contract. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, contracts whitelisted by owner, can mint new tokens. * */ contract MintableTokenExt is StandardToken, Ownable { using SafeMathLibExt for uint; bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); /** inPercentageUnit is percents of tokens multiplied to 10 up to percents decimals. * For example, for reserved tokens in percents 2.54% * inPercentageUnit = 254 * inPercentageDecimals = 2 */ struct ReservedTokensData { uint inTokens; uint inPercentageUnit; uint inPercentageDecimals; bool isReserved; bool isDistributed; bool isVested; } mapping (address => ReservedTokensData) public reservedTokensList; address[] public reservedTokensDestinations; uint public reservedTokensDestinationsLen = 0; bool private reservedTokensDestinationsAreSet = false; modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens if (!mintAgents[msg.sender]) { revert(); } _; } /** Make sure we are not done yet. */ modifier canMint() { if (mintingFinished) revert(); _; } function finalizeReservedAddress(address addr) public onlyMintAgent canMint { ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; reservedTokensData.isDistributed = true; } function isAddressReserved(address addr) public view returns (bool isReserved) { return reservedTokensList[addr].isReserved; } function areTokensDistributedForAddress(address addr) public view returns (bool isDistributed) { return reservedTokensList[addr].isDistributed; } function getReservedTokens(address addr) public view returns (uint inTokens) { return reservedTokensList[addr].inTokens; } function getReservedPercentageUnit(address addr) public view returns (uint inPercentageUnit) { return reservedTokensList[addr].inPercentageUnit; } function getReservedPercentageDecimals(address addr) public view returns (uint inPercentageDecimals) { return reservedTokensList[addr].inPercentageDecimals; } function getReservedIsVested(address addr) public view returns (bool isVested) { return reservedTokensList[addr].isVested; } function setReservedTokensListMultiple( address[] addrs, uint[] inTokens, uint[] inPercentageUnit, uint[] inPercentageDecimals, bool[] isVested ) public canMint onlyOwner { assert(!reservedTokensDestinationsAreSet); assert(addrs.length == inTokens.length); assert(inTokens.length == inPercentageUnit.length); assert(inPercentageUnit.length == inPercentageDecimals.length); for (uint iterator = 0; iterator < addrs.length; iterator++) { if (addrs[iterator] != address(0)) { setReservedTokensList( addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator], isVested[iterator] ); } } reservedTokensDestinationsAreSet = true; } /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) public onlyMintAgent canMint { totalSupply = totalSupply.plus(amount); balances[receiver] = balances[receiver].plus(amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event emit Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) public onlyOwner canMint { mintAgents[addr] = state; emit MintingAgentChanged(addr, state); } function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals,bool isVested) private canMint onlyOwner { assert(addr != address(0)); if (!isAddressReserved(addr)) { reservedTokensDestinations.push(addr); reservedTokensDestinationsLen++; } reservedTokensList[addr] = ReservedTokensData({ inTokens: inTokens, inPercentageUnit: inPercentageUnit, inPercentageDecimals: inPercentageDecimals, isReserved: true, isDistributed: false, isVested:isVested }); } } /** * ICO crowdsale contract that is capped by amout of tokens. * * - Tokens are dynamically created during the crowdsale * * */ contract MintedTokenCappedCrowdsaleExt is CrowdsaleExt { /* Maximum amount of tokens this crowdsale can sell. */ uint public maximumSellableTokens; constructor( string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _maximumSellableTokens, bool _isUpdatable, bool _isWhiteListed, address _tokenVestingAddress ) public CrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _isUpdatable, _isWhiteListed, _tokenVestingAddress) { maximumSellableTokens = _maximumSellableTokens; } // Crowdsale maximumSellableTokens has been changed event MaximumSellableTokensChanged(uint newMaximumSellableTokens); /** * Called from invest() to confirm if the curret investment does not break our cap rule. */ function isBreakingCap(uint tokensSoldTotal) public view returns (bool limitBroken) { return tokensSoldTotal > maximumSellableTokens; } function isBreakingInvestorCap(address addr, uint weiAmount) public view returns (bool limitBroken) { assert(isWhiteListed); uint maxCap = earlyParticipantWhitelist[addr].maxCap; return (investedAmountOf[addr].plus(weiAmount)) > maxCap; } function isCrowdsaleFull() public view returns (bool) { return tokensSold >= maximumSellableTokens; } function setMaximumSellableTokens(uint tokens) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= startsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); assert(!lastTierCntrct.finalized()); maximumSellableTokens = tokens; emit MaximumSellableTokensChanged(maximumSellableTokens); } function updateRate(uint oneTokenInCents) public onlyOwner { assert(!finalized); assert(isUpdatable); assert(now <= startsAt); CrowdsaleExt lastTierCntrct = CrowdsaleExt(getLastTier()); assert(!lastTierCntrct.finalized()); pricingStrategy.updateRate(oneTokenInCents); } /** * Dynamically create tokens and assign them to the investor. */ function assignTokens(address receiver, uint tokenAmount) private { MintableTokenExt mintableToken = MintableTokenExt(token); mintableToken.mint(receiver, tokenAmount); } } /** * ICO crowdsale contract that is capped by amout of tokens. * * - Tokens are dynamically created during the crowdsale * * */ contract MintedTokenCappedCrowdsaleExtv1 is MintedTokenCappedCrowdsaleExt { address[] public investedAmountOfAddresses; MintedTokenCappedCrowdsaleExt public mintedTokenCappedCrowdsaleExt; constructor( string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _maximumSellableTokens, bool _isUpdatable, bool _isWhiteListed, address _tokenVestingAddress, MintedTokenCappedCrowdsaleExt _oldMintedTokenCappedCrowdsaleExtAddress ) public MintedTokenCappedCrowdsaleExt(_name, _token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal, _maximumSellableTokens, _isUpdatable, _isWhiteListed, _tokenVestingAddress) { mintedTokenCappedCrowdsaleExt = _oldMintedTokenCappedCrowdsaleExtAddress; tokensSold = mintedTokenCappedCrowdsaleExt.tokensSold(); weiRaised = mintedTokenCappedCrowdsaleExt.weiRaised(); investorCount = mintedTokenCappedCrowdsaleExt.investorCount(); for (uint i = 0; i < mintedTokenCappedCrowdsaleExt.whitelistedParticipantsLength(); i++) { address whitelistAddress = mintedTokenCappedCrowdsaleExt.whitelistedParticipants(i); //whitelistedParticipants.push(whitelistAddress); uint256 tokenAmount = mintedTokenCappedCrowdsaleExt.tokenAmountOf(whitelistAddress); if (tokenAmount != 0){ tokenAmountOf[whitelistAddress] = tokenAmount; } uint256 investedAmount = mintedTokenCappedCrowdsaleExt.investedAmountOf(whitelistAddress); if (investedAmount != 0){ investedAmountOf[whitelistAddress] = investedAmount; } //setEarlyParticipantWhitelist(whitelistAddress, true, 1000000000000000000, 1000000000000000000000); } } }
Dynamically create tokens and assign them to the investor./
function assignTokens(address receiver, uint tokenAmount) private { MintableTokenExt mintableToken = MintableTokenExt(token); mintableToken.mint(receiver, tokenAmount); }
10,039,000
./full_match/5/0x3Fa112591F89E6af32A9A35D1D178Eaa89cf9947/sources/contracts/RoboNounsVRGDA.sol
Set the auction target price. Only callable by the owner.
function setTargetPrice(int256 _targetPrice) external onlyOwner { targetPrice = _targetPrice; emit AuctionTargetPriceUpdated(_targetPrice); }
1,868,888
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; // Sample contracts showing upgradeability with multiple inheritance. // Child contract inherits from Father and Mother contracts, and Father extends from Gramps. // // Human // / \ // | Gramps // | | // Mother Father // | | // -- Child -- /** * Sample base intializable contract that is a human */ contract SampleHuman is Initializable { bool public isHuman; function initialize() public initializer { __SampleHuman_init(); } // solhint-disable-next-line func-name-mixedcase function __SampleHuman_init() internal onlyInitializing { __SampleHuman_init_unchained(); } // solhint-disable-next-line func-name-mixedcase function __SampleHuman_init_unchained() internal onlyInitializing { isHuman = true; } } /** * Sample base intializable contract that defines a field mother */ contract SampleMother is Initializable, SampleHuman { uint256 public mother; function initialize(uint256 value) public virtual initializer { __SampleMother_init(value); } // solhint-disable-next-line func-name-mixedcase function __SampleMother_init(uint256 value) internal onlyInitializing { __SampleHuman_init(); __SampleMother_init_unchained(value); } // solhint-disable-next-line func-name-mixedcase function __SampleMother_init_unchained(uint256 value) internal onlyInitializing { mother = value; } } /** * Sample base intializable contract that defines a field gramps */ contract SampleGramps is Initializable, SampleHuman { string public gramps; function initialize(string memory value) public virtual initializer { __SampleGramps_init(value); } // solhint-disable-next-line func-name-mixedcase function __SampleGramps_init(string memory value) internal onlyInitializing { __SampleHuman_init(); __SampleGramps_init_unchained(value); } // solhint-disable-next-line func-name-mixedcase function __SampleGramps_init_unchained(string memory value) internal onlyInitializing { gramps = value; } } /** * Sample base intializable contract that defines a field father and extends from gramps */ contract SampleFather is Initializable, SampleGramps { uint256 public father; function initialize(string memory _gramps, uint256 _father) public initializer { __SampleFather_init(_gramps, _father); } // solhint-disable-next-line func-name-mixedcase function __SampleFather_init(string memory _gramps, uint256 _father) internal onlyInitializing { __SampleGramps_init(_gramps); __SampleFather_init_unchained(_father); } // solhint-disable-next-line func-name-mixedcase function __SampleFather_init_unchained(uint256 _father) internal onlyInitializing { father = _father; } } /** * Child extends from mother, father (gramps) */ contract SampleChild is Initializable, SampleMother, SampleFather { uint256 public child; function initialize( uint256 _mother, string memory _gramps, uint256 _father, uint256 _child ) public initializer { __SampleChild_init(_mother, _gramps, _father, _child); } // solhint-disable-next-line func-name-mixedcase function __SampleChild_init( uint256 _mother, string memory _gramps, uint256 _father, uint256 _child ) internal onlyInitializing { __SampleMother_init(_mother); __SampleFather_init(_gramps, _father); __SampleChild_init_unchained(_child); } // solhint-disable-next-line func-name-mixedcase function __SampleChild_init_unchained(uint256 _child) internal onlyInitializing { child = _child; } }
solhint-disable-next-line func-name-mixedcase
function __SampleHuman_init_unchained() internal onlyInitializing { isHuman = true; }
14,039,158
./full_match/44787/0xb4C5D876231C1Da7dc8B606b87C80a81A322b3D7/sources/project_/contracts/UnergyLogicFunding.sol
Pausable method
function pauseContract() public whenNotPaused onlyOwner { _pause(); }
13,257,162
./full_match/5/0x35a9ba1d7203DFfc83A03f98888233ba78c0493E/sources/contracts/Common.sol
function to transfer wager to game contract, without charging for VRF tokenAddress tokenAddress the wager is made on wager wager amount/
function _transferWagerPvPNoVRF( address tokenAddress, uint256 wager ) internal { if (!Bankroll.getIsValidWager(address(this), tokenAddress)) { revert NotApprovedBankroll(); } if (tokenAddress == address(0)) { if (!(msg.value == wager)) { revert InvalidValue(wager, msg.value); } IERC20(tokenAddress).safeTransferFrom( msg.sender, address(this), wager ); } }
1,875,942
pragma solidity 0.8.4; contract Foo { // Simple map mapping(uint => uint) a; /// #if_succeeds forall(uint k in a) a[k] > 1; function setA(uint key, uint val) public { a[key] = val; } /// #if_succeeds forall(uint k in a) a[k] > 1; function decA(uint key) public { a[key]--; } // Map with complex key mapping (string => int16) public c; string sS; /// #if_succeeds forall (string memory s in c) c[s] > -1; function setC(string memory s, int16 v) public { c[s] = v; } // Nested map mapping (string => mapping(uint8 => int8)) d; /// #if_succeeds forall (string memory s in d) forall (uint8 k in d[s]) d[s][k] > 0; function setD(string memory s, uint8 k, int8 v) public { d[s][k] = v; } // Map to array forall mapping (uint => uint[]) e; /// #if_succeeds forall (uint k in e) e[k].length > 0; function setE(uint k, uint[] memory v) public { e[k] = v; } // Array of maps, array forall only mapping (uint => uint)[] f; function pushF() public { f.push(); } /// #if_succeeds forall (uint i in f) f[i][0] > 0; function setF(uint i, uint j, uint v) public { f[i][j] = v; } // Array of maps, map forall only mapping (uint => uint)[] g; function pushG() public { g.push(); } /// #if_succeeds forall (uint k in g[i]) g[i][k] > 0; function setG(uint i, uint j, uint v) public { g[i][j] = v; } // Nested map first map only mapping (string => mapping(uint8 => int8)) h; /// #if_succeeds forall (string memory s in h) h[s][0] > 0; function setH(string memory s, uint8 k, int8 v) public { h[s][k] = v; } // Nested map last map only mapping (string => mapping(uint8 => int8)) i; /// #if_succeeds forall (uint8 x in i[s]) i[s][x] > 0; function setI(string memory s, uint8 k, int8 v) public { i[s][k] = v; } struct SA { mapping(string=>uint) m; uint cnt; } struct SB { SA[] sas; } SB j; function addSA() public { j.sas.push(); } /// #if_succeeds forall (string memory s in j.sas[saI].m) j.sas[saI].m[s] > 0; function setJ(uint saI, string memory x, uint v) public { j.sas[saI].m[x] = v; } /// #if_succeeds forall(uint i in j.sas) forall (string memory s in j.sas[i].m) j.sas[i].m[s] > 0; function setJ2(uint saI, string memory x, uint v) public { j.sas[saI].m[x] = v; } mapping (uint => uint) k; function setK(uint i, uint v) public { k[i] = v; } /// #if_succeeds forall(uint i in old(k)) old(k[i] > 0); function setK1(uint i, uint v) public { k[i] = v; } function dummy() private { /// Make sure direct references to renamed state var are updated correctly c; } }
if_succeeds forall (uint i in f) f[i][0] > 0;
function setF(uint i, uint j, uint v) public { f[i][j] = v; }
14,064,136
/* * CHEEMS INU Supply: 1 000 000 000 000 Max Wallet: 10 000 000 000 at launch then 20 000 000 000 Max TX: 2 500 000 000 at launch then 10 000 000 000 Tax: 8% Buy 10% Sell SPLIT: 20% LP 50% BUYBACKS 30% DEVELOPMENT/MARKETING DO NOT BUY UNTIL CONTRACT ADDRESS IS POSTED IN TELEGRAM https://t.me/cheemstokenbsc * */ pragma solidity =0.8.9; // SPDX-License-Identifier: UNLICENSED interface IBEP20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } 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; } 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 IuniswapV2Router01 { 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 factory() external pure returns (address); function WETH() external pure returns (address); 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; } /** * @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 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() external 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) external onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @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); } } } } /** * @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] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { 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)); } } //Cheems Inu Eth Contract ///////////// contract CheemsInu is IBEP20, Ownable { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; event ContractChanged(uint256 indexed value); event ContractChangedBool(bool indexed value); event ContractChangedAddress(address indexed value); event antiBotBan(address indexed value); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _buyLock; mapping ( address => bool ) public blackList; EnumerableSet.AddressSet private _excluded; //Token Info string private constant _name = 'CHEEMSINU'; string private constant _symbol = 'CINU'; uint8 private constant _decimals = 9; uint256 public constant InitialSupply= 4138058057 * 10**_decimals; //Amount to Swap variable (0.2%) uint256 currentAmountToSwap = 8276116 * 10**_decimals; //Divider for the MaxBalance based on circulating Supply (0.25%) uint16 public constant BalanceLimitDivider=400; //Divider for sellLimit based on circulating Supply (0.25%) uint16 public constant SellLimitDivider=400; //Buyers get locked for MaxBuyLockTime (put in seconds, works better especially if changing later) so they can't buy repeatedly uint16 public constant MaxBuyLockTime= 9 seconds; //The time Liquidity gets locked at start and prolonged once it gets released uint256 private constant DefaultLiquidityLockTime= 1800; //DevWallets address public TeamWallet=payable(0x78eEa15417FeADEF60414F9FDf7886E72e29FA68); address public BuyBackWallet=payable(0x7bc10AF41bD6CA5ba88097d35d0Eb85350E49Ba7); //Uniswap router (Main & Testnet) address private uniswapV2Router=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //variables that track balanceLimit and sellLimit, //can be updated based on circulating supply and Sell- and BalanceLimitDividers uint256 private _circulatingSupply =InitialSupply; uint256 public balanceLimit = _circulatingSupply; uint256 public sellLimit = _circulatingSupply; uint256 private antiWhale = 8276116 * 10**_decimals; // (0.2%) //Used for anti-bot autoblacklist uint256 private tradingEnabledAt; //DO NOT CHANGE, THIS IS FOR HOLDING A TIMESTAMP uint256 private autoBanTime = 90; // Set to the amount of time in seconds after enable trading you want addresses to be auto blacklisted if they buy/sell/transfer in this time. uint256 private enableAutoBlacklist = 1; //Leave 1 if using, set to 0 if not using. //Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer uint8 private _buyTax; uint8 private _sellTax; uint8 private _transferTax; uint8 private _burnTax; uint8 private _liquidityTax; uint8 private _marketingTax; address private _uniswapV2PairAddress; IuniswapV2Router02 private _uniswapV2Router; //Constructor/////////// constructor () { //contract creator gets 90% of the token to create LP-Pair uint256 deployerBalance=_circulatingSupply; _balances[msg.sender] = deployerBalance; emit Transfer(address(0), msg.sender, deployerBalance); // Uniswap Router _uniswapV2Router = IuniswapV2Router02(uniswapV2Router); //Creates a Uniswap Pair _uniswapV2PairAddress = IuniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); //Sets Buy/Sell limits balanceLimit=InitialSupply/BalanceLimitDivider; sellLimit=InitialSupply/SellLimitDivider; //Sets buyLockTime buyLockTime=0; //Set Starting Taxes _buyTax=8; _sellTax=10; _transferTax=10; _burnTax=0; _liquidityTax=20; _marketingTax=80; //Team wallets and deployer are excluded from Taxes _excluded.add(TeamWallet); _excluded.add(BuyBackWallet); _excluded.add(msg.sender); } //Transfer functionality/// //transfer function, every transfer runs through this function function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); //Manually Excluded adresses are transfering tax and lock free bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); //Transactions from and to the contract are always tax and lock free bool isContractTransfer=(sender==address(this) || recipient==address(this)); //transfers between UniswapRouter and UniswapPair are tax and lock free address uniswapV2Router=address(_uniswapV2Router); bool isLiquidityTransfer = ((sender == _uniswapV2PairAddress && recipient == uniswapV2Router) || (recipient == _uniswapV2PairAddress && sender == uniswapV2Router)); //differentiate between buy/sell/transfer to apply different taxes/restrictions bool isBuy=sender==_uniswapV2PairAddress|| sender == uniswapV2Router; bool isSell=recipient==_uniswapV2PairAddress|| recipient == uniswapV2Router; //Pick transfer if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ //once trading is enabled, it can't be turned off again require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } //applies taxes, checks for limits, locks generates autoLP function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ //Sells can't exceed the sell limit require(amount<=sellLimit,"Dump protection"); require(blackList[sender] == false, "Address blacklisted!"); if (block.timestamp <= tradingEnabledAt + autoBanTime && enableAutoBlacklist == 1) { blackList[sender] = true; emit antiBotBan(sender); } tax=_sellTax; } else if(isBuy){ //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); require(amount <= antiWhale,"Tx amount exceeding max buy amount"); require(blackList[recipient] == false, "Address blacklisted!"); if (block.timestamp <= tradingEnabledAt + autoBanTime && enableAutoBlacklist == 1) { blackList[recipient] = true; emit antiBotBan(recipient); } tax=_buyTax; } else {//Transfer //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(blackList[sender] == false, "Sender address blacklisted!"); require(blackList[recipient] == false, "Recipient address blacklisted!"); require(recipientBalance+amount<=balanceLimit,"whale protection"); if (block.timestamp <= tradingEnabledAt + autoBanTime && enableAutoBlacklist == 1) { blackList[sender] = true; emit antiBotBan(sender); } tax=_transferTax; } //Swapping AutoLP and MarketingETH is only possible if sender is not uniswapV2 pair, //if its not manually disabled, if its not already swapping and if its a Sell to avoid // people from causing a large price impact from repeatedly transfering when theres a large backlog of Tokens if((sender!=_uniswapV2PairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier)&&isSell) _swapContractToken(); //Calculates the exact token amount for each tax uint256 tokensToBeBurnt=_calculateFee(amount, tax, _burnTax); uint256 contractToken=_calculateFee(amount, tax, _marketingTax+_liquidityTax); //Subtract the Taxed Tokens from the amount uint256 taxedAmount=amount-(tokensToBeBurnt + contractToken); //Removes token _removeToken(sender,amount); //Adds the taxed tokens to the contract wallet _balances[address(this)] += contractToken; //Burns tokens _circulatingSupply-=tokensToBeBurnt; //Adds token _addToken(recipient, taxedAmount); emit Transfer(sender,recipient,taxedAmount); } //Feeless transfer only transfers function _feelessTransfer(address sender, address recipient, uint256 amount) private{ uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); //Removes token _removeToken(sender,amount); //Adds token _addToken(recipient, amount); emit Transfer(sender,recipient,amount); } //Calculates the token that should be taxed function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) { return (amount*tax*taxPercent) / 10000; } //balance that is claimable by the team uint256 public marketingBalance; //adds Token to balances function _addToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]+amount; //sets newBalance _balances[addr]=newAmount; } //removes Token function _removeToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]-amount; //sets newBalance _balances[addr]=newAmount; } //Swap Contract Tokens////////////////////////////////////////////////////////////////////////////////// //tracks auto generated ETH, useful for ticker etc uint256 public totalLPETH; //Locks the swap if already swapping bool private _isSwappingContractModifier; modifier lockTheSwap { _isSwappingContractModifier = true; _; _isSwappingContractModifier = false; } //swaps the token on the contract for Marketing ETH and LP Token. //always swaps the sellLimit of token to avoid a large price impact function _swapContractToken() private lockTheSwap{ uint256 contractBalance=_balances[address(this)]; uint16 totalTax=_marketingTax+_liquidityTax; uint256 tokenToSwap = currentAmountToSwap; //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0 if(contractBalance<tokenToSwap||totalTax==0){ return; } //splits the token in TokenForLiquidity and tokenForMarketing uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax; uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity; //splits tokenForLiquidity in 2 halves uint256 liqToken=tokenForLiquidity/2; uint256 liqETHToken=tokenForLiquidity-liqToken; //swaps marktetingToken and the liquidity token half for ETH uint256 swapToken=liqETHToken+tokenForMarketing; //Gets the initial ETH balance uint256 initialETHBalance = address(this).balance; _swapTokenForETH(swapToken); uint256 newETH=(address(this).balance - initialETHBalance); //calculates the amount of ETH belonging to the LP-Pair and converts them to LP uint256 liqETH = (newETH*liqETHToken)/swapToken; _addLiquidity(liqToken, liqETH); //Get the ETH balance after LP generation to get the //exact amount of token left for marketing uint256 distributeETH=(address(this).balance - initialETHBalance); //distributes remaining BETHNB to Marketing marketingBalance+=distributeETH; } //swaps tokens on the contract for ETH function _swapTokenForETH(uint256 amount) private { _approve(address(this), address(_uniswapV2Router), amount); address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); } //Adds Liquidity directly to the contract where LP are locked(unlike safemoon forks, that transfer it to the owner) function _addLiquidity(uint256 tokenamount, uint256 ethamount) private returns (uint256 tAmountSent, uint256 ethAmountSent) { totalLPETH+=ethamount; uint256 minETH = (ethamount*75) / 100; uint256 minTokens = (tokenamount*75) / 100; _approve(address(this), address(_uniswapV2Router), tokenamount); _uniswapV2Router.addLiquidityETH{value: ethamount}( address(this), tokenamount, minTokens, minETH, address(this), block.timestamp ); tAmountSent = tokenamount; ethAmountSent = ethamount; return (tAmountSent, ethAmountSent); } //public functions ///////////////////////////////////////////////////////////////////////////////////// function getLiquidityReleaseTimeInSeconds() external view returns (uint256){ if(block.timestamp<_liquidityUnlockTime){ return _liquidityUnlockTime-block.timestamp; } return 0; } function getBurnedTokens() external view returns(uint256){ return (InitialSupply-_circulatingSupply)/10**_decimals; } function getLimits() external view returns(uint256 balance, uint256 sell){ return(balanceLimit/10**_decimals, sellLimit/10**_decimals); } function getTaxes() external view returns(uint256 burnTax,uint256 liquidityTax, uint256 marketingTax, uint256 buyTax, uint256 sellTax, uint256 transferTax){ return (_burnTax,_liquidityTax,_marketingTax,_buyTax,_sellTax,_transferTax); } //How long is a given address still locked from buying function getAddressBuyLockTimeInSeconds(address AddressToCheck) external view returns (uint256){ uint256 lockTime=_buyLock[AddressToCheck]; if(lockTime<=block.timestamp) { return 0; } return lockTime-block.timestamp; } function getBuyLockTimeInSeconds() external view returns(uint256){ return buyLockTime; } //Functions every wallet can call //Resets buy lock of caller to the default buyLockTime should something go very wrong function AddressResetBuyLock() external{ _buyLock[msg.sender]=block.timestamp+buyLockTime; } //Settings////////////////////////////////////////////////////////////////////////////////////////////// bool public buyLockDisabled; uint256 public buyLockTime; bool public manualConversion; function TeamWithdrawALLMarketingETH() external onlyOwner{ uint256 amount=marketingBalance; marketingBalance=0; payable(TeamWallet).transfer((amount*37) / 100); payable(BuyBackWallet).transfer((amount-(amount*37) / 100)); emit Transfer(address(this), TeamWallet, (amount*37) / 100); emit Transfer(address(this), BuyBackWallet, (amount-(amount*37) / 100)); } function TeamWithdrawXMarketingETH(uint256 amount) external onlyOwner{ require(amount<=marketingBalance, "Error: Amount greater than available balance."); marketingBalance-=amount; payable(TeamWallet).transfer((amount*37) / 100); payable(BuyBackWallet).transfer((amount-(amount*37) / 100)); emit Transfer(address(this), TeamWallet, (amount*37) / 100); emit Transfer(address(this), BuyBackWallet, (amount-(amount*37) / 100)); } //switches autoLiquidity and marketing ETH generation during transfers function TeamSwitchManualETHConversion(bool manual) external onlyOwner{ manualConversion=manual; emit ContractChangedBool(manualConversion); } function TeamChangeAntiWhale(uint256 newAntiWhale) external onlyOwner{ antiWhale=newAntiWhale * 10**_decimals; emit ContractChanged(antiWhale); } function TeamChangeTeamWallet(address newTeamWallet) external onlyOwner{ require(newTeamWallet != address(0), "Error: Cannot be 0 address."); TeamWallet=payable(newTeamWallet); emit ContractChangedAddress(TeamWallet); } function TeamChangeBuyBackWallet(address newBuyBackWallet) external onlyOwner{ require(newBuyBackWallet != address(0), "Error: Cannot be 0 address."); BuyBackWallet=payable(newBuyBackWallet); emit ContractChangedAddress(BuyBackWallet); } //Disables the timeLock after buying for everyone function TeamDisableBuyLock(bool disabled) external onlyOwner{ buyLockDisabled=disabled; emit ContractChangedBool(buyLockDisabled); } //Sets BuyLockTime, needs to be lower than MaxBuyLockTime function TeamSetBuyLockTime(uint256 buyLockSeconds) external onlyOwner{ require(buyLockSeconds<=MaxBuyLockTime,"Buy Lock time too high"); buyLockTime=buyLockSeconds; emit ContractChanged(buyLockTime); } //Allows CA owner to change how much the contract sells to prevent massive contract sells as the token grows. function TeamUpdateAmountToSwap(uint256 newSwapAmount) external onlyOwner{ currentAmountToSwap = newSwapAmount; emit ContractChanged(currentAmountToSwap); } //Allows wallet exclusion to be added after launch function addWalletExclusion(address exclusionAdd) external onlyOwner{ _excluded.add(exclusionAdd); emit ContractChangedAddress(exclusionAdd); } //Allows you to remove wallet exclusions after launch function removeWalletExclusion(address exclusionRemove) external onlyOwner{ _excluded.remove(exclusionRemove); emit ContractChangedAddress(exclusionRemove); } //Adds address to blacklist and prevents sells, buys or transfers. function addAddressToBlacklist(address blacklistedAddress) external onlyOwner { blackList[ blacklistedAddress ] = true; emit ContractChangedAddress(blacklistedAddress); } function blacklistAddressArray ( address [] memory _address ) public onlyOwner { for ( uint256 x=0; x< _address.length ; x++ ){ blackList[_address[x]] = true; } } //Check if address is blacklisted (can be called by anyone) function checkAddressBlacklist(address submittedAddress) external view returns (bool isBlacklisted) { if (blackList[submittedAddress] == true) { isBlacklisted = true; return isBlacklisted; } if (blackList[submittedAddress] == false) { isBlacklisted = false; return isBlacklisted; } } //Remove address from blacklist and allow sells, buys or transfers. function removeAddressFromBlacklist(address blacklistedAddress) external onlyOwner { blackList[ blacklistedAddress ] = false; emit ContractChangedAddress(blacklistedAddress); } //Sets Taxes, is limited by MaxTax(20%) to make it impossible to create honeypot function TeamSetTaxes(uint8 burnTaxes, uint8 liquidityTaxes, uint8 marketingTaxes, uint8 buyTax, uint8 sellTax, uint8 transferTax) external onlyOwner{ uint8 totalTax=burnTaxes+liquidityTaxes+marketingTaxes; require(totalTax==100, "burn+liq+marketing needs to equal 100%"); require(buyTax <= 20, "Error: Honeypot prevention prevents buyTax from exceeding 20."); require(sellTax <= 20, "Error: Honeypot prevention prevents sellTax from exceeding 20."); require(transferTax <= 20, "Error: Honeypot prevention prevents transferTax from exceeding 20."); _burnTax=burnTaxes; _liquidityTax=liquidityTaxes; _marketingTax=marketingTaxes; _buyTax=buyTax; _sellTax=sellTax; _transferTax=transferTax; emit ContractChanged(_burnTax); emit ContractChanged(_liquidityTax); emit ContractChanged(_buyTax); emit ContractChanged(_sellTax); emit ContractChanged(_transferTax); } //manually converts contract token to LP function TeamCreateLPandETH() external onlyOwner{ _swapContractToken(); } function teamUpdateUniswapRouter(address newRouter) external onlyOwner { require(newRouter != address(0), "Error: Cannot be 0 address."); uniswapV2Router=newRouter; emit ContractChangedAddress(newRouter); } //Limits need to be at least target, to avoid setting value to 0(avoid potential Honeypot) function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) external onlyOwner{ //SellLimit needs to be below 1% to avoid a Large Price impact when generating auto LP require(newSellLimit<_circulatingSupply/100, "Error: New sell limit above 1% of circulating supply."); //Adds decimals to limits newBalanceLimit=newBalanceLimit*10**_decimals; newSellLimit=newSellLimit*10**_decimals; //Calculates the target Limits based on supply uint256 targetBalanceLimit=_circulatingSupply/BalanceLimitDivider; uint256 targetSellLimit=_circulatingSupply/SellLimitDivider; require((newBalanceLimit>=targetBalanceLimit), "newBalanceLimit needs to be at least target"); require((newSellLimit>=targetSellLimit), "newSellLimit needs to be at least target"); balanceLimit = newBalanceLimit; sellLimit = newSellLimit; emit ContractChanged(balanceLimit); emit ContractChanged(sellLimit); } //Setup Functions/////////////////////////////////////////////////////////////////////////////////////// bool public tradingEnabled; address private _liquidityTokenAddress; //Enables trading for everyone function SetupEnableTrading() external onlyOwner{ tradingEnabled=true; tradingEnabledAt=block.timestamp; } //Sets up the LP-Token Address required for LP Release function SetupLiquidityTokenAddress(address liquidityTokenAddress) external onlyOwner{ require(liquidityTokenAddress != address(0), "Error: Cannot be 0 address."); _liquidityTokenAddress=liquidityTokenAddress; } //Liquidity Lock//////////////////////////////////////////////////////////////////////////////////////// //the timestamp when Liquidity unlocks uint256 private _liquidityUnlockTime; //Adds time to LP lock in seconds. function TeamProlongLiquidityLockInSeconds(uint256 secondsUntilUnlock) external onlyOwner{ _prolongLiquidityLock(secondsUntilUnlock+block.timestamp); emit ContractChanged(secondsUntilUnlock+block.timestamp); } //Adds time to LP lock based on set time. function _prolongLiquidityLock(uint256 newUnlockTime) private{ // require new unlock time to be longer than old one require(newUnlockTime>_liquidityUnlockTime, "Error: New unlock time is shorter than old one."); _liquidityUnlockTime=newUnlockTime; emit ContractChanged(_liquidityUnlockTime); } //Release Liquidity Tokens once unlock time is over function TeamReleaseLiquidity() external onlyOwner returns (address tWAddress, uint256 amountSent) { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); //Liquidity release if something goes wrong at start liquidityToken.transfer(TeamWallet, amount); emit Transfer(address(this), TeamWallet, amount); tWAddress = TeamWallet; amountSent = amount; return (tWAddress, amountSent); } //Removes Liquidity once unlock Time is over, function TeamRemoveLiquidity() external onlyOwner returns (uint256 newBalance) { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); liquidityToken.approve(address(_uniswapV2Router),amount); //Removes Liquidity and adds it to marketing Balance uint256 initialETHBalance = address(this).balance; _uniswapV2Router.removeLiquidityETHSupportingFeeOnTransferTokens( address(this), amount, (amount*75) / 100, (amount*75) / 100, address(this), block.timestamp ); uint256 newETHBalance = address(this).balance-initialETHBalance; marketingBalance+=newETHBalance; newBalance=newETHBalance; return newBalance; } //Releases all remaining ETH on the contract wallet, so ETH wont be burned function TeamRemoveRemainingETH() external onlyOwner{ require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); (bool sent,) =TeamWallet.call{value: (address(this).balance)}(""); require(sent, "Error: Not sent."); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //external////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// receive() external payable {} fallback() external payable {} // IBEP20 function getOwner() external view override returns (address) { return owner(); } function name() external pure override returns (string memory) { return _name; } function symbol() external pure override returns (string memory) { return _symbol; } function decimals() external pure override returns (uint8) { return _decimals; } function totalSupply() external view override returns (uint256) { return _circulatingSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address _owner, address spender) external view override returns (uint256) { return _allowances[_owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "Approve from zero"); require(spender != address(0), "Approve to zero"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "Transfer > allowance"); _approve(sender, msg.sender, currentAllowance - amount); return true; } // IBEP20 - Helpers function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "<0 allowance"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } }
adds Token to balancesthe amount of token after transfersets newBalance
function _addToken(address addr, uint256 amount) private { uint256 newAmount=_balances[addr]+amount; _balances[addr]=newAmount; }
138,037
./full_match/1/0x70588Eb4626600e6b9cD49b140E39e5a814D9535/sources/erc721bo/contracts/ERC721BO.sol
Same as `_safeReMint`, with an additional `data` parameter which is forwarded in IERC721Receiver.onERC721Received to contract recipients./
function _safeReMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _remint(to, tokenId); if (!_checkOnERC721Received(address(0), to, tokenId, _data)) revert TransferToNonERC721ReceiverImplementer(); }
3,053,407
./full_match/3/0xB28E516287E15Aa9694e5802Dde276bE53124437/sources/browser/New_EIP_Interface.sol
send `_value` token to `_to` from `_from` on the condition it is approved by `_from` _from The address of the sender _to The address of the recipient _value The amount of token to be transferred return success Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) virtual public returns (bool success) {}
14,241,526
./full_match/5/0xbd2b42146E75dDc07c29888DAec04Fb176889685/sources/contracts/ArtStation_v0.2.sol
Mint new NFT (no minimum sell price set yet). Can only be called by the contract owner. _to Recipient of the NFT. _tokenId Custom unique token ID of the NFT./
function safeMint(address _to, uint256 _tokenId) public onlyOwner { _safeMint(_to, _tokenId); }
1,940,037
/** *Submitted for verification at Etherscan.io on 2021-03-23 */ // Sources flattened with hardhat v2.1.1 https://hardhat.org // SPDX-License-Identifier: MIT pragma solidity 0.8.0; // File src/contracts/tokens/erc721.sol /** * @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); } // File src/contracts/tokens/erc721-token-receiver.sol /** * @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); } // File src/contracts/utils/erc165.sol /** * @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); } // File src/contracts/utils/supports-interface.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 view override returns (bool) { return supportedInterfaces[_interfaceID]; } } // File src/contracts/utils/address-utils.sol /** * @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); } } // File src/contracts/tokens/nf-token.sol /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract NFToken is ERC721, SupportsInterface { 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 = "003001"; string constant NOT_VALID_NFT = "003002"; string constant NOT_OWNER_OR_OPERATOR = "003003"; string constant NOT_OWNER_APPROVED_OR_OPERATOR = "003004"; string constant NOT_ABLE_TO_RECEIVE_NFT = "003005"; string constant NFT_ALREADY_EXISTS = "003006"; string constant NOT_OWNER = "003007"; string constant IS_OWNER = "003008"; /** * @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 msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate(uint256 _tokenId) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_OR_OPERATOR ); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer(uint256 _tokenId) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || 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); if (tokenOwner == msg.sender) { _transfer(_to, _tokenId); } else { _fakeTransfer(_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 view override 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 view override 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 view override 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 view override 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); emit Transfer(from, _to, _tokenId); } /** * @dev Perform a fake transfer * @notice Does NO checks. * @param _to Address of what might have been the new owner. * @param _tokenId The NFT that is not going to be transferred. */ function _fakeTransfer(address _to, uint256 _tokenId) internal { address tokenOwner = idToOwner[_tokenId]; address approved = idToApproval[_tokenId]; emit Transfer(tokenOwner, _to, _tokenId); emit Transfer(_to, tokenOwner, _tokenId); if (approved != address(0)) { emit Approval(tokenOwner, approved, _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 msg.sender. */ 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); 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 view virtual 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); if (tokenOwner == msg.sender) { _transfer(_to, _tokenId); } else { _fakeTransfer(_to, _tokenId); } } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function _clearApproval(uint256 _tokenId) private { if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; } } } // File src/contracts/tokens/erc721-metadata.sol /** * @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); } // File src/contracts/tokens/nf-token-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 view override returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external view override 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 view override 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 virtual override { 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; } } // File src/contracts/ownership/ownable.sol /** * @dev The contract has an owner address, and provides basic authorization control whitch * simplifies the implementation of user permissions. This contract is based on the source code at: * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol */ contract Ownable { /** * @dev Error constants. */ string public constant NOT_CURRENT_OWNER = "018001"; string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = "018002"; /** * @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); /** * @dev The constructor sets the original `owner` of the contract to the sender account. */ constructor() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, NOT_CURRENT_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), CANNOT_TRANSFER_TO_ZERO_ADDRESS); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File deploy/v1/create.sol pragma solidity 0.8.0; contract MarioXCantBuyThis is NFTokenMetadata, Ownable { /** * @dev Contract constructor. Sets metadata extension `name` and `symbol`. */ constructor() { nftName = "MarioX - Can't buy this"; nftSymbol = "CANTBUY"; } /** * @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. * @param _uri String representing RFC 3986 URI. */ function mint( address _to, uint256 _tokenId, string calldata _uri ) external onlyOwner { super._mint(_to, _tokenId); super._setTokenUri(_tokenId, _uri); } }
A standard for detecting smart contract interfaces./
interface ERC165 { function supportsInterface(bytes4 _interfaceID) external view returns (bool); } }
7,944,232
./full_match/44787/0x792C37e5E135A4a643796d17e4C1D8De1cf59E0f/sources/contracts/mocks/MockTreasury.sol
/ convert amount to match TELO decimals
function valueOfToken(address _token, uint256 _amount) public view returns (uint256 value_) { if (isReserveToken[_token]) { value_ = _amount.mul(10**IERC20(TELO).decimals()).div( 10**IERC20(_token).decimals() ); value_ = IBondCalculator(bondCalculator[_token]).valuation( _token, _amount ); } } @param _managing MANAGING @param _address address @return bool
13,287,200
./partial_match/1/0xB02b25158d0875de0A9084eC85768133f97A9828/sources/src/Cassette.sol
Calculate page number of a specified token ID _tokenId Token ID to return the page number of return uint256 A token's corresponding page number/
function page(uint256 _tokenId) public view returns (uint256) { if (_tokenId > MAX_PAGE * TOTAL_CHAINS) revert Cassette_ValueOutOfRange(); return _tokenId == 0 ? 0 : (_tokenId + TOTAL_CHAINS - 1) / TOTAL_CHAINS; }
9,352,327
//Address: 0xd3a97d46fd0c28a5a035a4e0813afe7c2c1376bd //Contract name: InterCrypto //Balance: 0 Ether //Verification Date: 8/15/2017 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.15; 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 { require(newOwner != address(0)); owner = newOwner; } } interface OraclizeI { // address public cbAddress; function cbAddress() constant returns (address); // Reads public variable cbAddress function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasoaurce) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } interface OraclizeAddrResolverI { function getAddress() returns (address _addr); } // this is a reduced and optimize version of the usingOracalize contract in https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol contract myUsingOracalize is Ownable { OraclizeAddrResolverI OAR; OraclizeI public oraclize; uint public oracalize_gaslimit = 100000; function myUsingOracalize() { oraclize_setNetwork(); update_oracalize(); } function update_oracalize() public { oraclize = OraclizeI(OAR.getAddress()); } function oraclize_query(string datasource, string arg1, string arg2) internal returns (bytes32 id) { uint price = oraclize.getPrice(datasource, oracalize_gaslimit); if (price > 1 ether + tx.gasprice*oracalize_gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, oracalize_gaslimit); } function oraclize_getPrice(string datasource) internal returns (uint) { return oraclize.getPrice(datasource, oracalize_gaslimit); } function setGasLimit(uint _newLimit) onlyOwner public { oracalize_gaslimit = _newLimit; } function oraclize_setNetwork() internal { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); } else if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); } else if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); } else if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); } else if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); } else if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); } else if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); } else { revert(); } } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } return _size; } // This will not throw error on wrong input, but instead consume large and unknown amount of gas // This should never occure as it's use with the ShapeShift deposit return value is checked before calling function function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } } /// @title Inter-crypto currency converter /// @author Jack Tanner - <[email protected]> contract InterCrypto is Ownable, myUsingOracalize { // _______________VARIABLES_______________ struct Transaction { address returnAddress; uint amount; } mapping (uint => Transaction) public transactions; uint transactionCount = 0; mapping (bytes32 => uint) oracalizeMyId2transactionID; mapping (address => uint) public recoverable; // _______________EVENTS_______________ event TransactionStarted(uint indexed transactionID); event TransactionSentToShapeShift(uint indexed transactionID, address indexed returnAddress, address indexed depositAddress, uint amount); event TransactionAborted(uint indexed transactionID, string reason); event Recovered(address indexed recoveredTo, uint amount); // _______________EXTERNAL FUNCTIONS_______________ // constructor function InterCrypto() {} // suicide function function kill() onlyOwner external { selfdestruct(owner); } // Default function which will accept Ether function () payable {} // Return the price of using Oracalize function getInterCryptoPrice() constant public returns (uint) { return oraclize_getPrice('URL'); } // Create a cryptocurrency conversion using Oracalize and Shapeshift return address = msg.sender function sendToOtherBlockchain1(string _coinSymbol, string _toAddress) external payable returns(uint) { return engine(_coinSymbol, _toAddress, msg.sender); } // Create a cryptocurrency conversion using Oracalize and custom Shapeshift return address function sendToOtherBlockchain2(string _coinSymbol, string _toAddress, address _returnAddress) external payable returns(uint) { return engine(_coinSymbol, _toAddress, _returnAddress); } // Callback function for Oracalize function __callback(bytes32 myid, string result) { if (msg.sender != oraclize.cbAddress()) revert(); uint transactionID = oracalizeMyId2transactionID[myid]; Transaction memory transaction = transactions[transactionID]; if( bytes(result).length == 0 ) { TransactionAborted(transactionID, "Oracalize return value was invalid, this is probably due to incorrect sendToOtherBlockchain() argments"); recoverable[transaction.returnAddress] += transaction.amount; transaction.amount = 0; } else { address depositAddress = parseAddr(result); require(depositAddress != msg.sender); // prevent DAO tpe recursion hack that can potentially be done by oracalize uint sendAmount = transaction.amount; transaction.amount = 0; if (depositAddress.send(sendAmount)) TransactionSentToShapeShift(transactionID, transaction.returnAddress, depositAddress, sendAmount); else { TransactionAborted(transactionID, "transaction to address returned by Oracalize failed"); recoverable[transaction.returnAddress] += sendAmount; } } } // Cancel a transaction that has not been completed // Note that this should only be required if Oracalize should fail to respond function cancelTransaction(uint transactionID) external { Transaction memory transaction = transactions[transactionID]; if (transaction.amount > 0) { require(msg.sender == transaction.returnAddress); recoverable[msg.sender] += transaction.amount; transaction.amount = 0; TransactionAborted(transactionID, "transaction cancelled by creator"); } } // Send any pending funds back to their owner function recover() external { uint amount = recoverable[msg.sender]; recoverable[msg.sender] = 0; if (msg.sender.send(amount)) { Recovered(msg.sender, amount); } else { recoverable[msg.sender] = amount; } } // _______________PUBLIC FUNCTIONS_______________ // _______________INTERNAL FUNCTIONS_______________ // Request for a ShapeShift transaction to be made function engine(string _coinSymbol, string _toAddress, address _returnAddress) internal returns(uint transactionID) { // Example arguments: // "ltc", "LbZcDdMeP96ko85H21TQii98YFF9RgZg3D" Litecoin // "btc", "1L8oRijgmkfcZDYA21b73b6DewLtyYs87s" Bitcoin // "dash", "Xoopows17idkTwNrMZuySXBwQDorsezQAx" Dash // "zec", "t1N7tf1xRxz5cBK51JADijLDWS592FPJtya" ZCash // "doge", "DMAFvwTH2upni7eTau8au6Rktgm2bUkMei" Dogecoin // See https://info.shapeshift.io/about // Test symbol pairs using ShapeShift API (shapeshift.io/validateAddress/[address]/[coinSymbol]) or by creating a test // transaction first whenever possible before using it with InterCrypto transactionID = transactionCount++; if (!isValidateParameter(_coinSymbol, 6) || !isValidateParameter(_toAddress, 120)) { // Waves smbol is "waves" , Monero integrated addresses are 106 characters TransactionAborted(transactionID, "input parameters are too long or contain invalid symbols"); recoverable[msg.sender] += msg.value; return; } uint oracalizePrice = getInterCryptoPrice(); if (msg.value > oracalizePrice) { Transaction memory transaction = Transaction(_returnAddress, msg.value-oracalizePrice); transactions[transactionID] = transaction; // Create post data string like ' {"withdrawal":"LbZcDdMeP96ko85H21TQii98YFF9RgZg3D","pair":"eth_ltc","returnAddress":"558999ff2e0daefcb4fcded4c89e07fdf9ccb56c"}' string memory postData = createShapeShiftTransactionPost(_coinSymbol, _toAddress); // TODO: send custom gasLimit for retrn transaction equal to the exact cost of __callback. Note that this should only be donewhen the contract is finalized bytes32 myQueryId = oraclize_query("URL", "json(https://shapeshift.io/shift).deposit", postData); if (myQueryId == 0) { TransactionAborted(transactionID, "unexpectedly high Oracalize price when calling oracalize_query"); recoverable[msg.sender] += msg.value-oracalizePrice; transaction.amount = 0; return; } oracalizeMyId2transactionID[myQueryId] = transactionID; TransactionStarted(transactionID); } else { TransactionAborted(transactionID, "Not enough Ether sent to cover Oracalize fee"); // transactions[transactionID].amount = 0; recoverable[msg.sender] += msg.value; } } // Adapted from https://github.com/kieranelby/KingOfTheEtherThrone/blob/master/contracts/KingOfTheEtherThrone.sol function isValidateParameter(string _parameter, uint maxSize) constant internal returns (bool allowed) { bytes memory parameterBytes = bytes(_parameter); uint lengthBytes = parameterBytes.length; if (lengthBytes < 1 || lengthBytes > maxSize) { return false; } for (uint i = 0; i < lengthBytes; i++) { byte b = parameterBytes[i]; if ( !( (b >= 48 && b <= 57) || // 0 - 9 (b >= 65 && b <= 90) || // A - Z (b >= 97 && b <= 122) // a - z )) { return false; } } return true; } function concatBytes(bytes b1, bytes b2, bytes b3, bytes b4, bytes b5, bytes b6, bytes b7) internal returns (bytes bFinal) { bFinal = new bytes(b1.length + b2.length + b3.length + b4.length + b5.length + b6.length + b7.length); uint i = 0; uint j; for (j = 0; j < b1.length; j++) bFinal[i++] = b1[j]; for (j = 0; j < b2.length; j++) bFinal[i++] = b2[j]; for (j = 0; j < b3.length; j++) bFinal[i++] = b3[j]; for (j = 0; j < b4.length; j++) bFinal[i++] = b4[j]; for (j = 0; j < b5.length; j++) bFinal[i++] = b5[j]; for (j = 0; j < b6.length; j++) bFinal[i++] = b6[j]; for (j = 0; j < b7.length; j++) bFinal[i++] = b7[j]; } function createShapeShiftTransactionPost(string _coinSymbol, string _toAddress) internal returns (string sFinal) { string memory s1 = ' {"withdrawal":"'; string memory s3 = '","pair":"eth_'; string memory s5 = '","returnAddress":"'; string memory s7 = '"}'; bytes memory bFinal = concatBytes(bytes(s1), bytes(_toAddress), bytes(s3), bytes(_coinSymbol), bytes(s5), bytes(addressToBytes(msg.sender)), bytes(s7)); sFinal = string(bFinal); } // Authored by https://github.com/axic function nibbleToChar(uint nibble) internal returns (uint ret) { if (nibble > 9) return nibble + 87; // nibble + 'a'- 10 else return nibble + 48; // '0' } // Authored by https://github.com/axic function addressToBytes(address _address) internal returns (bytes) { uint160 tmp = uint160(_address); // 40 bytes of space, but actually uses 64 bytes string memory holder = " "; bytes memory ret = bytes(holder); // NOTE: this is written in an expensive way, as out-of-order array access // is not supported yet, e.g. we cannot go in reverse easily // (or maybe it is a bug: https://github.com/ethereum/solidity/issues/212) uint j = 0; for (uint i = 0; i < 20; i++) { uint _tmp = tmp / (2 ** (8*(19-i))); // shr(tmp, 8*(19-i)) uint nb1 = (_tmp / 0x10) & 0x0f; // shr(tmp, 8) & 0x0f uint nb2 = _tmp & 0x0f; ret[j++] = byte(nibbleToChar(nb1)); ret[j++] = byte(nibbleToChar(nb2)); } return ret; } // _______________PRIVATE FUNCTIONS_______________ }
_______________INTERNAL FUNCTIONS_______________ Request for a ShapeShift transaction to be made Example arguments: "ltc", "LbZcDdMeP96ko85H21TQii98YFF9RgZg3D" Litecoin "btc", "1L8oRijgmkfcZDYA21b73b6DewLtyYs87s" Bitcoin "dash", "Xoopows17idkTwNrMZuySXBwQDorsezQAx" Dash "zec", "t1N7tf1xRxz5cBK51JADijLDWS592FPJtya" ZCash "doge", "DMAFvwTH2upni7eTau8au6Rktgm2bUkMei" Dogecoin See https:info.shapeshift.io/about Test symbol pairs using ShapeShift API (shapeshift.io/validateAddress/[address]/[coinSymbol]) or by creating a test transaction first whenever possible before using it with InterCrypto
function engine(string _coinSymbol, string _toAddress, address _returnAddress) internal returns(uint transactionID) { transactionID = transactionCount++; TransactionAborted(transactionID, "input parameters are too long or contain invalid symbols"); recoverable[msg.sender] += msg.value; return; } uint oracalizePrice = getInterCryptoPrice();
13,112,240
./partial_match/1/0x24276C57C033E4e25E0CdBC4a98e2e9B767c2A98/sources/contracts/protocol/libraries/logic/ConfiguratorLogic.sol
Updates the xToken implementation and initializes it Emits the `XTokenUpgraded` event cachedPool The Pool containing the reserve with the xToken input The parameters needed for the initialize call/
function executeUpdatePToken( IPool cachedPool, ConfiguratorInputTypes.UpdatePTokenInput calldata input ) public { DataTypes.ReserveData memory reserveData = cachedPool.getReserveData( input.asset ); (, , , uint256 decimals, ) = cachedPool .getConfiguration(input.asset) .getParams(); bytes memory encodedCall = abi.encodeWithSelector( IInitializablePToken.initialize.selector, cachedPool, input.treasury, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.xTokenAddress, input.implementation, encodedCall ); emit PTokenUpgraded( input.asset, reserveData.xTokenAddress, input.implementation ); }
4,266,870
pragma solidity ^0.6.3; import "./ERC20Interface.sol"; import "./BlackCaspianUpgradeable.sol"; contract ERC20Proxy is ERC20Interface, BlackCaspianUpgradeable { // MEMBERS /// @notice Returns the name of the token. string public name; /// @notice Returns the symbol of the token. string public symbol; /// @notice Returns the number of decimals the token uses. uint8 public decimals; // CONSTRUCTOR function ERC20Proxy( string _name, string _symbol, uint8 _decimals, address _custodian ) BlackCaspianUpgradeable(_custodian) public { name = _name; symbol = _symbol; decimals = _decimals; } // PUBLIC FUNCTIONS // (ERC20Interface) /** @notice Returns the total token supply. * * @return the total token supply. */ function totalSupply() public view returns (uint256) { return BlackCaspian.totalSupply(); } /** @notice Returns the account balance of another account with address * `_owner`. * * @return balance the balance of account with address `_owner`. */ function balanceOf(address _owner) public view returns (uint256 balance) { return BlackCaspian.balanceOf(_owner); } /** @dev Internal use only. */ function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl { emit Transfer(_from, _to, _value); } /** @notice Transfers `_value` amount of tokens to address `_to`. * * @dev Will fire the `Transfer` event. Will revert if the `_from` * account balance does not have enough tokens to spend. * * @return success true if transfer completes. */ function transfer(address _to, uint256 _value) public returns (bool success) { return BlackCaspian.transferWithSender(msg.sender, _to, _value); } /** @notice Transfers `_value` amount of tokens from address `_from` * to address `_to`. * * @dev Will fire the `Transfer` event. Will revert unless the `_from` * account has deliberately authorized the sender of the message * via some mechanism. * * @return success true if transfer completes. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return BlackCaspian.transferFromWithSender(msg.sender, _from, _to, _value); } /** @dev Internal use only. */ function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl { emit Approval(_owner, _spender, _value); } /** @notice Allows `_spender` to withdraw from your account multiple times, * up to the `_value` amount. If this function is called again it * overwrites the current allowance with _value. * * @dev Will fire the `Approval` event. * * @return success true if approval completes. */ function approve(address _spender, uint256 _value) public returns (bool success) { return BlackCaspian.approveWithSender(msg.sender, _spender, _value); } /** @notice Increases the amount `_spender` is allowed to withdraw from * your account. * This function is implemented to avoid the race condition in standard * ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used instead of * `approve`. * * @return success true if approval completes. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return BlackCaspian.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** @notice Decreases the amount `_spender` is allowed to withdraw from * your account. This function is implemented to avoid the race * condition in standard ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used * instead of `approve`. * * @return success true if approval completes. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return BlackCaspian.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** @notice Returns how much `_spender` is currently allowed to spend from * `_owner`'s balance. * * @return remaining the remaining allowance. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return BlackCaspian.allowance(_owner, _spender); } }
Returns how much `_spender` is currently allowed to spend from `_owner`'s balance. return remaining the remaining allowance./
function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return BlackCaspian.allowance(_owner, _spender); }
5,369,295
/** * This contract specifically stores all the user * data to avoid inconsistencies during Blockvitae * contract update. * * This files acts as the DB layer between the * model User.sol and the controller Blockvitae.sol */ pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; // experimental // imports import "./DB.sol"; contract DBGetter { DB private db; constructor(DB _db) public { db = _db; } modifier isOwner(address _sender) { require(db.isOwnerDB(_sender)); _; } // @description // checks if the user with given address exists // // @param address _user // address of the user to be looked up // // @return bool // true if user exists else false function isUserExists(address _user) public view isOwner(msg.sender) returns(bool) { require(_user != address(0)); return db.isExists(_user, msg.sender); } // @description // finds the UserEducation struct values for the given user // // @param address _user // address of the user who's data is to be searched // // @return User.UserEducation[] // UserEducation struct array of the user with given address function findUserEducation(address _user) view public isOwner(msg.sender) returns(User.UserEducation[]){ return db.getUserEducation(_user, msg.sender); } // @description // finds the UserPublication struct values for the given user // // @param address _user // address of the user who's data is to be searched // // @return User.UserPublication[] // UserPublication struct array of the user with given address function findUserPublication(address _user) view public isOwner(msg.sender) returns(User.UserPublication[]){ return db.getUserPublication(_user, msg.sender); } // @description // finds the UserSkill struct values for the given user // // @param address _user // address of the user who's data is to be searched // // @return User.UserSkill // UserSkill struct of the user with given address function findUserSkill(address _user) view public isOwner(msg.sender) returns(User.UserSkill) { return db.getUserSkill(_user, msg.sender); } // @description // finds the UserIntroduction struct values for the given user // // @param address _user // address of the user who's data is to be searched // // @return User.UserIntroduction // UserIntroduction struct of the user with given address function findUserIntroduction(address _user) view public isOwner(msg.sender) returns(User.UserIntroduction) { return db.getUserIntro(_user, msg.sender); } // @description // finds the UserProject struct values for the given user // // @param address _user // address of the user who's data is to be searched // // @return User.UserProject[] // UserProject struct array of the user with given address function findUserProject(address _user) view public isOwner(msg.sender) returns(User.UserProject[]) { return db.getUserProject(_user, msg.sender); } // @description // finds the UserDetail struct values for the given user // // @param address _user // address of the user who's data is to be searched // // @return User.UserDetail // UserDetail struct of the user with given address function findUserDetail(address _user) view public isOwner(msg.sender) returns(User.UserDetail) { return db.getUserDetail(_user, msg.sender); } // @description // finds the UserSocial struct values for the given user // // @param address _user // address of the user who's data is to be searched // // @return User.UserSocial // UserSocial struct of the user with given address function findUserSocial(address _user) view public isOwner(msg.sender) returns(User.UserSocial) { return db.getUserSocial(_user, msg.sender); } // @description // finds the UserWorkExp struct values for the given user // // @param address _user // address of the address of the user who's data is to be searched // // @return User.UserWorkExp // UserWorkExp struct of the user with given address function findUserWorkExp(address _user) view public isOwner(msg.sender) returns(User.UserWorkExp[]) { return db.getUserWorkExp(_user, msg.sender); } // @description // finds the address the given userName // // @param string _userName // userName of the user who's address is to be searched // // @return address // address of the user with given userName function findAddrForUserName(bytes32 _userName) view public isOwner(msg.sender) returns(address) { return db.getUserNameAddr(_userName, msg.sender); } // @description // Checks if the given username is available or taken // // @param string _userName // username to be checked // // @return bool // true if username is available else false function usernameExists(bytes32 _userName) view public isOwner(msg.sender) returns(bool) { if (db.getUserNameAddr(_userName, msg.sender) != address(0x0)) return false; else return true; } }
@description finds the UserWorkExp struct values for the given user address _user address of the address of the user who's data is to be searched return User.UserWorkExp UserWorkExp struct of the user with given address
function findUserWorkExp(address _user) view public isOwner(msg.sender) returns(User.UserWorkExp[]) { return db.getUserWorkExp(_user, msg.sender); }
12,780,495
pragma solidity 0.5.17; import "./MToken.sol"; import "./ErrorReporter.sol"; import "./PriceOracle.sol"; import "./MomaMasterInterface.sol"; import "./MomaMasterStorage.sol"; import "./MomaPool.sol"; /** * @title Moma's MomaMaster Contract * @author Moma */ contract MomaMaster is MomaMasterInterface, MomaMasterV1Storage, MomaMasterErrorReporter, ExponentialNoError { /// @notice Emitted when an admin supports a market event MarketListed(MToken mToken); /// @notice Emitted when an account enters a market event MarketEntered(MToken mToken, address account); /// @notice Emitted when an account exits a market event MarketExited(MToken mToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(MToken mToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a mToken is changed event NewBorrowCap(MToken indexed mToken, uint newBorrowCap); /// @notice Emitted when a new token speed is updated for a market event TokenSpeedUpdated(address indexed token, MToken indexed mToken, uint oldSpeed, uint newSpeed); /// @notice Emitted when token is distributed to a supplier event DistributedSupplierToken(address indexed token, MToken indexed mToken, address indexed supplier, uint tokenDelta, uint tokenSupplyIndex); /// @notice Emitted when token is distributed to a borrower event DistributedBorrowerToken(address indexed token, MToken indexed mToken, address indexed borrower, uint tokenDelta, uint tokenBorrowIndex); /// @notice Emitted when token is claimed by user event TokenClaimed(address indexed token, address indexed user, uint accrued, uint claimed, uint notClaimed); /// @notice Emitted when token farm is updated by admin event TokenFarmUpdated(EIP20Interface token, uint oldStart, uint oldEnd, uint newStart, uint newEnd); /// @notice Emitted when a new token market is added to momaMarkets event NewTokenMarket(address indexed token, MToken indexed mToken); /// @notice Emitted when token is granted by admin event TokenGranted(address token, address recipient, uint amount); /// @notice Indicator that this is a MomaMaster contract (for inspection) bool public constant isMomaMaster = true; /// @notice The initial moma index for a market uint224 public constant momaInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (MToken[] memory) { MToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param mToken The mToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, MToken mToken) external view returns (bool) { return markets[address(mToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param mTokens The list of addresses of the mToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory mTokens) public returns (uint[] memory) { uint len = mTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { MToken mToken = MToken(mTokens[i]); results[i] = uint(addToMarketInternal(mToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param mToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(mToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (oracle.getUnderlyingPrice(mToken) == 0) { // not have price return Error.PRICE_ERROR; } if (marketToJoin.accountMembership[borrower]) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(mToken); emit MarketEntered(mToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param mTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address mTokenAddress) external returns (uint) { MToken mToken = MToken(mTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the mToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(mToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set mToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete mToken from the account’s list of assets */ // load into memory for faster iteration MToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == mToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 MToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(mToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param mToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[mToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateFarmSupplyIndex(mToken); distributeSupplierFarm(mToken, minter); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param mToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address mToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused mToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param mToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateFarmSupplyIndex(mToken); distributeSupplierFarm(mToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[mToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param mToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused mToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param mToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint) { require(isLendingPool, "this is not lending pool"); // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[mToken], "borrow is paused"); if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[mToken].accountMembership[borrower]) { // only mTokens may call borrowAllowed if borrower not in market require(msg.sender == mToken, "sender must be mToken"); // attempt to add borrower to the market Error err = addToMarketInternal(MToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[mToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[mToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = MToken(mToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving uint borrowIndex = MToken(mToken).borrowIndex(); updateFarmBorrowIndex(mToken, borrowIndex); distributeBorrowerFarm(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param mToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address mToken, address borrower, uint borrowAmount) external { // Shh - currently unused mToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param mToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; require(isLendingPool, "this is not lending pool"); if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving uint borrowIndex = MToken(mToken).borrowIndex(); updateFarmBorrowIndex(mToken, borrowIndex); distributeBorrowerFarm(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param mToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address mToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused mToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param mTokenBorrowed Asset which was borrowed by the borrower * @param mTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; require(isLendingPool, "this is not lending pool"); if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param mTokenBorrowed Asset which was borrowed by the borrower * @param mTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused mTokenBorrowed; mTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param mTokenCollateral Asset which was used as collateral and will be seized * @param mTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); require(isLendingPool, "this is not lending pool"); // Shh - currently unused seizeTokens; if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (MToken(mTokenCollateral).momaMaster() != MToken(mTokenBorrowed).momaMaster()) { return uint(Error.MOMAMASTER_MISMATCH); } // Keep the flywheel moving updateFarmSupplyIndex(mTokenCollateral); distributeSupplierFarm(mTokenCollateral, borrower); distributeSupplierFarm(mTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param mTokenCollateral Asset which was used as collateral and will be seized * @param mTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused mTokenCollateral; mTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param mToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(mToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateFarmSupplyIndex(mToken); distributeSupplierFarm(mToken, src); distributeSupplierFarm(mToken, dst); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param mToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer */ function transferVerify(address mToken, address src, address dst, uint transferTokens) external { // Shh - currently unused mToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `mTokenBalance` is the number of mTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint mTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address mTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, MToken mTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in MToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { MToken asset = assets[i]; // Read the balances and exchange rate from the mToken (oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * mTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with mTokenModify if (asset == mTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in mToken.liquidateBorrowFresh) * @param mTokenBorrowed The address of the borrowed mToken * @param mTokenCollateral The address of the collateral mToken * @param actualRepayAmount The amount of mTokenBorrowed underlying to convert into mTokenCollateral tokens * @return (errorCode, number of mTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(MToken(mTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(MToken(mTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = MToken(mTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the MomaMaster * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _updatePriceOracle() public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Read the new oracle from factory address newOracle = MomaFactoryInterface(factory).oracle(); // Check newOracle require(newOracle != address(0), "factory not set oracle"); // Track the old oracle for the MomaMaster PriceOracle oldOracle = oracle; // Set MomaMaster's oracle to newOracle oracle = PriceOracle(newOracle); // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, PriceOracle(newOracle)); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); require(newCloseFactorMantissa >= closeFactorMinMantissa, "close factor too small"); require(newCloseFactorMantissa <= closeFactorMaxMantissa, "close factor too large"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param mToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(mToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } require(newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa, "liquidation incentive too small"); require(newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "liquidation incentive too large"); // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param mToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(MToken mToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (isLendingPool) { require(address(mToken.interestRateModel()) != address(0), "mToken not set interestRateModel"); } // Check is mToken require(MomaFactoryInterface(factory).isMToken(address(mToken)), 'not mToken'); if (markets[address(mToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } require(mToken.isMToken(), 'not mToken contract'); // Sanity check to make sure its really a MToken // Note that isMomaed is not in active use anymore // markets[address(mToken)] = Market({isListed: true, isMomaed: false, collateralFactorMantissa: 0}); markets[address(mToken)] = Market({isListed: true, collateralFactorMantissa: 0}); _addMarketInternal(address(mToken)); emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address mToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != MToken(mToken), "market already added"); } allMarkets.push(MToken(mToken)); } /** * @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or pauseGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param mTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == pauseGuardian, "only admin or pauseGuardian can set borrow caps"); uint numMarkets = mTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(mTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(mTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _upgradeLendingPool() external returns (bool) { require(msg.sender == admin, "only admin can upgrade"); // must update oracle first, it succuss or revert, so no need to check again _updatePriceOracle(); // all markets must set interestRateModel for (uint i = 0; i < allMarkets.length; i++) { MToken mToken = allMarkets[i]; require(address(mToken.interestRateModel()) != address(0), "support market not set interestRateModel"); // require(oracle.getUnderlyingPrice(mToken) != 0, "support market not set price"); // let functions check } bool state = MomaFactoryInterface(factory).upgradeLendingPool(); if (state) { require(updateBorrowBlock() == 0, "update borrow block error"); isLendingPool = true; } return state; } function _setMintPaused(MToken mToken, bool state) external returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state, "only admin can unpause"); mintGuardianPaused[address(mToken)] = state; emit ActionPaused(mToken, "Mint", state); return state; } function _setBorrowPaused(MToken mToken, bool state) external returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state, "only admin can unpause"); borrowGuardianPaused[address(mToken)] = state; emit ActionPaused(mToken, "Borrow", state); return state; } function _setTransferPaused(bool state) external returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) external returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(MomaPool momaPool) external { require(msg.sender == momaPool.admin(), "only momaPool admin can change brains"); require(momaPool._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == momaMasterImplementation; } /*** Farming ***/ /** * @notice Update all markets' borrow block for all tokens when pool upgrade to lending pool * @return uint 0=success, otherwise a failure */ function updateBorrowBlock() internal returns (uint) { uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits"); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; uint32 nextBlock = blockNumber; TokenFarmState storage state = farmStates[token]; if (state.startBlock > blockNumber) nextBlock = state.startBlock; // if (state.endBlock < blockNumber) blockNumber = state.endBlock; MToken[] memory mTokens = state.tokenMarkets; for (uint j = 0; j < mTokens.length; j++) { MToken mToken = mTokens[j]; state.borrowState[address(mToken)].block = nextBlock; // if state.speeds[address(mToken)] > 0 ? } } return uint(Error.NO_ERROR); } /** * @notice Accrue tokens and MOMA to the market by updating the supply index * @param mToken The market whose supply index to update */ function updateFarmSupplyIndex(address mToken) internal { updateMomaSupplyIndex(mToken); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; updateTokenSupplyIndex(token, mToken); } } /** * @notice Accrue tokens and MOMA to the market by updating the supply index * @param mToken The market whose supply index to update * @param marketBorrowIndex The market borrow index */ function updateFarmBorrowIndex(address mToken, uint marketBorrowIndex) internal { updateMomaBorrowIndex(mToken, marketBorrowIndex); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; updateTokenBorrowIndex(token, mToken, marketBorrowIndex); } } /** * @notice Calculate tokens and MOMA accrued by a supplier * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute tokens and MOMA to */ function distributeSupplierFarm(address mToken, address supplier) internal { distributeSupplierMoma(mToken, supplier); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; distributeSupplierToken(token, mToken, supplier); } } /** * @notice Calculate tokens and MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute tokens and MOMA to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerFarm(address mToken, address borrower, uint marketBorrowIndex) internal { distributeBorrowerMoma(mToken, borrower, marketBorrowIndex); for (uint i = 0; i < allTokens.length; i++) { address token = allTokens[i]; distributeBorrowerToken(token, mToken, borrower, marketBorrowIndex); } } /*** Tokens Farming ***/ /** * @notice Accrue token to the market by updating the supply index * @param token The token whose supply index to update * @param mToken The market whose supply index to update */ function updateTokenSupplyIndex(address token, address mToken) internal { delegateToFarming(abi.encodeWithSignature("updateTokenSupplyIndex(address,address)", token, mToken)); } /** * @notice Accrue token to the market by updating the borrow index * @param token The token whose borrow index to update * @param mToken The market whose borrow index to update * @param marketBorrowIndex The market borrow index */ function updateTokenBorrowIndex(address token, address mToken, uint marketBorrowIndex) internal { delegateToFarming(abi.encodeWithSignature("updateTokenBorrowIndex(address,address,uint256)", token, mToken, marketBorrowIndex)); } /** * @notice Calculate token accrued by a supplier * @param token The token in which the supplier is interacting * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute token to */ function distributeSupplierToken(address token, address mToken, address supplier) internal { delegateToFarming(abi.encodeWithSignature("distributeSupplierToken(address,address,address)", token, mToken, supplier)); } /** * @notice Calculate token accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute token to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerToken(address token, address mToken, address borrower, uint marketBorrowIndex) internal { delegateToFarming(abi.encodeWithSignature("distributeBorrowerToken(address,address,address,uint256)", token, mToken, borrower, marketBorrowIndex)); } /*** Reward Public Functions ***/ /** * @notice Distribute all the token accrued to user in specified markets of specified token and claim * @param token The token to distribute * @param mTokens The list of markets to distribute token in * @param suppliers Whether or not to distribute token earned by supplying * @param borrowers Whether or not to distribute token earned by borrowing */ function dclaim(address token, MToken[] memory mTokens, bool suppliers, bool borrowers) public { delegateToFarming(abi.encodeWithSignature("dclaim(address,address[],bool,bool)", token, mTokens, suppliers, borrowers)); } /** * @notice Distribute all the token accrued to user in all markets of specified token and claim * @param token The token to distribute * @param suppliers Whether or not to distribute token earned by supplying * @param borrowers Whether or not to distribute token earned by borrowing */ function dclaim(address token, bool suppliers, bool borrowers) external { delegateToFarming(abi.encodeWithSignature("dclaim(address,bool,bool)", token, suppliers, borrowers)); } /** * @notice Distribute all the token accrued to user in all markets of specified tokens and claim * @param tokens The list of tokens to distribute and claim * @param suppliers Whether or not to distribute token earned by supplying * @param borrowers Whether or not to distribute token earned by borrowing */ function dclaim(address[] memory tokens, bool suppliers, bool borrowers) public { delegateToFarming(abi.encodeWithSignature("dclaim(address[],bool,bool)", tokens, suppliers, borrowers)); } /** * @notice Distribute all the token accrued to user in all markets of all tokens and claim * @param suppliers Whether or not to distribute token earned by supplying * @param borrowers Whether or not to distribute token earned by borrowing */ function dclaim(bool suppliers, bool borrowers) external { delegateToFarming(abi.encodeWithSignature("dclaim(bool,bool)", suppliers, borrowers)); } /** * @notice Claim all the token have been distributed to user of specified token * @param token The token to claim */ function claim(address token) external { delegateToFarming(abi.encodeWithSignature("claim(address)", token)); } /** * @notice Claim all the token have been distributed to user of all tokens */ function claim() external { delegateToFarming(abi.encodeWithSignature("claim()")); } /** * @notice Calculate undistributed token accrued by the user in specified market of specified token * @param user The address to calculate token for * @param token The token to calculate * @param mToken The market to calculate token * @param suppliers Whether or not to calculate token earned by supplying * @param borrowers Whether or not to calculate token earned by borrowing * @return The amount of undistributed token of this user */ function undistributed(address user, address token, address mToken, bool suppliers, bool borrowers) public view returns (uint) { bytes memory data = delegateToFarmingView(abi.encodeWithSignature("undistributed(address,address,address,bool,bool)", user, token, mToken, suppliers, borrowers)); return abi.decode(data, (uint)); } /** * @notice Calculate undistributed tokens accrued by the user in all markets of specified token * @param user The address to calculate token for * @param token The token to calculate * @param suppliers Whether or not to calculate token earned by supplying * @param borrowers Whether or not to calculate token earned by borrowing * @return The amount of undistributed token of this user in each market */ function undistributed(address user, address token, bool suppliers, bool borrowers) public view returns (uint[] memory) { bytes memory data = delegateToFarmingView(abi.encodeWithSignature("undistributed(address,address,bool,bool)", user, token, suppliers, borrowers)); return abi.decode(data, (uint[])); } /*** Token Distribution Admin ***/ /** * @notice Transfer token to the recipient * @dev Note: If there is not enough token, we do not perform the transfer all. * @param token The token to transfer * @param recipient The address of the recipient to transfer token to * @param amount The amount of token to (possibly) transfer */ function _grantToken(address token, address recipient, uint amount) external { delegateToFarming(abi.encodeWithSignature("_grantToken(address,address,uint256)", token, recipient, amount)); } /** * @notice Admin function to add/update erc20 token farming * @dev Can only add token or restart this token farm again after endBlock * @param token Token to add/update for farming * @param start Block heiht to start to farm this token * @param end Block heiht to stop farming * @return uint 0=success, otherwise a failure */ function _setTokenFarm(EIP20Interface token, uint start, uint end) external returns (uint) { bytes memory data = delegateToFarming(abi.encodeWithSignature("_setTokenFarm(address,uint256,uint256)", token, start, end)); return abi.decode(data, (uint)); } /** * @notice Set token speed for multi markets * @dev Note that token speed could be set to 0 to halt liquidity rewards for a market * @param token The token to update speed * @param mTokens The markets whose token speed to update * @param newSpeeds New token speeds for markets */ function _setTokensSpeed(address token, MToken[] memory mTokens, uint[] memory newSpeeds) public { delegateToFarming(abi.encodeWithSignature("_setTokensSpeed(address,address[],uint256[])", token, mTokens, newSpeeds)); } /*** MOMA Farming ***/ /** * @notice Accrue MOMA to the market by updating the supply index * @param mToken The market whose supply index to update */ function updateMomaSupplyIndex(address mToken) internal { IMomaFarming(currentMomaFarming()).updateMarketSupplyState(mToken); } /** * @notice Accrue MOMA to the market by updating the borrow index * @param mToken The market whose borrow index to update * @param marketBorrowIndex The market borrow index */ function updateMomaBorrowIndex(address mToken, uint marketBorrowIndex) internal { IMomaFarming(currentMomaFarming()).updateMarketBorrowState(mToken, marketBorrowIndex); } /** * @notice Calculate MOMA accrued by a supplier * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOMA to */ function distributeSupplierMoma(address mToken, address supplier) internal { IMomaFarming(currentMomaFarming()).distributeSupplierMoma(mToken, supplier); } /** * @notice Calculate MOMA accrued by a borrower * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOMA to * @param marketBorrowIndex The market borrow index */ function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) internal { IMomaFarming(currentMomaFarming()).distributeBorrowerMoma(mToken, borrower, marketBorrowIndex); } /*** View functions ***/ /** * @notice Return all of the support tokens * @dev The automatic getter may be used to access an individual token. * @return The list of market addresses */ function getAllTokens() external view returns (address[] memory) { return allTokens; } /** * @notice Weather a token is farming * @param token The token address to ask for * @param market Which market * @return Wether this market farm the token currently */ function isFarming(address token, address market) external view returns (bool) { uint blockNumber = getBlockNumber(); TokenFarmState storage state = farmStates[token]; return state.speeds[market] > 0 && blockNumber > uint(state.startBlock) && blockNumber <= uint(state.endBlock); } /** * @notice Get the market speed for a token * @param token The token address to ask for * @param market Which market * @return The market farm speed of this token currently */ function getTokenMarketSpeed(address token, address market) external view returns (uint) { return farmStates[token].speeds[market]; } /** * @notice Get the accrued amount of this token farming for a user * @param token The token address to ask for * @param user The user address to ask for * @return The accrued amount of this token farming for a user */ function getTokenUserAccrued(address token, address user) external view returns (uint) { return farmStates[token].accrued[user]; } /** * @notice Weather a market is this token market * @param token The token address to ask for * @param market The market address to ask for * @return true of false */ function isTokenMarket(address token, address market) external view returns (bool) { return farmStates[token].isTokenMarket[market]; } /** * @notice Return all the farming support markets of a token * @param token The token address to ask for * @return The list of market addresses */ function getTokenMarkets(address token) external view returns (MToken[] memory) { return farmStates[token].tokenMarkets; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() external view returns (MToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /*** Delegate ***/ /** * @notice Get current moma farming contract * @return The contract address */ function currentMomaFarming() public view returns (address) { return MomaFactoryInterface(factory).momaFarming(); } /** * @notice Get current farming contract * @return The contract address */ function currentFarmingDelegate() public view returns (address) { return MomaFactoryInterface(factory).farmingDelegate(); } /** * @notice Internal method to delegate execution to farming contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToFarming(bytes memory data) internal returns (bytes memory) { address callee = currentFarmingDelegate(); (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Public method to delegate view execution to farming contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToFarmingSelf(bytes memory data) public returns (bytes memory) { require(msg.sender == address(this), "can only called by self"); return delegateToFarming(data); } /** * @notice Internal method to delegate view execution to farming contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToFarmingView(bytes memory data) internal view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToFarmingSelf(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } } interface IMomaFarming { function updateMarketSupplyState(address mToken) external; function updateMarketBorrowState(address mToken, uint marketBorrowIndex) external; function distributeSupplierMoma(address mToken, address supplier) external; function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) external; function upgradeLendingPool(address pool) external; function isMomaFarming() external view returns (bool); }
Transfer token to the recipient Note: If there is not enough token, we do not perform the transfer all. token The token to transfer recipient The address of the recipient to transfer token to amount The amount of token to (possibly) transfer/
function _grantToken(address token, address recipient, uint amount) external { delegateToFarming(abi.encodeWithSignature("_grantToken(address,address,uint256)", token, recipient, amount)); }
12,663,239
//Address: 0x96b26c1872566fd977e7a282a17bc0203a20a90e //Contract name: SimpleSale //Balance: 0 Ether //Verification Date: 9/21/2017 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.16; /** * @title ERC20 interface * @dev cutdown simply to allow removal of tokens sent to contract */ contract ERC20 { function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @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 Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } // 200 000 000 ether = A56FA5B99019A5C8000000 = 88 bits. We have 256. // we do NOT need safemath. contract SimpleSale is Ownable,Pausable { address public multisig = 0xc862705dDA23A2BAB54a6444B08a397CD4DfCD1c; address public cs; uint256 public totalCollected; bool public saleFinished; uint256 public startTime = 1505998800; uint256 public stopTime = 1508590800; mapping (address => uint256) public deposits; mapping (address => bool) public authorised; // just to annoy the heck out of americans /** * @dev throws if person sending is not contract owner or cs role */ modifier onlyCSorOwner() { require((msg.sender == owner) || (msg.sender==cs)); _; } /** * @dev throws if person sending is not authorised or sends nothing */ modifier onlyAuthorised() { require (authorised[msg.sender]); require (msg.value > 0); require (now >= startTime); require (now <= stopTime); require (!saleFinished); require(!paused); _; } /** * @dev set start and stop times */ function setPeriod(uint256 start, uint256 stop) onlyOwner { startTime = start; stopTime = stop; } /** * @dev authorise an account to participate */ function authoriseAccount(address whom) onlyCSorOwner { authorised[whom] = true; } /** * @dev authorise a lot of accounts in one go */ function authoriseManyAccounts(address[] many) onlyCSorOwner { for (uint256 i = 0; i < many.length; i++) { authorised[many[i]] = true; } } /** * @dev ban an account from participation (default) */ function blockAccount(address whom) onlyCSorOwner { authorised[whom] = false; } /** * @dev set a new CS representative */ function setCS(address newCS) onlyOwner { cs = newCS; } /** * @dev call an end (e.g. because cap reached) */ function stopSale() onlyOwner { saleFinished = true; } function SimpleSale() { } /** * @dev fallback function received ether, sends it to the multisig, notes indivdual and group contributions */ function () payable onlyAuthorised { multisig.transfer(msg.value); deposits[msg.sender] += msg.value; totalCollected += msg.value; } /** * @dev in case somebody sends ERC2o tokens... */ function emergencyERC20Drain( ERC20 token, uint amount ) onlyOwner { token.transfer(owner, amount); } }
set start and stop times/
function setPeriod(uint256 start, uint256 stop) onlyOwner { startTime = start; stopTime = stop; }
1,056,293
// SPDX-License-Identifier: MIT pragma solidity 0.7.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import './mocks/CryptionNetworkToken.sol'; import './lib/EventProof.sol'; import './lib/RLPReader.sol'; contract MasterChef is Ownable{ using SafeMath for uint256; using SafeERC20 for IERC20; using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; /// @notice information stuct on each user than stakes LP tokens. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. } /// @notice all the settings for this farm in one struct struct FarmInfo { IERC20 lpToken; IERC20 rewardToken; uint256 startBlock; uint256 blockReward; uint256 bonusEndBlock; uint256 bonus; uint256 endBlock; uint256 lastRewardBlock; // Last block number that reward distribution occurs. uint256 accRewardPerShare; // Accumulated Rewards per share, times 1e12 uint256 farmableSupply; // set in init, total amount of tokens farmable uint256 numFarmers; } FarmInfo public farmInfo; /// @notice information on each user than stakes LP tokens mapping (address => UserInfo) public userInfo; // Receipts root vs bool. It is used to avoid same tx submission twice. mapping (bytes32 => bool) public receipts; uint256 public constant EVENT_INDEX_IN_RECEIPT = 3; uint256 public TRANSFER_EVENT_PARAMS_INDEX_IN_RECEIPT = 1; bytes32 public constant TRANSFER_EVENT_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; address CRYPTION_VALIDATOR_SHARE_PROXY_CONTRACT = address(0x44d2c14F79EF400D6AF53822a054945704BF1FeA); event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); constructor( IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, uint256 _blockReward, uint256 _startBlock, uint256 _endBlock, uint256 _bonusEndBlock, uint256 _bonus ) public { farmInfo.rewardToken = _rewardToken; farmInfo.startBlock = _startBlock; farmInfo.blockReward = _blockReward; farmInfo.bonusEndBlock = _bonusEndBlock; farmInfo.bonus = _bonus; uint256 lastRewardBlock = block.number > _startBlock ? block.number : _startBlock; farmInfo.lpToken = _lpToken; farmInfo.lastRewardBlock = lastRewardBlock; farmInfo.accRewardPerShare = 0; farmInfo.endBlock = _endBlock; farmInfo.farmableSupply = _amount; } /** * @notice Gets the reward multiplier over the given _fromBlock until _to block * @param _fromBlock the start of the period to measure rewards for * @param _to the end of the period to measure rewards for * @return The weighted multiplier for the given period */ function getMultiplier(uint256 _fromBlock, uint256 _to) public view returns (uint256) { uint256 _from = _fromBlock >= farmInfo.startBlock ? _fromBlock : farmInfo.startBlock; uint256 to = farmInfo.endBlock > _to ? _to : farmInfo.endBlock; if (to <= farmInfo.bonusEndBlock) { return to.sub(_from).mul(farmInfo.bonus); } else if (_from >= farmInfo.bonusEndBlock) { return to.sub(_from); } else { return farmInfo.bonusEndBlock.sub(_from).mul(farmInfo.bonus).add( to.sub(farmInfo.bonusEndBlock) ); } } /** * @notice function to see accumulated balance of reward token for specified user * @param _user the user for whom unclaimed tokens will be shown * @return total amount of withdrawable reward tokens */ function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = farmInfo.accRewardPerShare; uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this)); if (block.number > farmInfo.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(farmInfo.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(farmInfo.blockReward); accRewardPerShare = accRewardPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); } /** * @notice updates pool information to be up to date to the current block */ function updatePool() public { if (block.number <= farmInfo.lastRewardBlock) { return; } uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this)); if (lpSupply == 0) { farmInfo.lastRewardBlock = block.number < farmInfo.endBlock ? block.number : farmInfo.endBlock; return; } uint256 multiplier = getMultiplier(farmInfo.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(farmInfo.blockReward); farmInfo.accRewardPerShare = farmInfo.accRewardPerShare.add(tokenReward.mul(1e12).div(lpSupply)); farmInfo.lastRewardBlock = block.number < farmInfo.endBlock ? block.number : farmInfo.endBlock; } function deposit( bytes32 _trustedBlockhash, bytes memory _rlpEncodedBlockHeader, bytes memory _rlpEncodedReceipt, bytes memory _receiptPath, bytes memory _receiptWitness, uint8 _transferEventIndex, bytes32 _receiptsRoot ) public { require(_receiptsRoot != bytes32(0), "Invalid receipts root"); require(receipts[_receiptsRoot] == false, "Tx already processed"); receipts[_receiptsRoot] = true; // validations bool proofVerification = EventProof.proveReceiptInclusion( _trustedBlockhash, _rlpEncodedBlockHeader, _rlpEncodedReceipt, _receiptPath, _receiptWitness ); require(proofVerification == true, "Merkle Proof verification failed"); // It is an array consisting of below data points : // contract address on which event is fired // Array : // unique id for event fired --- hash of event signature // from // to // value - transferred value RLPReader.RLPItem[] memory rlpReceiptList = RLPReader.toList(RLPReader.toRlpItem(_rlpEncodedReceipt)); // Here we get all the events fired in the receipt. RLPReader.RLPItem[] memory rlpEventList = RLPReader.toList(rlpReceiptList[EVENT_INDEX_IN_RECEIPT]); RLPReader.RLPItem[] memory transferEventList = RLPReader.toList(rlpEventList[_transferEventIndex]); RLPReader.RLPItem[] memory transferEventParams = RLPReader.toList( transferEventList[TRANSFER_EVENT_PARAMS_INDEX_IN_RECEIPT] ); require( address(RLPReader.toUint(transferEventList[0])) == CRYPTION_VALIDATOR_SHARE_PROXY_CONTRACT, "Stake only using Cryption Network validator" ); // Transfer event signature require(bytes32(transferEventParams[0].toUint()) == TRANSFER_EVENT_SIG , "Invalid event signature"); // `to` adddress must be masterchef contract require( address(RLPReader.toUint(transferEventParams[2])) == address(this), "Shares must be transferred to masterchef" ); _depositInternal( address(transferEventParams[1].toUint()), // `from` address transferEventList[2].toUint() // Value transferred ); } /** * @notice deposit LP token function for msg.sender * @param _amount the total deposit amount */ function _depositInternal(address _user, uint256 _amount) internal { UserInfo storage user = userInfo[_user]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt); _safeRewardTransfer(_user, pending); } if (user.amount == 0 && _amount > 0) { farmInfo.numFarmers++; } // farmInfo.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12); emit Deposit(_user, _amount); } /** * @notice withdraw LP token function for msg.sender * @param _amount the total withdrawable amount */ function withdraw(uint256 _amount) public { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "INSUFFICIENT"); updatePool(); if (user.amount == _amount && _amount > 0) { farmInfo.numFarmers--; } uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt); _safeRewardTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12); farmInfo.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _amount); } /** * @notice emergency functoin to withdraw LP tokens and forego harvest rewards. Important to protect users LP tokens */ function emergencyWithdraw() public { UserInfo storage user = userInfo[msg.sender]; farmInfo.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, user.amount); if (user.amount > 0) { farmInfo.numFarmers--; } user.amount = 0; user.rewardDebt = 0; } /** * @notice Safe reward transfer function, just in case a rounding error causes pool to not have enough reward tokens * @param _to the user address to transfer tokens to * @param _amount the total amount of tokens to transfer */ function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 rewardBal = farmInfo.rewardToken.balanceOf(address(this)); if (_amount > rewardBal) { farmInfo.rewardToken.transfer(_to, rewardBal); } else { farmInfo.rewardToken.transfer(_to, _amount); } } }
deposit LP token function for msg.sender _amount the total deposit amount/
function _depositInternal(address _user, uint256 _amount) internal { UserInfo storage user = userInfo[_user]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt); _safeRewardTransfer(_user, pending); } if (user.amount == 0 && _amount > 0) { farmInfo.numFarmers++; } user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12); emit Deposit(_user, _amount); }
2,571,952
./partial_match/1/0x58DE79366Af408A429d023062768f9252166895C/sources/contracts/ERC20Reflections.sol
withdraw tokens from contract (only owner)
function withdrawTokens( address tokenAddress, address receiverAddress ) external onlyOwner returns (bool success) { IERC20 tokenContract = IERC20(tokenAddress); uint256 amount = tokenContract.balanceOf(address(this)); return tokenContract.transfer(receiverAddress, amount); }
4,342,809
./partial_match/56/0x17566271FEBF4E7e0E72a7D1E3eF2E915d642cCe/sources/StrategyApeLP.sol
Function that has to be called as part of strat migration. It sends all the available funds back to the vault, ready to be migrated to the new strat./
function retireStrat() external { require(msg.sender == vault, "!vault"); IMasterChef(masterchef).emergencyWithdraw(poolId); uint256 pairBal = IERC20(lpPair).balanceOf(address(this)); IERC20(lpPair).transfer(vault, pairBal); }
11,058,818
./full_match/80001/0x5505d54BcC71CE94730B121240b1B68318D2839e/sources/contracts/token/UChildPowerful.sol
Function to stop minting new tokens. NOTE: restricting access to owner only. See {ERC20Mintable-finishMinting}./ onlyOwner
function _finishMinting() internal virtual override(PowerfulERC20Upgradeable, ERC20MintableUpgradeable) { super._finishMinting(); }
5,653,774
./full_match/97/0x5fa6d524b66f9462f5F2BC6115b0A732748A13D1/sources/project_/contracts/MoedaSocial.sol
Só pode ser chamada se não for zeroVerifica o intervalo de tempo exigidorequire(block.timestamp > nextMint[to], "You cannot mint twice in a row");retorna trueretorna o saldo remanescente permitidoallowance(_owner, from);_transfer(from, to, valor);Atenção: no solidity o timestamp é em segundosLibera a trava de mint para o administrador (não mais)nextMint[to] = block.timestamp + _mintDelay;if(msg.sender != _owner) nextMint[msg.sender] = block.timestamp + _mintDelay;
function transferMoeda(address from, address to, uint64 valor) public restricted { require(_mintAmount > 0, "Minting is not enabled"); approve(from, valor); transferFrom(from, to, valor); }
3,277,586
./partial_match/56/0x2b25a0FfFe14D42279658EF199aE443d236e09F9/sources/GamixToken.sol
save gas UPDATE: Let's not destroy the contract here Just transfer the balance to the admin
function endSale() public isOwner { require(transfer(owner, balanceOf[address(this)])); owner.transfer(address(this).balance); _ended = true; }
11,340,241
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "@darwinia/contracts-utils/contracts/ECDSA.sol"; /** * @title Manages a set of guards and a threshold to double-check BEEFY commitment * @dev Stores the guards and a threshold * @author echo */ contract GuardRegistry { event AddedGuard(address guard); event RemovedGuard(address guard); event ChangedThreshold(uint256 threshold); // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 internal constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "ChangeGuard(bytes32 network,bytes4 sig,bytes params,uint256 nonce)" // ); bytes32 internal constant GUARD_TYPEHASH = 0x20823b509c0ff3e2ea0853237833f25b5c32c94d52327fd569cf245995a8206b; address internal constant SENTINEL_GUARDS = address(0x1); /** * @dev NETWORK Source chain network identifier ('Crab', 'Darwinia', 'Pangolin') */ bytes32 public immutable NETWORK; /** * @dev Nonce to prevent replay of update operations */ uint256 public nonce; /** * @dev Store all guards in the linked list */ mapping(address => address) internal guards; /** * @dev Count of all guards */ uint256 internal guardCount; /** * @dev Number of required confirmations for update operations */ uint256 internal threshold; /** * @dev Sets initial storage of contract. * @param _network source chain network name * @param _guards List of Safe guards. * @param _threshold Number of required confirmations for check commitment or change guards. */ constructor(bytes32 _network, address[] memory _guards, uint256 _threshold) public { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "Guard: Guards have already been setup"); // Validate that threshold is smaller than number of added guards. require(_threshold <= _guards.length, "Guard: Threshold cannot exceed guard count"); // There has to be at least one Safe guard. require(_threshold >= 1, "Guard: Threshold needs to be greater than 0"); // Initializing Safe guards. address currentGuard = SENTINEL_GUARDS; for (uint256 i = 0; i < _guards.length; i++) { // Guard address cannot be null. address guard = _guards[i]; require(guard != address(0) && guard != SENTINEL_GUARDS && guard != address(this) && currentGuard != guard, "Guard: Invalid guard address provided"); // No duplicate guards allowed. require(guards[guard] == address(0), "Guard: Address is already an guard"); guards[currentGuard] = guard; currentGuard = guard; emit AddedGuard(guard); } guards[currentGuard] = SENTINEL_GUARDS; guardCount = _guards.length; threshold = _threshold; NETWORK = _network; } /** * @dev Allows to add a new guard to the registry and update the threshold at the same time. * This can only be done via multi-sig. * @notice Adds the guard `guard` to the registry and updates the threshold to `_threshold`. * @param guard New guard address. * @param _threshold New threshold. * @param signatures The signatures of the guards which to add new guard and update the `threshold` . */ function addGuardWithThreshold( address guard, uint256 _threshold, bytes[] memory signatures ) public { // Guard address cannot be null, the sentinel or the registry itself. require(guard != address(0) && guard != SENTINEL_GUARDS && guard != address(this), "Guard: Invalid guard address provided"); // No duplicate guards allowed. require(guards[guard] == address(0), "Guard: Address is already an guard"); verifyGuardSignatures(msg.sig, abi.encode(guard, _threshold), signatures); guards[guard] = guards[SENTINEL_GUARDS]; guards[SENTINEL_GUARDS] = guard; guardCount++; emit AddedGuard(guard); // Change threshold if threshold was changed. if (threshold != _threshold) _changeThreshold(_threshold); } /** * @dev Allows to remove an guard from the registry and update the threshold at the same time. * This can only be done via multi-sig. * @notice Removes the guard `guard` from the registry and updates the threshold to `_threshold`. * @param prevGuard Guard that pointed to the guard to be removed in the linked list * @param guard Guard address to be removed. * @param _threshold New threshold. * @param signatures The signatures of the guards which to remove a guard and update the `threshold` . */ function removeGuard( address prevGuard, address guard, uint256 _threshold, bytes[] memory signatures ) public { // Only allow to remove an guard, if threshold can still be reached. require(guardCount - 1 >= _threshold, "Guard: Threshold cannot exceed guard count"); // Validate guard address and check that it corresponds to guard index. require(guard != address(0) && guard != SENTINEL_GUARDS, "Guard: Invalid guard address provided"); require(guards[prevGuard] == guard, "Guard: Invalid prevGuard, guard pair provided"); verifyGuardSignatures(msg.sig, abi.encode(prevGuard, guard, _threshold), signatures); guards[prevGuard] = guards[guard]; guards[guard] = address(0); guardCount--; emit RemovedGuard(guard); // Change threshold if threshold was changed. if (threshold != _threshold) _changeThreshold(_threshold); } /** * @dev Allows to swap/replace a guard from the registry with another address. * This can only be done via multi-sig. * @notice Replaces the guard `oldGuard` in the registry with `newGuard`. * @param prevGuard guard that pointed to the guard to be replaced in the linked list * @param oldGuard guard address to be replaced. * @param newGuard New guard address. * @param signatures The signatures of the guards which to swap/replace a guard and update the `threshold` . */ function swapGuard( address prevGuard, address oldGuard, address newGuard, bytes[] memory signatures ) public { // Guard address cannot be null, the sentinel or the registry itself. require(newGuard != address(0) && newGuard != SENTINEL_GUARDS && newGuard != address(this), "Guard: Invalid guard address provided"); // No duplicate guards allowed. require(guards[newGuard] == address(0), "Guard: Address is already an guard"); // Validate oldGuard address and check that it corresponds to guard index. require(oldGuard != address(0) && oldGuard != SENTINEL_GUARDS, "Guard: Invalid guard address provided"); require(guards[prevGuard] == oldGuard, "Guard: Invalid prevGuard, guard pair provided"); verifyGuardSignatures(msg.sig, abi.encode(prevGuard, oldGuard, newGuard), signatures); guards[newGuard] = guards[oldGuard]; guards[prevGuard] = newGuard; guards[oldGuard] = address(0); emit RemovedGuard(oldGuard); emit AddedGuard(newGuard); } /** * @dev Allows to update the number of required confirmations by guards. * This can only be done via multi-sig. * @notice Changes the threshold of the registry to `_threshold`. * @param _threshold New threshold. * @param signatures The signatures of the guards which to update the `threshold` . */ function changeThreshold(uint256 _threshold, bytes[] memory signatures) public { verifyGuardSignatures(msg.sig, abi.encode(_threshold), signatures); _changeThreshold(_threshold); } function _changeThreshold(uint256 _threshold) internal { // Validate that threshold is smaller than number of owners. require(_threshold <= guardCount, "Guard: Threshold cannot exceed guard count"); // There has to be at least one guard. require(_threshold >= 1, "Guard: Threshold needs to be greater than 0"); threshold = _threshold; emit ChangedThreshold(threshold); } function getThreshold() public view returns (uint256) { return threshold; } function isGuard(address guard) public view returns (bool) { return guard != SENTINEL_GUARDS && guards[guard] != address(0); } /** * @dev Returns array of guards. * @return Array of guards. */ function getGuards() public view returns (address[] memory) { address[] memory array = new address[](guardCount); // populate return array uint256 index = 0; address currentGuard = guards[SENTINEL_GUARDS]; while (currentGuard != SENTINEL_GUARDS) { array[index] = currentGuard; currentGuard = guards[currentGuard]; index++; } return array; } function verifyGuardSignatures( bytes4 methodID, bytes memory params, bytes[] memory signatures ) internal { bytes32 structHash = keccak256( abi.encode( GUARD_TYPEHASH, NETWORK, methodID, params, nonce ) ); checkGuardSignatures(structHash, signatures); nonce++; } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param structHash The struct Hash of the data (could be either a message/commitment hash). * @param signatures Signature data that should be verified. only ECDSA signature. * Signers need to be sorted in ascending order */ function checkGuardSignatures( bytes32 structHash, bytes[] memory signatures ) public view { // Load threshold to avoid multiple storage loads uint256 _threshold = threshold; // Check that a threshold is set require(_threshold > 0, "Guard: Threshold needs to be defined"); bytes32 dataHash = encodeDataHash(structHash); checkNSignatures(dataHash, signatures, _threshold); } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash). * @param signatures Signature data that should be verified. only ECDSA signature. * Signers need to be sorted in ascending order * @param requiredSignatures Amount of required valid signatures. */ function checkNSignatures( bytes32 dataHash, bytes[] memory signatures, uint256 requiredSignatures ) public view { // Check that the provided signature data is not too short require(signatures.length >= requiredSignatures, "GS020"); // There cannot be an owner with address 0. address lastGuard = address(0); address currentGuard; for (uint256 i = 0; i < requiredSignatures; i++) { currentGuard = ECDSA.recover(dataHash, signatures[i]); require(currentGuard > lastGuard && guards[currentGuard] != address(0) && currentGuard != SENTINEL_GUARDS, "Guard: Invalid guard provided"); lastGuard = currentGuard; } } /** * @dev Returns the chain id used by this contract. */ function getChainId() public pure returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } function domainSeparator() public view returns (bytes32) { return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), address(this))); } function encodeDataHash(bytes32 structHash) internal view returns (bytes32) { return keccak256(abi.encodePacked(hex"1901", domainSeparator(), structHash)); } }
Allows to remove an guard from the registry and update the threshold at the same time. This can only be done via multi-sig. Removes the guard `guard` from the registry and updates the threshold to `_threshold`. prevGuard Guard that pointed to the guard to be removed in the linked list guard Guard address to be removed. _threshold New threshold. signatures The signatures of the guards which to remove a guard and update the `threshold` ./ Only allow to remove an guard, if threshold can still be reached. Validate guard address and check that it corresponds to guard index. Change threshold if threshold was changed.
function removeGuard( address prevGuard, address guard, uint256 _threshold, bytes[] memory signatures ) public { require(guardCount - 1 >= _threshold, "Guard: Threshold cannot exceed guard count"); require(guard != address(0) && guard != SENTINEL_GUARDS, "Guard: Invalid guard address provided"); require(guards[prevGuard] == guard, "Guard: Invalid prevGuard, guard pair provided"); verifyGuardSignatures(msg.sig, abi.encode(prevGuard, guard, _threshold), signatures); guards[prevGuard] = guards[guard]; guards[guard] = address(0); guardCount--; emit RemovedGuard(guard); if (threshold != _threshold) _changeThreshold(_threshold); }
5,352,132
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; library Internal_Merkle_Library_Sorted_Hash { // Hashes a and b in the order they are passed function hash_node(bytes32 a, bytes32 b) internal pure returns (bytes32 hash) { assembly { mstore(0x00, a) mstore(0x20, b) hash := keccak256(0x00, 0x40) } } // Hashes a and b in sorted order function hash_pair(bytes32 a, bytes32 b) internal pure returns (bytes32 hash) { hash = a < b ? hash_node(a, b) : hash_node(b, a); } // Counts number of set bits (1's) in 32-bit unsigned integer function bit_count_32(uint32 n) internal pure returns (uint32) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return (((n + (n >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; } // Round 32-bit unsigned integer up to the nearest power of 2 function round_up_to_power_of_2(uint32 n) internal pure returns (uint32) { if (bit_count_32(n) == 1) return n; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return n + 1; } // Get the Element Merkle Root for a tree with just a single bytes element in calldata function get_root_from_one_c(bytes calldata element) internal pure returns (bytes32) { return keccak256(abi.encodePacked(bytes1(0), element)); } // Get the Element Merkle Root for a tree with just a single bytes element in memory function get_root_from_one_m(bytes memory element) internal pure returns (bytes32) { return keccak256(abi.encodePacked(bytes1(0), element)); } // Get the Element Merkle Root for a tree with just a single bytes32 element in calldata function get_root_from_one(bytes32 element) internal pure returns (bytes32) { return keccak256(abi.encodePacked(bytes1(0), element)); } // Get nodes (parent of leafs) from bytes elements in calldata function get_nodes_from_elements_c(bytes[] calldata elements) internal pure returns (bytes32[] memory nodes) { uint256 element_count = elements.length; uint256 node_count = (element_count >> 1) + (element_count & 1); nodes = new bytes32[](node_count); uint256 write_index; uint256 left_index; while (write_index < node_count) { left_index = write_index << 1; if (left_index == element_count - 1) { nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index])); break; } nodes[write_index++] = hash_pair( keccak256(abi.encodePacked(bytes1(0), elements[left_index])), keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1])) ); } } // Get nodes (parent of leafs) from bytes elements in memory function get_nodes_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory nodes) { uint256 element_count = elements.length; uint256 node_count = (element_count >> 1) + (element_count & 1); nodes = new bytes32[](node_count); uint256 write_index; uint256 left_index; while (write_index < node_count) { left_index = write_index << 1; if (left_index == element_count - 1) { nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index])); break; } nodes[write_index++] = hash_pair( keccak256(abi.encodePacked(bytes1(0), elements[left_index])), keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1])) ); } } // Get nodes (parent of leafs) from bytes32 elements in calldata function get_nodes_from_elements_c(bytes32[] calldata elements) internal pure returns (bytes32[] memory nodes) { uint256 element_count = elements.length; uint256 node_count = (element_count >> 1) + (element_count & 1); nodes = new bytes32[](node_count); uint256 write_index; uint256 left_index; while (write_index < node_count) { left_index = write_index << 1; if (left_index == element_count - 1) { nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index])); break; } nodes[write_index++] = hash_pair( keccak256(abi.encodePacked(bytes1(0), elements[left_index])), keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1])) ); } } // Get nodes (parent of leafs) from bytes32 elements in memory function get_nodes_from_elements_m(bytes32[] memory elements) internal pure returns (bytes32[] memory nodes) { uint256 element_count = elements.length; uint256 node_count = (element_count >> 1) + (element_count & 1); nodes = new bytes32[](node_count); uint256 write_index; uint256 left_index; while (write_index < node_count) { left_index = write_index << 1; if (left_index == element_count - 1) { nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index])); break; } nodes[write_index++] = hash_pair( keccak256(abi.encodePacked(bytes1(0), elements[left_index])), keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1])) ); } } // Get the Element Merkle Root given nodes (parent of leafs) function get_root_from_nodes(bytes32[] memory nodes) internal pure returns (bytes32) { uint256 node_count = nodes.length; uint256 write_index; uint256 left_index; while (node_count > 1) { left_index = write_index << 1; if (left_index == node_count - 1) { nodes[write_index] = nodes[left_index]; write_index = 0; node_count = (node_count >> 1) + (node_count & 1); continue; } if (left_index >= node_count) { write_index = 0; node_count = (node_count >> 1) + (node_count & 1); continue; } nodes[write_index++] = hash_pair(nodes[left_index], nodes[left_index + 1]); } return nodes[0]; } // Get the Element Merkle Root for a tree with several bytes elements in calldata function get_root_from_many_c(bytes[] calldata elements) internal pure returns (bytes32) { return get_root_from_nodes(get_nodes_from_elements_c(elements)); } // Get the Element Merkle Root for a tree with several bytes elements in memory function get_root_from_many_m(bytes[] memory elements) internal pure returns (bytes32) { return get_root_from_nodes(get_nodes_from_elements_m(elements)); } // Get the Element Merkle Root for a tree with several bytes32 elements in calldata function get_root_from_many_c(bytes32[] calldata elements) internal pure returns (bytes32) { return get_root_from_nodes(get_nodes_from_elements_c(elements)); } // Get the Element Merkle Root for a tree with several bytes32 elements in memory function get_root_from_many_m(bytes32[] memory elements) internal pure returns (bytes32) { return get_root_from_nodes(get_nodes_from_elements_m(elements)); } // get_root_from_size_proof cannot be implemented with sorted hashed pairs // Get the original Element Merkle Root, given an index, a leaf, and a Single Proof function get_root_from_leaf_and_single_proof( uint256 index, bytes32 leaf, bytes32[] calldata proof ) internal pure returns (bytes32) { uint256 proof_index = proof.length - 1; uint256 upper_bound = uint256(proof[0]) - 1; while (proof_index > 0) { if (index != upper_bound || (index & 1 == 1)) { leaf = hash_pair(proof[proof_index], leaf); proof_index -= 1; } index >>= 1; upper_bound >>= 1; } return leaf; } // Get the original Element Merkle Root, given an index, a bytes element in calldata, and a Single Proof function get_root_from_single_proof_c( uint256 index, bytes calldata element, bytes32[] calldata proof ) internal pure returns (bytes32 hash) { hash = keccak256(abi.encodePacked(bytes1(0), element)); hash = get_root_from_leaf_and_single_proof(index, hash, proof); } // Get the original Element Merkle Root, given an index, a bytes element in memory, and a Single Proof function get_root_from_single_proof_m( uint256 index, bytes memory element, bytes32[] calldata proof ) internal pure returns (bytes32 hash) { hash = keccak256(abi.encodePacked(bytes1(0), element)); hash = get_root_from_leaf_and_single_proof(index, hash, proof); } // Get the original Element Merkle Root, given an index, a bytes32 element, and a Single Proof function get_root_from_single_proof( uint256 index, bytes32 element, bytes32[] calldata proof ) internal pure returns (bytes32 hash) { hash = keccak256(abi.encodePacked(bytes1(0), element)); hash = get_root_from_leaf_and_single_proof(index, hash, proof); } // Get the original and updated Element Merkle Root, given an index, a leaf, an update leaf, and a Single Proof function get_roots_from_leaf_and_single_proof_update( uint256 index, bytes32 leaf, bytes32 update_leaf, bytes32[] calldata proof ) internal pure returns (bytes32 scratch, bytes32) { uint256 proof_index = proof.length - 1; uint256 upper_bound = uint256(proof[0]) - 1; while (proof_index > 0) { if ((index != upper_bound) || (index & 1 == 1)) { scratch = proof[proof_index]; proof_index -= 1; leaf = hash_pair(scratch, leaf); update_leaf = hash_pair(scratch, update_leaf); } index >>= 1; upper_bound >>= 1; } return (leaf, update_leaf); } // Get the original and updated Element Merkle Root, // given an index, a bytes element in calldata, a bytes update element in calldata, and a Single Proof function get_roots_from_single_proof_update_c( uint256 index, bytes calldata element, bytes calldata update_element, bytes32[] calldata proof ) internal pure returns (bytes32 hash, bytes32 update_hash) { hash = keccak256(abi.encodePacked(bytes1(0), element)); update_hash = keccak256(abi.encodePacked(bytes1(0), update_element)); return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof); } // Get the original and updated Element Merkle Root, // given an index, a bytes element in calldata, a bytes update element in memory, and a Single Proof function get_roots_from_single_proof_update_m( uint256 index, bytes calldata element, bytes memory update_element, bytes32[] calldata proof ) internal pure returns (bytes32 hash, bytes32 update_hash) { hash = keccak256(abi.encodePacked(bytes1(0), element)); update_hash = keccak256(abi.encodePacked(bytes1(0), update_element)); return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof); } // Get the original and updated Element Merkle Root, given an index, a bytes32 element, a bytes32 update element, and a Single Proof function get_roots_from_single_proof_update( uint256 index, bytes32 element, bytes32 update_element, bytes32[] calldata proof ) internal pure returns (bytes32 hash, bytes32 update_hash) { hash = keccak256(abi.encodePacked(bytes1(0), element)); update_hash = keccak256(abi.encodePacked(bytes1(0), update_element)); return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof); } // get_indices_from_multi_proof cannot be implemented with sorted hashed pairs // Get leafs from bytes elements in calldata, in reverse order function get_reversed_leafs_from_elements_c(bytes[] calldata elements) internal pure returns (bytes32[] memory leafs) { uint256 element_count = elements.length; leafs = new bytes32[](element_count); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); write_index += 1; read_index -= 1; } } // Get leafs from bytes elements in memory, in reverse order function get_reversed_leafs_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory leafs) { uint256 element_count = elements.length; leafs = new bytes32[](element_count); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); write_index += 1; read_index -= 1; } } // Get leafs from bytes32 elements in calldata, in reverse order function get_reversed_leafs_from_elements_c(bytes32[] calldata elements) internal pure returns (bytes32[] memory leafs) { uint256 element_count = elements.length; leafs = new bytes32[](element_count); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); write_index += 1; read_index -= 1; } } // Get leafs from bytes32 elements in memory, in reverse order function get_reversed_leafs_from_elements_m(bytes32[] memory elements) internal pure returns (bytes32[] memory leafs) { uint256 element_count = elements.length; leafs = new bytes32[](element_count); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); write_index += 1; read_index -= 1; } } // Get the original Element Merkle Root, given leafs and an Existence Multi Proof function get_root_from_leafs_and_multi_proof(bytes32[] memory leafs, bytes32[] calldata proof) internal pure returns (bytes32 right) { uint256 leaf_count = leafs.length; uint256 read_index; uint256 write_index; uint256 proof_index = 3; bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001; bytes32 flags = proof[1]; bytes32 skips = proof[2]; while (true) { if (skips & bit_check == bit_check) { if (flags & bit_check == bit_check) return leafs[(write_index == 0 ? leaf_count : write_index) - 1]; leafs[write_index] = leafs[read_index]; read_index = (read_index + 1) % leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; continue; } right = (flags & bit_check == bit_check) ? leafs[read_index++] : proof[proof_index++]; read_index %= leaf_count; leafs[write_index] = hash_pair(right, leafs[read_index]); read_index = (read_index + 1) % leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; } } // Get the original Element Merkle Root, given bytes elements in calldata and an Existence Multi Proof function get_root_from_multi_proof_c(bytes[] calldata elements, bytes32[] calldata proof) internal pure returns (bytes32) { return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof); } // Get the original Element Merkle Root, given bytes elements in memory and an Existence Multi Proof function get_root_from_multi_proof_m(bytes[] memory elements, bytes32[] calldata proof) internal pure returns (bytes32) { return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_m(elements), proof); } // Get the original Element Merkle Root, given bytes32 elements in calldata and an Existence Multi Proof function get_root_from_multi_proof_c(bytes32[] calldata elements, bytes32[] calldata proof) internal pure returns (bytes32) { return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof); } // Get the original Element Merkle Root, given bytes32 elements in memory and an Existence Multi Proof function get_root_from_multi_proof_m(bytes32[] memory elements, bytes32[] calldata proof) internal pure returns (bytes32) { return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_m(elements), proof); } // Get current and update leafs from current bytes elements in calldata and update bytes elements in calldata, in reverse order function get_reversed_leafs_from_current_and_update_elements_c( bytes[] calldata elements, bytes[] calldata update_elements ) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) { uint256 element_count = elements.length; require(update_elements.length == element_count, "LENGTH_MISMATCH"); leafs = new bytes32[](element_count); update_leafs = new bytes32[](element_count); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index])); write_index += 1; read_index -= 1; } } // Get current and update leafs from current bytes elements in calldata and update bytes elements in memory, in reverse order function get_reversed_leafs_from_current_and_update_elements_m( bytes[] calldata elements, bytes[] memory update_elements ) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) { uint256 element_count = elements.length; require(update_elements.length == element_count, "LENGTH_MISMATCH"); leafs = new bytes32[](element_count); update_leafs = new bytes32[](element_count); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index])); write_index += 1; read_index -= 1; } } // Get current and update leafs from current bytes32 elements in calldata and update bytes32 elements in calldata, in reverse order function get_reversed_leafs_from_current_and_update_elements_c( bytes32[] calldata elements, bytes32[] calldata update_elements ) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) { uint256 element_count = elements.length; require(update_elements.length == element_count, "LENGTH_MISMATCH"); leafs = new bytes32[](element_count); update_leafs = new bytes32[](element_count); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index])); write_index += 1; read_index -= 1; } } // Get current and update leafs from current bytes32 elements in calldata and update bytes32 elements in memory, in reverse order function get_reversed_leafs_from_current_and_update_elements_m( bytes32[] calldata elements, bytes32[] memory update_elements ) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) { uint256 element_count = elements.length; require(update_elements.length == element_count, "LENGTH_MISMATCH"); leafs = new bytes32[](element_count); update_leafs = new bytes32[](element_count); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index])); write_index += 1; read_index -= 1; } } // Get the original and updated Element Merkle Root, given leafs, update leafs, and an Existence Multi Proof function get_roots_from_leafs_and_multi_proof_update( bytes32[] memory leafs, bytes32[] memory update_leafs, bytes32[] calldata proof ) internal pure returns (bytes32 flags, bytes32 skips) { uint256 leaf_count = update_leafs.length; uint256 read_index; uint256 write_index; uint256 proof_index = 3; bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001; flags = proof[1]; skips = proof[2]; bytes32 scratch; uint256 scratch_2; while (true) { if (skips & bit_check == bit_check) { if (flags & bit_check == bit_check) { read_index = (write_index == 0 ? leaf_count : write_index) - 1; return (leafs[read_index], update_leafs[read_index]); } leafs[write_index] = leafs[read_index]; update_leafs[write_index] = update_leafs[read_index]; read_index = (read_index + 1) % leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; continue; } if (flags & bit_check == bit_check) { scratch_2 = (read_index + 1) % leaf_count; leafs[write_index] = hash_pair(leafs[read_index], leafs[scratch_2]); update_leafs[write_index] = hash_pair(update_leafs[read_index], update_leafs[scratch_2]); read_index += 2; } else { scratch = proof[proof_index++]; leafs[write_index] = hash_pair(scratch, leafs[read_index]); update_leafs[write_index] = hash_pair(scratch, update_leafs[read_index]); read_index += 1; } read_index %= leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; } } // Get the original and updated Element Merkle Root, // given bytes elements in calldata, bytes update elements in calldata, and an Existence Multi Proof function get_roots_from_multi_proof_update_c( bytes[] calldata elements, bytes[] calldata update_elements, bytes32[] calldata proof ) internal pure returns (bytes32, bytes32) { (bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_c( elements, update_elements ); return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof); } // Get the original and updated Element Merkle Root, // given bytes elements in calldata, bytes update elements in memory, and an Existence Multi Proof function get_roots_from_multi_proof_update_m( bytes[] calldata elements, bytes[] memory update_elements, bytes32[] calldata proof ) internal pure returns (bytes32, bytes32) { (bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_m( elements, update_elements ); return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof); } // Get the original and updated Element Merkle Root, // given bytes32 elements in calldata, bytes32 update elements in calldata, and an Existence Multi Proof function get_roots_from_multi_proof_update_c( bytes32[] calldata elements, bytes32[] calldata update_elements, bytes32[] calldata proof ) internal pure returns (bytes32, bytes32) { (bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_c( elements, update_elements ); return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof); } // Get the original and updated Element Merkle Root, // given bytes32 elements in calldata, bytes32 update elements in memory, and an Existence Multi Proof function get_roots_from_multi_proof_update_m( bytes32[] calldata elements, bytes32[] memory update_elements, bytes32[] calldata proof ) internal pure returns (bytes32, bytes32) { (bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_m( elements, update_elements ); return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof); } // Get the original Element Merkle Root, given an Append Proof function get_root_from_append_proof(bytes32[] calldata proof) internal pure returns (bytes32 hash) { uint256 proof_index = bit_count_32(uint32(uint256(proof[0]))); hash = proof[proof_index]; while (proof_index > 1) { proof_index -= 1; hash = hash_pair(proof[proof_index], hash); } } // Get the original and updated Element Merkle Root, given append leaf and an Append Proof function get_roots_from_leaf_and_append_proof_single_append(bytes32 append_leaf, bytes32[] calldata proof) internal pure returns (bytes32 hash, bytes32 scratch) { uint256 proof_index = bit_count_32(uint32(uint256(proof[0]))); hash = proof[proof_index]; append_leaf = hash_pair(hash, append_leaf); while (proof_index > 1) { proof_index -= 1; scratch = proof[proof_index]; append_leaf = hash_pair(scratch, append_leaf); hash = hash_pair(scratch, hash); } return (hash, append_leaf); } // Get the original and updated Element Merkle Root, given a bytes append element in calldata and an Append Proof function get_roots_from_append_proof_single_append_c(bytes calldata append_element, bytes32[] calldata proof) internal pure returns (bytes32 append_leaf, bytes32) { append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element)); return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof); } // Get the original and updated Element Merkle Root, given a bytes append element in memory and an Append Proof function get_roots_from_append_proof_single_append_m(bytes memory append_element, bytes32[] calldata proof) internal pure returns (bytes32 append_leaf, bytes32) { append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element)); return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof); } // Get the original and updated Element Merkle Root, given a bytes32 append element in calldata and an Append Proof function get_roots_from_append_proof_single_append(bytes32 append_element, bytes32[] calldata proof) internal pure returns (bytes32 append_leaf, bytes32) { append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element)); return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof); } // Get leafs from bytes elements in calldata function get_leafs_from_elements_c(bytes[] calldata elements) internal pure returns (bytes32[] memory leafs) { uint256 element_count = elements.length; leafs = new bytes32[](element_count); while (element_count > 0) { element_count -= 1; leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count])); } } // Get leafs from bytes elements in memory function get_leafs_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory leafs) { uint256 element_count = elements.length; leafs = new bytes32[](element_count); while (element_count > 0) { element_count -= 1; leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count])); } } // Get leafs from bytes32 elements in calldata function get_leafs_from_elements_c(bytes32[] calldata elements) internal pure returns (bytes32[] memory leafs) { uint256 element_count = elements.length; leafs = new bytes32[](element_count); while (element_count > 0) { element_count -= 1; leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count])); } } // Get leafs from bytes32 elements in memory function get_leafs_from_elements_m(bytes32[] memory elements) internal pure returns (bytes32[] memory leafs) { uint256 element_count = elements.length; leafs = new bytes32[](element_count); while (element_count > 0) { element_count -= 1; leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count])); } } // Get the original and updated Element Merkle Root, given append leafs and an Append Proof function get_roots_from_leafs_and_append_proof_multi_append(bytes32[] memory append_leafs, bytes32[] calldata proof) internal pure returns (bytes32 hash, bytes32) { uint256 leaf_count = append_leafs.length; uint256 write_index; uint256 read_index; uint256 offset = uint256(proof[0]); uint256 index = offset; // reuse leaf_count variable as upper_bound, since leaf_count no longer needed leaf_count += offset; leaf_count -= 1; uint256 proof_index = bit_count_32(uint32(offset)); hash = proof[proof_index]; while (leaf_count > 0) { if ((write_index == 0) && (index & 1 == 1)) { append_leafs[0] = hash_pair(proof[proof_index], append_leafs[read_index]); proof_index -= 1; read_index += 1; if (proof_index > 0) { hash = hash_pair(proof[proof_index], hash); } write_index = 1; index += 1; } else if (index < leaf_count) { append_leafs[write_index++] = hash_pair(append_leafs[read_index++], append_leafs[read_index]); read_index += 1; index += 2; } if (index >= leaf_count) { if (index == leaf_count) { append_leafs[write_index] = append_leafs[read_index]; } read_index = 0; write_index = 0; leaf_count >>= 1; offset >>= 1; index = offset; } } return (hash, append_leafs[0]); } // Get the original and updated Element Merkle Root, given bytes append elements in calldata and an Append Proof function get_roots_from_append_proof_multi_append_c(bytes[] calldata append_elements, bytes32[] calldata proof) internal pure returns (bytes32, bytes32) { return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof); } // Get the original and updated Element Merkle Root, given bytes append elements in memory and an Append Proof function get_roots_from_append_proof_multi_append_m(bytes[] memory append_elements, bytes32[] calldata proof) internal pure returns (bytes32, bytes32) { return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof); } // Get the original and updated Element Merkle Root, given bytes32 append elements in calldata and an Append Proof function get_roots_from_append_proof_multi_append_c(bytes32[] calldata append_elements, bytes32[] calldata proof) internal pure returns (bytes32, bytes32) { return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof); } // Get the original and updated Element Merkle Root, given bytes32 append elements in memory and an Append Proof function get_roots_from_append_proof_multi_append_m(bytes32[] memory append_elements, bytes32[] calldata proof) internal pure returns (bytes32, bytes32) { return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof); } // Get the updated Element Merkle Root, given an append leaf and an Append Proof function get_new_root_from_leafs_and_append_proof_single_append(bytes32 append_leaf, bytes32[] memory proof) internal pure returns (bytes32 append_hash) { uint256 proof_index = bit_count_32(uint32(uint256(proof[0]))); append_hash = hash_pair(proof[proof_index], append_leaf); while (proof_index > 1) { proof_index -= 1; append_hash = hash_pair(proof[proof_index], append_hash); } } // Get the updated Element Merkle Root, given a bytes append elements in calldata and an Append Proof function get_new_root_from_append_proof_single_append_c(bytes calldata append_element, bytes32[] memory proof) internal pure returns (bytes32 append_leaf) { append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element)); return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof); } // Get the updated Element Merkle Root, given a bytes append elements in memory and an Append Proof function get_new_root_from_append_proof_single_append_m(bytes memory append_element, bytes32[] memory proof) internal pure returns (bytes32 append_leaf) { append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element)); return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof); } // Get the updated Element Merkle Root, given a bytes32 append elements in calldata and an Append Proof function get_new_root_from_append_proof_single_append(bytes32 append_element, bytes32[] memory proof) internal pure returns (bytes32 append_leaf) { append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element)); return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof); } // Get the updated Element Merkle Root, given append leafs and an Append Proof function get_new_root_from_leafs_and_append_proof_multi_append(bytes32[] memory append_leafs, bytes32[] memory proof) internal pure returns (bytes32) { uint256 leaf_count = append_leafs.length; uint256 write_index; uint256 read_index; uint256 offset = uint256(proof[0]); uint256 index = offset; // reuse leaf_count variable as upper_bound, since leaf_count no longer needed leaf_count += offset; leaf_count -= 1; uint256 proof_index = proof.length - 1; while (leaf_count > 0) { if ((write_index == 0) && (index & 1 == 1)) { append_leafs[0] = hash_pair(proof[proof_index], append_leafs[read_index]); read_index += 1; proof_index -= 1; write_index = 1; index += 1; } else if (index < leaf_count) { append_leafs[write_index++] = hash_pair(append_leafs[read_index++], append_leafs[read_index++]); index += 2; } if (index >= leaf_count) { if (index == leaf_count) { append_leafs[write_index] = append_leafs[read_index]; } read_index = 0; write_index = 0; leaf_count >>= 1; offset >>= 1; index = offset; } } return append_leafs[0]; } // Get the updated Element Merkle Root, given bytes append elements in calldata and an Append Proof function get_new_root_from_append_proof_multi_append_c(bytes[] calldata append_elements, bytes32[] memory proof) internal pure returns (bytes32) { return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof); } // Get the updated Element Merkle Root, given bytes append elements in memory and an Append Proof function get_new_root_from_append_proof_multi_append_m(bytes[] memory append_elements, bytes32[] memory proof) internal pure returns (bytes32) { return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof); } // Get the updated Element Merkle Root, given bytes32 append elements in calldata and an Append Proof function get_new_root_from_append_proof_multi_append_c(bytes32[] calldata append_elements, bytes32[] memory proof) internal pure returns (bytes32) { return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof); } // Get the updated Element Merkle Root, given bytes32 append elements in memory and an Append Proof function get_new_root_from_append_proof_multi_append_m(bytes32[] memory append_elements, bytes32[] memory proof) internal pure returns (bytes32) { return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof); } // Get the original Element Merkle Root and derive Append Proof, given an index, an append leaf, and a Single Proof function get_append_proof_from_leaf_and_single_proof( uint256 index, bytes32 leaf, bytes32[] calldata proof ) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) { uint256 proof_index = proof.length - 1; uint256 append_node_index = uint256(proof[0]); uint256 upper_bound = append_node_index - 1; uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1; append_proof = new bytes32[](append_proof_index); append_proof[0] = bytes32(append_node_index); bytes32 scratch; while (proof_index > 0) { if (index != upper_bound || (index & 1 == 1)) { scratch = proof[proof_index]; leaf = hash_pair(scratch, leaf); if (append_node_index & 1 == 1) { append_proof_index -= 1; append_proof[append_proof_index] = scratch; append_hash = hash_pair(scratch, append_hash); } proof_index -= 1; } else if (append_node_index & 1 == 1) { append_proof_index -= 1; append_proof[append_proof_index] = leaf; append_hash = leaf; } index >>= 1; upper_bound >>= 1; append_node_index >>= 1; } require(append_proof_index == 2 || append_hash == leaf, "INVALID_PROOF"); if (append_proof_index == 2) { append_proof[1] = leaf; } } // Get the original Element Merkle Root and derive Append Proof, given an index, a bytes element in calldata, and a Single Proof function get_append_proof_from_single_proof( uint256 index, bytes calldata element, bytes32[] calldata proof ) internal pure returns (bytes32 leaf, bytes32[] memory) { leaf = keccak256(abi.encodePacked(bytes1(0), element)); return get_append_proof_from_leaf_and_single_proof(index, leaf, proof); } // Get the original Element Merkle Root and derive Append Proof, given an index, a bytes32 element, and a Single Proof function get_append_proof_from_single_proof( uint256 index, bytes32 element, bytes32[] calldata proof ) internal pure returns (bytes32 leaf, bytes32[] memory) { leaf = keccak256(abi.encodePacked(bytes1(0), element)); return get_append_proof_from_leaf_and_single_proof(index, leaf, proof); } // Get the original Element Merkle Root and derive Append Proof, given an index, a leaf, an update leaf, and a Single Proof function get_append_proof_from_leaf_and_single_proof_update( uint256 index, bytes32 leaf, bytes32 update_leaf, bytes32[] calldata proof ) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) { uint256 proof_index = proof.length - 1; uint256 append_node_index = uint256(proof[0]); uint256 upper_bound = append_node_index - 1; uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1; append_proof = new bytes32[](append_proof_index); append_proof[0] = bytes32(append_node_index); bytes32 scratch; while (proof_index > 0) { if (index != upper_bound || (index & 1 == 1)) { scratch = proof[proof_index]; leaf = hash_pair(scratch, leaf); update_leaf = hash_pair(scratch, update_leaf); if (append_node_index & 1 == 1) { append_proof_index -= 1; append_proof[append_proof_index] = scratch; append_hash = hash_pair(scratch, append_hash); } proof_index -= 1; } else if (append_node_index & 1 == 1) { append_proof_index -= 1; append_proof[append_proof_index] = update_leaf; append_hash = leaf; } index >>= 1; upper_bound >>= 1; append_node_index >>= 1; } require(append_proof_index == 2 || append_hash == leaf, "INVALID_PROOF"); if (append_proof_index == 2) { append_proof[1] = update_leaf; } } // Get the original Element Merkle Root and derive Append Proof, // given an index, a bytes element in calldata, a bytes update element in calldata, and a Single Proof function get_append_proof_from_single_proof_update_c( uint256 index, bytes calldata element, bytes calldata update_element, bytes32[] calldata proof ) internal pure returns (bytes32 leaf, bytes32[] memory) { leaf = keccak256(abi.encodePacked(bytes1(0), element)); bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element)); return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof); } // Get the original Element Merkle Root and derive Append Proof, // given an index, a bytes element in calldata, a bytes update element in memory, and a Single Proof function get_append_proof_from_single_proof_update_m( uint256 index, bytes calldata element, bytes memory update_element, bytes32[] calldata proof ) internal pure returns (bytes32 leaf, bytes32[] memory) { leaf = keccak256(abi.encodePacked(bytes1(0), element)); bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element)); return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof); } // Get the original Element Merkle Root and derive Append Proof, // given an index, a bytes32 element, a bytes32 update element, and a Single Proof function get_append_proof_from_single_proof_update( uint256 index, bytes32 element, bytes32 update_element, bytes32[] calldata proof ) internal pure returns (bytes32 leaf, bytes32[] memory) { leaf = keccak256(abi.encodePacked(bytes1(0), element)); bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element)); return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof); } // Hashes leaf at read index and next index (circular) to write index function hash_within_leafs( bytes32[] memory leafs, uint256 write_index, uint256 read_index, uint256 leaf_count ) internal pure { leafs[write_index] = hash_pair(leafs[read_index], leafs[(read_index + 1) % leaf_count]); } // Hashes value with leaf at read index to write index function hash_with_leafs( bytes32[] memory leafs, bytes32 value, uint256 write_index, uint256 read_index ) internal pure { leafs[write_index] = hash_pair(value, leafs[read_index]); } // Get the original Element Merkle Root and derive Append Proof, given leafs and an Existence Multi Proof function get_append_proof_from_leafs_and_multi_proof(bytes32[] memory leafs, bytes32[] calldata proof) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) { uint256 leaf_count = leafs.length; uint256 read_index; uint256 write_index; uint256 proof_index = 3; uint256 append_node_index = uint256(proof[0]); uint256 append_proof_index = uint256(bit_count_32(uint32(append_node_index))) + 1; append_proof = new bytes32[](append_proof_index); append_proof[0] = bytes32(append_node_index); bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001; bytes32 flags = proof[1]; bytes32 skips = proof[2]; uint256 read_index_of_append_node; while (true) { if (skips & bit_check == bit_check) { if (flags & bit_check == bit_check) { read_index = (write_index == 0 ? leaf_count : write_index) - 1; // reuse flags as scratch variable flags = leafs[read_index]; require(append_proof_index == 2 || append_hash == flags, "INVALID_PROOF"); if (append_proof_index == 2) { append_proof[1] = flags; } return (append_hash, append_proof); } if (append_node_index & 1 == 1) { append_proof_index -= 1; append_hash = leafs[read_index]; // TODO scratch this leafs[read_index] above append_proof[append_proof_index] = leafs[read_index]; } read_index_of_append_node = write_index; append_node_index >>= 1; leafs[write_index] = leafs[read_index]; read_index = (read_index + 1) % leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; continue; } if (read_index_of_append_node == read_index) { if (append_node_index & 1 == 1) { append_proof_index -= 1; if (flags & bit_check == bit_check) { // reuse read_index_of_append_node as temporary scratch variable read_index_of_append_node = (read_index + 1) % leaf_count; append_hash = hash_pair(leafs[read_index_of_append_node], append_hash); append_proof[append_proof_index] = leafs[read_index_of_append_node]; } else { append_hash = hash_pair(proof[proof_index], append_hash); append_proof[append_proof_index] = proof[proof_index]; } } read_index_of_append_node = write_index; append_node_index >>= 1; } if (flags & bit_check == bit_check) { hash_within_leafs(leafs, write_index, read_index, leaf_count); read_index += 2; } else { hash_with_leafs(leafs, proof[proof_index], write_index, read_index); proof_index += 1; read_index += 1; } read_index %= leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; } } // Get the original Element Merkle Root and derive Append Proof, given bytes elements in calldata and an Existence Multi Proof function get_append_proof_from_multi_proof(bytes[] calldata elements, bytes32[] calldata proof) internal pure returns (bytes32, bytes32[] memory) { return get_append_proof_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof); } // Get the original Element Merkle Root and derive Append Proof, given bytes32 elements in calldata and an Existence Multi Proof function get_append_proof_from_multi_proof(bytes32[] calldata elements, bytes32[] calldata proof) internal pure returns (bytes32, bytes32[] memory) { return get_append_proof_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof); } // Get combined current and update leafs from current bytes elements in calldata and update bytes elements in calldata, in reverse order function get_reversed_combined_leafs_from_current_and_update_elements_c( bytes[] calldata elements, bytes[] calldata update_elements ) internal pure returns (bytes32[] memory combined_leafs) { uint256 element_count = elements.length; require(update_elements.length == element_count, "LENGTH_MISMATCH"); combined_leafs = new bytes32[](element_count << 1); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index])); write_index += 1; read_index -= 1; } } // Get combined current and update leafs from current bytes elements in calldata and update bytes elements in memory, in reverse order function get_reversed_combined_leafs_from_current_and_update_elements_m( bytes[] calldata elements, bytes[] memory update_elements ) internal pure returns (bytes32[] memory combined_leafs) { uint256 element_count = elements.length; require(update_elements.length == element_count, "LENGTH_MISMATCH"); combined_leafs = new bytes32[](element_count << 1); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index])); write_index += 1; read_index -= 1; } } // Get combined current and update leafs from current bytes32 elements in calldata and update bytes32 elements in calldata, in reverse order function get_reversed_combined_leafs_from_current_and_update_elements_c( bytes32[] calldata elements, bytes32[] calldata update_elements ) internal pure returns (bytes32[] memory combined_leafs) { uint256 element_count = elements.length; require(update_elements.length == element_count, "LENGTH_MISMATCH"); combined_leafs = new bytes32[](element_count << 1); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index])); write_index += 1; read_index -= 1; } } // Get combined current and update leafs from current bytes32 elements in calldata and update bytes32 elements in memory, in reverse order function get_reversed_combined_leafs_from_current_and_update_elements_m( bytes32[] calldata elements, bytes32[] memory update_elements ) internal pure returns (bytes32[] memory combined_leafs) { uint256 element_count = elements.length; require(update_elements.length == element_count, "LENGTH_MISMATCH"); combined_leafs = new bytes32[](element_count << 1); uint256 read_index = element_count - 1; uint256 write_index; while (write_index < element_count) { combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index])); combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index])); write_index += 1; read_index -= 1; } } // Copy leaf and update leaf at read indices and to write indices function copy_within_combined_leafs( bytes32[] memory combined_leafs, uint256 write_index, uint256 read_index, uint256 leaf_count ) internal pure { combined_leafs[write_index] = combined_leafs[read_index]; combined_leafs[leaf_count + write_index] = combined_leafs[leaf_count + read_index]; } // Hashes leaf and update leaf at read indices and next indices (circular) to write indices function hash_within_combined_leafs( bytes32[] memory combined_leafs, uint256 write_index, uint256 read_index, uint256 leaf_count ) internal pure { uint256 scratch = (read_index + 1) % leaf_count; combined_leafs[write_index] = hash_pair(combined_leafs[read_index], combined_leafs[scratch]); combined_leafs[leaf_count + write_index] = hash_pair( combined_leafs[leaf_count + read_index], combined_leafs[leaf_count + scratch] ); } // Hashes value with leaf and update leaf at read indices to write indices function hash_with_combined_leafs( bytes32[] memory combined_leafs, bytes32 value, uint256 write_index, uint256 read_index, uint256 leaf_count ) internal pure { combined_leafs[write_index] = hash_pair(value, combined_leafs[read_index]); combined_leafs[leaf_count + write_index] = hash_pair(value, combined_leafs[leaf_count + read_index]); } // Get the original Element Merkle Root and derive Append Proof, given combined leafs and update leafs and an Existence Multi Proof function get_append_proof_from_leafs_and_multi_proof_update(bytes32[] memory combined_leafs, bytes32[] calldata proof) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) { uint256 leaf_count = combined_leafs.length >> 1; uint256 read_index; uint256 write_index; uint256 read_index_of_append_node; uint256 proof_index = 3; uint256 append_node_index = uint256(proof[0]); uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1; append_proof = new bytes32[](append_proof_index); append_proof[0] = bytes32(append_node_index); bytes32 flags = proof[1]; bytes32 skips = proof[2]; bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001; while (true) { if (skips & bit_check == bit_check) { if (flags & bit_check == bit_check) { read_index = (write_index == 0 ? leaf_count : write_index) - 1; // reuse flags as scratch variable flags = combined_leafs[read_index]; require(append_proof_index == 2 || append_hash == flags, "INVALID_PROOF"); if (append_proof_index == 2) { append_proof[1] = combined_leafs[leaf_count + read_index]; } return (flags, append_proof); } if (append_node_index & 1 == 1) { append_proof_index -= 1; append_hash = combined_leafs[read_index]; append_proof[append_proof_index] = combined_leafs[leaf_count + read_index]; } read_index_of_append_node = write_index; append_node_index >>= 1; combined_leafs[write_index] = combined_leafs[read_index]; combined_leafs[leaf_count + write_index] = combined_leafs[leaf_count + read_index]; read_index = (read_index + 1) % leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; continue; } if (read_index_of_append_node == read_index) { if (append_node_index & 1 == 1) { append_proof_index -= 1; if (flags & bit_check == bit_check) { // use read_index_of_append_node as temporary scratch read_index_of_append_node = (read_index + 1) % leaf_count; append_hash = hash_pair(combined_leafs[read_index_of_append_node], append_hash); append_proof[append_proof_index] = combined_leafs[leaf_count + read_index_of_append_node]; } else { append_hash = hash_pair(proof[proof_index], append_hash); append_proof[append_proof_index] = proof[proof_index]; } } read_index_of_append_node = write_index; append_node_index >>= 1; } if (flags & bit_check == bit_check) { hash_within_combined_leafs(combined_leafs, write_index, read_index, leaf_count); read_index += 2; } else { hash_with_combined_leafs(combined_leafs, proof[proof_index], write_index, read_index, leaf_count); proof_index += 1; read_index += 1; } read_index %= leaf_count; write_index = (write_index + 1) % leaf_count; bit_check <<= 1; } } // Get the original Element Merkle Root and derive Append Proof, // given bytes elements in calldata, bytes update elements in calldata, and an Existence Multi Proof function get_append_proof_from_multi_proof_update_c( bytes[] calldata elements, bytes[] calldata update_elements, bytes32[] calldata proof ) internal pure returns (bytes32, bytes32[] memory) { return get_append_proof_from_leafs_and_multi_proof_update( get_reversed_combined_leafs_from_current_and_update_elements_c(elements, update_elements), proof ); } // Get the original Element Merkle Root and derive Append Proof, // given bytes elements in calldata, bytes update elements in memory, and an Existence Multi Proof function get_append_proof_from_multi_proof_update_m( bytes[] calldata elements, bytes[] memory update_elements, bytes32[] calldata proof ) internal pure returns (bytes32, bytes32[] memory) { return get_append_proof_from_leafs_and_multi_proof_update( get_reversed_combined_leafs_from_current_and_update_elements_m(elements, update_elements), proof ); } // Get the original Element Merkle Root and derive Append Proof, // given bytes32 elements in calldata, bytes32 update elements in calldata, and an Existence Multi Proof function get_append_proof_from_multi_proof_update_c( bytes32[] calldata elements, bytes32[] calldata update_elements, bytes32[] calldata proof ) internal pure returns (bytes32, bytes32[] memory) { return get_append_proof_from_leafs_and_multi_proof_update( get_reversed_combined_leafs_from_current_and_update_elements_c(elements, update_elements), proof ); } // Get the original Element Merkle Root and derive Append Proof, // given bytes32 elements in calldata, bytes32 update elements in memory, and an Existence Multi Proof function get_append_proof_from_multi_proof_update_m( bytes32[] calldata elements, bytes32[] memory update_elements, bytes32[] calldata proof ) internal pure returns (bytes32, bytes32[] memory) { return get_append_proof_from_leafs_and_multi_proof_update( get_reversed_combined_leafs_from_current_and_update_elements_m(elements, update_elements), proof ); } // INTERFACE: Check if bytes element in calldata exists at index, given a root and a Single Proof function element_exists_c( bytes32 root, uint256 index, bytes calldata element, bytes32[] calldata proof ) internal pure returns (bool) { return hash_node(proof[0], get_root_from_single_proof_c(index, element, proof)) == root; } // INTERFACE: Check if bytes element in calldata exists at index, given a root and a Single Proof function element_exists_m( bytes32 root, uint256 index, bytes memory element, bytes32[] calldata proof ) internal pure returns (bool) { return hash_node(proof[0], get_root_from_single_proof_m(index, element, proof)) == root; } // INTERFACE: Check if bytes32 element exists at index, given a root and a Single Proof function element_exists( bytes32 root, uint256 index, bytes32 element, bytes32[] calldata proof ) internal pure returns (bool) { return hash_node(proof[0], get_root_from_single_proof(index, element, proof)) == root; } // INTERFACE: Check if bytes elements in calldata exist, given a root and a Single Proof function elements_exist_c( bytes32 root, bytes[] calldata elements, bytes32[] calldata proof ) internal pure returns (bool) { return hash_node(proof[0], get_root_from_multi_proof_c(elements, proof)) == root; } // INTERFACE: Check if bytes elements in memory exist, given a root and a Single Proof function elements_exist_m( bytes32 root, bytes[] memory elements, bytes32[] calldata proof ) internal pure returns (bool) { return hash_node(proof[0], get_root_from_multi_proof_m(elements, proof)) == root; } // INTERFACE: Check if bytes32 elements in calldata exist, given a root and a Single Proof function elements_exist_c( bytes32 root, bytes32[] calldata elements, bytes32[] calldata proof ) internal pure returns (bool) { return hash_node(proof[0], get_root_from_multi_proof_c(elements, proof)) == root; } // INTERFACE: Check if bytes32 elements in memory exist, given a root and a Single Proof function elements_exist_m( bytes32 root, bytes32[] memory elements, bytes32[] calldata proof ) internal pure returns (bool) { return hash_node(proof[0], get_root_from_multi_proof_m(elements, proof)) == root; } // get_indices cannot be implemented with sorted hashed pairs // verify_size_with_proof cannot be implemented with sorted hashed pairs // INTERFACE: Check tree size, given a the Element Merkle Root function verify_size( bytes32 root, uint256 size, bytes32 element_root ) internal pure returns (bool) { if (root == bytes32(0) && size == 0) return true; return hash_node(bytes32(size), element_root) == root; } // INTERFACE: Try to update a bytes element in calldata, given a root, and index, an bytes element in calldata, and a Single Proof function try_update_one_c( bytes32 root, uint256 index, bytes calldata element, bytes calldata update_element, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_single_proof_update_c(index, element, update_element, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(total_element_count, new_element_root); } // INTERFACE: Try to update a bytes element in memory, given a root, and index, an bytes element in calldata, and a Single Proof function try_update_one_m( bytes32 root, uint256 index, bytes calldata element, bytes memory update_element, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_single_proof_update_m(index, element, update_element, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(total_element_count, new_element_root); } // INTERFACE: Try to update a bytes32 element, given a root, and index, an bytes32 element, and a Single Proof function try_update_one( bytes32 root, uint256 index, bytes32 element, bytes32 update_element, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_single_proof_update(index, element, update_element, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(total_element_count, new_element_root); } // INTERFACE: Try to update bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof function try_update_many_c( bytes32 root, bytes[] calldata elements, bytes[] calldata update_elements, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_multi_proof_update_c(elements, update_elements, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(total_element_count, new_element_root); } // INTERFACE: Try to update bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof function try_update_many_m( bytes32 root, bytes[] calldata elements, bytes[] memory update_elements, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_multi_proof_update_m(elements, update_elements, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(total_element_count, new_element_root); } // INTERFACE: Try to update bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof function try_update_many_c( bytes32 root, bytes32[] calldata elements, bytes32[] calldata update_elements, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_multi_proof_update_c(elements, update_elements, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(total_element_count, new_element_root); } // INTERFACE: Try to update bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof function try_update_many_m( bytes32 root, bytes32[] calldata elements, bytes32[] memory update_elements, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_multi_proof_update_m(elements, update_elements, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(total_element_count, new_element_root); } // INTERFACE: Try to append a bytes element in calldata, given a root and an Append Proof function try_append_one_c( bytes32 root, bytes calldata append_element, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE"); if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one_c(append_element)); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_append_proof_single_append_c(append_element, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root); } // INTERFACE: Try to append a bytes element in memory, given a root and an Append Proof function try_append_one_m( bytes32 root, bytes memory append_element, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE"); if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one_m(append_element)); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_append_proof_single_append_m(append_element, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root); } // INTERFACE: Try to append a bytes32 element, given a root and an Append Proof function try_append_one( bytes32 root, bytes32 append_element, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE"); if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one(append_element)); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_append_proof_single_append(append_element, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root); } // INTERFACE: Try to append bytes elements in calldata, given a root and an Append Proof function try_append_many_c( bytes32 root, bytes[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE"); if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_c(append_elements)); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_c(append_elements, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root); } // INTERFACE: Try to append bytes elements in memory, given a root and an Append Proof function try_append_many_m( bytes32 root, bytes[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE"); if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_m(append_elements)); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_m(append_elements, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root); } // INTERFACE: Try to append bytes32 elements in calldata, given a root and an Append Proof function try_append_many_c( bytes32 root, bytes32[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE"); if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_c(append_elements)); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_c(append_elements, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root); } // INTERFACE: Try to append bytes32 elements in memory, given a root and an Append Proof function try_append_many_m( bytes32 root, bytes32[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 new_element_root) { bytes32 total_element_count = proof[0]; require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE"); if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_m(append_elements)); bytes32 old_element_root; (old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_m(append_elements, proof); require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF"); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root); } // INTERFACE: Try to append a bytes element in calldata, given a root, an index, a bytes element in calldata, and a Single Proof function try_append_one_using_one_c( bytes32 root, uint256 index, bytes calldata element, bytes calldata append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to append a bytes element in memory, given a root, an index, a bytes element in calldata, and a Single Proof function try_append_one_using_one_m( bytes32 root, uint256 index, bytes calldata element, bytes memory append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to append a bytes32 element, given a root, an index, a bytes32 element, and a Single Proof function try_append_one_using_one( bytes32 root, uint256 index, bytes32 element, bytes32 append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to append bytes elements in calldata, given a root, an index, a bytes element in calldata, and a Single Proof function try_append_many_using_one_c( bytes32 root, uint256 index, bytes calldata element, bytes[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to append bytes elements in memory, given a root, an index, a bytes element in calldata, and a Single Proof function try_append_many_using_one_m( bytes32 root, uint256 index, bytes calldata element, bytes[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to append bytes32 elements in calldata, given a root, an index, a bytes32 element, and a Single Proof function try_append_many_using_one_c( bytes32 root, uint256 index, bytes32 element, bytes32[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to append bytes32 elements in memory, given a root, an index, a bytes32 element, and a Single Proof function try_append_many_using_one_m( bytes32 root, uint256 index, bytes32 element, bytes32[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to append a bytes element in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof function try_append_one_using_many_c( bytes32 root, bytes[] calldata elements, bytes calldata append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to append a bytes element in memory, given a root, bytes elements in calldata, and an Existence Multi Proof function try_append_one_using_many_m( bytes32 root, bytes[] calldata elements, bytes memory append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to append a bytes32 element, given a root, bytes32 elements in calldata, and an Existence Multi Proof function try_append_one_using_many( bytes32 root, bytes32[] calldata elements, bytes32 append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to append bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof function try_append_many_using_many_c( bytes32 root, bytes[] calldata elements, bytes[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to append bytes elements in memory, given a root, bytes elements in calldata, and an Existence Multi Proof function try_append_many_using_many_m( bytes32 root, bytes[] calldata elements, bytes[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to append bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof function try_append_many_using_many_c( bytes32 root, bytes32[] calldata elements, bytes32[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to append bytes32 elements in memory, given a root, bytes32 elements in calldata, and an Existence Multi Proof function try_append_many_using_many_m( bytes32 root, bytes32[] calldata elements, bytes32[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to update a bytes element in calldata and append a bytes element in calldata, // given a root, an index, a bytes element in calldata, and a Single Proof function try_update_one_and_append_one_c( bytes32 root, uint256 index, bytes calldata element, bytes calldata update_element, bytes calldata append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof_update_c(index, element, update_element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to update a bytes element in memory and append a bytes element in memory, // given a root, an index, a bytes element in calldata, and a Single Proof function try_update_one_and_append_one_m( bytes32 root, uint256 index, bytes calldata element, bytes memory update_element, bytes memory append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof_update_m(index, element, update_element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to update a bytes32 element and append a bytes32 element, // given a root, an index, a bytes32 element, and a Single Proof function try_update_one_and_append_one( bytes32 root, uint256 index, bytes32 element, bytes32 update_element, bytes32 append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to update a bytes element in calldata and append bytes elements in calldata, // given a root, an index, a bytes element in calldata, and a Single Proof function try_update_one_and_append_many_c( bytes32 root, uint256 index, bytes calldata element, bytes calldata update_element, bytes[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof_update_c(index, element, update_element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to update a bytes element in memory and append bytes elements in memory, // given a root, an index, a bytes element in calldata, and a Single Proof function try_update_one_and_append_many_m( bytes32 root, uint256 index, bytes calldata element, bytes memory update_element, bytes[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof_update_m(index, element, update_element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to update a bytes32 element and append bytes32 elements in calldata, // given a root, an index, a bytes32 element, and a Single Proof function try_update_one_and_append_many_c( bytes32 root, uint256 index, bytes32 element, bytes32 update_element, bytes32[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to update a bytes32 element and append bytes32 elements in memory, // given a root, an index, a bytes32 element, and a Single Proof function try_update_one_and_append_many_m( bytes32 root, uint256 index, bytes32 element, bytes32 update_element, bytes32[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to update bytes elements in calldata and append a bytes element in calldata, // given a root, bytes elements in calldata, and a Single Proof function try_update_many_and_append_one_c( bytes32 root, bytes[] calldata elements, bytes[] calldata update_elements, bytes calldata append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to update bytes elements in memory and append a bytes element in memory, // given a root, bytes elements in calldata, and a Single Proof function try_update_many_and_append_one_m( bytes32 root, bytes[] calldata elements, bytes[] memory update_elements, bytes memory append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to update bytes32 elements in calldata and append a bytes32 element, // given a root, bytes32 elements in calldata, and a Single Proof function try_update_many_and_append_one_c( bytes32 root, bytes32[] calldata elements, bytes32[] calldata update_elements, bytes32 append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to update bytes32 elements in memory and append a bytes32 element, // given a root, bytes32 elements in calldata, and a Single Proof function try_update_many_and_append_one_m( bytes32 root, bytes32[] calldata elements, bytes32[] memory update_elements, bytes32 append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); } // INTERFACE: Try to update bytes elements in calldata and append bytes elements in calldata, // given a root, bytes elements in calldata, and an Existence Multi Proof function try_update_many_and_append_many_c( bytes32 root, bytes[] calldata elements, bytes[] calldata update_elements, bytes[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to update bytes elements in memory and append bytes elements in memory, // given a root, bytes elements in calldata, and an Existence Multi Proof function try_update_many_and_append_many_m( bytes32 root, bytes[] calldata elements, bytes[] memory update_elements, bytes[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to update bytes32 elements in calldata and append bytes32 elements in calldata, // given a root, bytes32 elements in calldata, and an Existence Multi Proof function try_update_many_and_append_many_c( bytes32 root, bytes32[] calldata elements, bytes32[] calldata update_elements, bytes32[] calldata append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Try to update bytes32 elements in memory and append bytes32 elements in memory, // given a root, bytes32 elements in calldata, and an Existence Multi Proof function try_update_many_and_append_many_m( bytes32 root, bytes32[] calldata elements, bytes32[] memory update_elements, bytes32[] memory append_elements, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof); return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root); } // INTERFACE: Create a tree and return the root, given a bytes element in calldata function create_from_one_c(bytes calldata element) internal pure returns (bytes32 new_element_root) { return hash_node(bytes32(uint256(1)), get_root_from_one_c(element)); } // INTERFACE: Create a tree and return the root, given a bytes element in memory function create_from_one_m(bytes memory element) internal pure returns (bytes32 new_element_root) { return hash_node(bytes32(uint256(1)), get_root_from_one_m(element)); } // INTERFACE: Create a tree and return the root, given a bytes32 element function create_from_one(bytes32 element) internal pure returns (bytes32 new_element_root) { return hash_node(bytes32(uint256(1)), get_root_from_one(element)); } // INTERFACE: Create a tree and return the root, given bytes elements in calldata function create_from_many_c(bytes[] calldata elements) internal pure returns (bytes32 new_element_root) { return hash_node(bytes32(elements.length), get_root_from_many_c(elements)); } // INTERFACE: Create a tree and return the root, given bytes elements in memory function create_from_many_m(bytes[] memory elements) internal pure returns (bytes32 new_element_root) { return hash_node(bytes32(elements.length), get_root_from_many_m(elements)); } // INTERFACE: Create a tree and return the root, given bytes32 elements in calldata function create_from_many_c(bytes32[] calldata elements) internal pure returns (bytes32 new_element_root) { return hash_node(bytes32(elements.length), get_root_from_many_c(elements)); } // INTERFACE: Create a tree and return the root, given bytes32 elements in memory function create_from_many_m(bytes32[] memory elements) internal pure returns (bytes32 new_element_root) { return hash_node(bytes32(elements.length), get_root_from_many_m(elements)); } }
INTERFACE: Try to update bytes32 elements in memory and append a bytes32 element, given a root, bytes32 elements in calldata, and a Single Proof
function try_update_many_and_append_one_m( bytes32 root, bytes32[] calldata elements, bytes32[] memory update_elements, bytes32 append_element, bytes32[] calldata proof ) internal pure returns (bytes32 element_root) { bytes32 total_element_count = proof[0]; require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE"); bytes32[] memory append_proof; (element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof); require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF"); element_root = get_new_root_from_append_proof_single_append(append_element, append_proof); return hash_node(bytes32(uint256(total_element_count) + 1), element_root); }
12,859,805
./full_match/1/0xE540D1b18B40dF28b844F77C26d5A9b01b966E57/sources/src/SharpFactsAggregator.sol
Registers a new range to aggregate from Caches a recent block hash (MINIMUM_BLOCKS_CONFIRMATIONS to -MAXIMUM_BLOCKS_CONFIRMATIONS from present), relying on the global `blockhash` Solidity function blocksConfirmations Number of blocks preceding the current block Minimum blocks confirmations to avoid reorgs Maximum MAXIMUM_BLOCKS_CONFIRMATIONS blocks confirmations to capture an available block hash with Solidity `blockhash()` If the parent hash is not available, revert (This should never happen under the current EVM rules) If we cannot aggregate further in the past (e.g., genesis block is reached or it's a new tree) Set the aggregator state's `continuableParentHash` to the target block's parent hash so we can easily continue aggregating from it without specifying `rightBoundStartBlock` in `aggregateSharpJobs`
function registerNewRange( uint256 blocksConfirmations ) external onlyOperator { if (blocksConfirmations < MINIMUM_BLOCKS_CONFIRMATIONS) { revert NotEnoughBlockConfirmations(); } if (blocksConfirmations > MAXIMUM_BLOCKS_CONFIRMATIONS) { revert TooManyBlocksConfirmations(); } if (targetBlockParentHash == bytes32(0)) { revert UnknownParentHash(); } if (aggregatorState.continuableParentHash == bytes32(0)) { aggregatorState.continuableParentHash = targetBlockParentHash; } emit NewRangeRegistered(targetBlock, targetBlockParentHash); }
16,518,339
./partial_match/8217/0xEa6E36822227100B8FccBbEd55520c00a17BD160/sources/contracts/Voting.sol
Queue a passed proposal The proposal must be in Passed state Current block must be before `queueDeadline` of this proposal If secretary is null, any GC with at least 1 vote can queue. Otherwise only secretary can queue.
function queue(uint256 proposalId) external override onlyState(proposalId, ProposalState.Passed) onlyExecutor(proposalId) { Proposal storage p = proposals[proposalId]; require(p.targets.length > 0, "Proposal has no action"); p.eta = block.number + execDelay; p.execDeadline = p.eta + execTimeout; p.queued = true; emit ProposalQueued(proposalId, p.eta); }
16,911,284
pragma solidity ^0.4.17; import "./Distribute.sol"; contract Transaction { // Tracks the addres of the questioner, index of the question. mapping(uint => address) public questionTracker; // Tracks the tokens pledged, index of the question. mapping(uint => uint) public questionValue; // Tracks the id to an array of addresses of answerers. mapping (uint => address[]) public answererTracker; // Tracks the id to an array of tokens rewarded to the answerers. mapping (uint => uint[]) public tokensRewarded; // Address of the deployed contract of Distribute contract. address bank; Distribute instanceDistribute; function Transaction( address distributeAddress ) public { instanceDistribute = Distribute(distributeAddress); } function accountCreation(address _account) public returns (bool success) { //Distribute instanceDistribute = Distribute(bank); return instanceDistribute.accountCreation(_account); } function getBalance(address _account) public returns (uint){ //Distribute instanceDistribute = Distribute(bank); return instanceDistribute.balanceOf(_account); } // If enough in balance, subtracts from account, sets to questioner public variable, and // returns true. Else, return false. function addQuestioner(address _questioner, uint _value, uint _id) public returns (bool success) { if(instanceDistribute.checkBalance(_questioner, _value)) { questionTracker[_id] = _questioner; questionValue[_id] = _value; return true; } else { return false; } } // Function adds answerer to the contract. function addAnswerer(address _answerer, uint _id) public returns (bool success) { answererTracker[_id].push(_answerer); return true; } // Function distributes token from the tokensRewarded variable. function executeTransaction(uint[] distribution, uint _id) public returns (bool success) { //Distribute instanceDistribute = Distribute(bank); tokensRewarded[_id] = distribution; for(uint i = 0; i < answererTracker[_id].length; i++) { bool process = instanceDistribute.addTokens(answererTracker[_id][i], tokensRewarded[_id][i]); if(!process) { return false; } } return true; } }
If enough in balance, subtracts from account, sets to questioner public variable, and returns true. Else, return false.
function addQuestioner(address _questioner, uint _value, uint _id) public returns (bool success) { if(instanceDistribute.checkBalance(_questioner, _value)) { questionTracker[_id] = _questioner; questionValue[_id] = _value; return true; } else { return false; } }
15,843,909
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev {ERC1155} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract NiftyLaunchComics is Context, AccessControl, ERC1155, Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); string public name = "Nifty Launch Comics"; string public symbol = "NLC"; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that * deploys the contract. */ constructor(string memory uri) ERC1155(uri) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Updates base token uri * * See {ERC1155-_setURI}. * * Requirements: * * - the caller must have the `DEFAULT_ADMIN_ROLE`. */ function setURI(string memory newuri) external onlyRole(DEFAULT_ADMIN_ROLE) { _setURI(newuri); } /** * @dev Allows token holders to destroy both their * own tokens and those that they have been approved to use. * * See {ERC1155-_burn}. * * Requirements: * * - burning must not be paused. */ function burn( address account, uint256 id, uint256 value ) public whenNotPaused { require(account == _msgSender() || isApprovedForAll(account, _msgSender()), "Caller is not owner nor approved"); _burn(account, id, value); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {burn}. */ function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public whenNotPaused { require(account == _msgSender() || isApprovedForAll(account, _msgSender()), "Caller is not owner nor approved"); _burnBatch(account, ids, values); } /** * @dev Creates `amount` new tokens for `to`, of token type `id`. * * See {ERC1155-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint( address to, uint256 id, uint256 amount, bytes memory data ) public onlyRole(MINTER_ROLE) { _mint(to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}. */ function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public onlyRole(MINTER_ROLE) { _mintBatch(to, ids, amounts, data); } /** * @dev Pauses all token burns. * * See {ERC1155Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pauseBurn() public onlyRole(PAUSER_ROLE) { _pause(); } /** * @dev Unpauses all token burns. * * See {ERC1155Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpauseBurn() public onlyRole(PAUSER_ROLE) { _unpause(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(AccessControl, ERC1155) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT 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; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT 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); } }
See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view override(AccessControl, ERC1155) returns (bool) { return super.supportsInterface(interfaceId); }
5,792,560
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; contract UpgradeableNFT is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, OwnableUpgradeable, UUPSUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; CountersUpgradeable.Counter private _tokenIdCounter; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() initializer public { __ERC721_init("UpgradeableNFT", "UNFT"); __ERC721Enumerable_init(); __ERC721URIStorage_init(); __Ownable_init(); __UUPSUpgradeable_init(); } // custom function version() pure public virtual returns(string memory){ return 'V1'; } // mint tokens and send them function massSend(address[] calldata recipients, string[] calldata uris) external virtual onlyOwner{ for(uint index = 0 ; index < recipients.length; index++){ address to = recipients[index]; uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uris[index]); } } //end custom function safeMint(address to, string memory uri) public virtual onlyOwner { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uri); } function _authorizeUpgrade(address newImplementation) internal onlyOwner override {} // The following functions are overrides required by Solidity. function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } } contract UpgradeableNFT_V2 is UpgradeableNFT { function version() pure public override virtual returns(string memory){ return 'V2'; } } contract UpgradeableNFT_V3 is UpgradeableNFT_V2 { function version() pure public override virtual returns(string memory){ return 'V3'; } }
mint tokens and send them
function massSend(address[] calldata recipients, string[] calldata uris) external virtual onlyOwner{ for(uint index = 0 ; index < recipients.length; index++){ address to = recipients[index]; uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(to, tokenId); _setTokenURI(tokenId, uris[index]); } }
5,399,815
// SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./ERC20/IERC20.sol"; import "./ERC20/IERC20Permit.sol"; import "./ERC20/SafeERC20.sol"; import "./interfaces/IERC3156FlashBorrower.sol"; import "./interfaces/IERC3156FlashLender.sol"; import "./interfaces/IRERC20.sol"; import "./interfaces/IRTokenProxy.sol"; import "./interfaces/IRulerCore.sol"; import "./interfaces/IOracle.sol"; import "./utils/Clones.sol"; import "./utils/Create2.sol"; import "./utils/Initializable.sol"; import "./utils/Ownable.sol"; import "./utils/ReentrancyGuard.sol"; /** * @title RulerCore contract * @author crypto-pumpkin * Ruler Pair: collateral, paired token, expiry, mintRatio * - ! Paired Token cannot be a deflationary token ! * - rTokens have same decimals of each paired token * - all Ratios are 1e18 * - rTokens have same decimals as Paired Token * - Collateral can be deflationary token, but not rebasing token */ contract RulerCore is Ownable, IRulerCore, IERC3156FlashLender, ReentrancyGuard { using SafeERC20 for IERC20; // following ERC3156 https://eips.ethereum.org/EIPS/eip-3156 bytes32 public constant FLASHLOAN_CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); bool public override paused; IOracle public override oracle; address public override responder; address public override feeReceiver; address public override rERC20Impl; uint256 public override flashLoanRate; address[] public override collaterals; /// @notice collateral => minimum collateralization ratio, paired token default to 1e18 mapping(address => uint256) public override minColRatioMap; /// @notice collateral => pairedToken => expiry => mintRatio => Pair mapping(address => mapping(address => mapping(uint48 => mapping(uint256 => Pair)))) public override pairs; mapping(address => Pair[]) private pairList; mapping(address => uint256) public override feesMap; // v1.0.2 uint256 public override depositPauseWindow; // v1.0.3 uint256 public override redeemFeeRate; modifier onlyNotPaused() { require(!paused, "Ruler: paused"); _; } function initialize(address _rERC20Impl, address _feeReceiver) external initializer { require(_rERC20Impl != address(0), "Ruler: _rERC20Impl cannot be 0"); require(_feeReceiver != address(0), "Ruler: _feeReceiver cannot be 0"); rERC20Impl = _rERC20Impl; feeReceiver = _feeReceiver; flashLoanRate = 0.00085 ether; depositPauseWindow = 24 hours; initializeOwner(); initializeReentrancyGuard(); } /// @notice market make deposit, deposit paired Token to received rcTokens, considered as an immediately repaid loan function mmDeposit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt ) public override onlyNotPaused nonReentrant { Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio]; _validateDepositInputs(_col, pair); pair.rcToken.mint(msg.sender, _rcTokenAmt); feesMap[_paired] = feesMap[_paired] + _rcTokenAmt * pair.feeRate / 1e18; // record loan ammount to colTotal as it is equivalent to be an immediately repaid loan uint256 colAmount = _getColAmtFromRTokenAmt(_rcTokenAmt, _col, address(pair.rcToken), pair.mintRatio); pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal + colAmount; // receive paired tokens from sender, deflationary token is not allowed IERC20 pairedToken = IERC20(_paired); uint256 pairedBalBefore = pairedToken.balanceOf(address(this)); pairedToken.safeTransferFrom(msg.sender, address(this), _rcTokenAmt); require(pairedToken.balanceOf(address(this)) - pairedBalBefore >= _rcTokenAmt, "Ruler: transfer paired failed"); emit MarketMakeDeposit(msg.sender, _col, _paired, _expiry, _mintRatio, _rcTokenAmt); } function mmDepositWithPermit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt, Permit calldata _pairedPermit ) external override { _permit(_paired, _pairedPermit); mmDeposit(_col, _paired, _expiry, _mintRatio, _rcTokenAmt); } /// @notice deposit collateral to a Ruler Pair, sender receives rcTokens and rrTokens function deposit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt ) public override onlyNotPaused nonReentrant { Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio]; _validateDepositInputs(_col, pair); // receive collateral IERC20 collateral = IERC20(_col); uint256 colBalBefore = collateral.balanceOf(address(this)); collateral.safeTransferFrom(msg.sender, address(this), _colAmt); uint256 received = collateral.balanceOf(address(this)) - colBalBefore; require(received > 0, "Ruler: transfer failed"); pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal + received; // mint rTokens for reveiced collateral uint256 mintAmount = _getRTokenAmtFromColAmt(received, _col, _paired, pair.mintRatio); pair.rcToken.mint(msg.sender, mintAmount); pair.rrToken.mint(msg.sender, mintAmount); emit Deposit(msg.sender, _col, _paired, _expiry, _mintRatio, received); } function depositWithPermit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, Permit calldata _colPermit ) external override { _permit(_col, _colPermit); deposit(_col, _paired, _expiry, _mintRatio, _colAmt); } /// @notice redeem with rrTokens and rcTokens before expiry only, sender receives collateral, fees charged on collateral function redeem( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rTokenAmt ) external override onlyNotPaused nonReentrant { Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio]; require(pair.mintRatio != 0, "Ruler: pair does not exist"); require(block.timestamp <= pair.expiry, "Ruler: expired, col forfeited"); pair.rrToken.burnByRuler(msg.sender, _rTokenAmt); pair.rcToken.burnByRuler(msg.sender, _rTokenAmt); // send collateral to sender uint256 colAmountToPay = _getColAmtFromRTokenAmt(_rTokenAmt, _col, address(pair.rcToken), pair.mintRatio); // once redeemed, it won't be considered as a loan for the pair anymore pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal - colAmountToPay; // accrue fees on payment _sendAmtPostFeesOptionalAccrue(IERC20(_col), colAmountToPay, redeemFeeRate, true /* accrue */); emit Redeem(msg.sender, _col, _paired, _expiry, _mintRatio, _rTokenAmt); } /// @notice repay with rrTokens and paired token amount, sender receives collateral, no fees charged on collateral function repay( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rrTokenAmt ) public override onlyNotPaused nonReentrant { Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio]; require(pair.mintRatio != 0, "Ruler: pair does not exist"); require(block.timestamp <= pair.expiry, "Ruler: expired, col forfeited"); pair.rrToken.burnByRuler(msg.sender, _rrTokenAmt); // receive paired tokens from sender, deflationary token is not allowed IERC20 pairedToken = IERC20(_paired); uint256 pairedBalBefore = pairedToken.balanceOf(address(this)); pairedToken.safeTransferFrom(msg.sender, address(this), _rrTokenAmt); require(pairedToken.balanceOf(address(this)) - pairedBalBefore >= _rrTokenAmt, "Ruler: transfer paired failed"); feesMap[_paired] = feesMap[_paired] + _rrTokenAmt * pair.feeRate / 1e18; // send collateral back to sender uint256 colAmountToPay = _getColAmtFromRTokenAmt(_rrTokenAmt, _col, address(pair.rrToken), pair.mintRatio); _safeTransfer(IERC20(_col), msg.sender, colAmountToPay); emit Repay(msg.sender, _col, _paired, _expiry, _mintRatio, _rrTokenAmt); } function repayWithPermit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rrTokenAmt, Permit calldata _pairedPermit ) external override { _permit(_paired, _pairedPermit); repay(_col, _paired, _expiry, _mintRatio, _rrTokenAmt); } /// @notice sender collect paired tokens by returning same amount of rcTokens to Ruler function collect( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt ) external override onlyNotPaused nonReentrant { Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio]; require(pair.mintRatio != 0, "Ruler: pair does not exist"); require(block.timestamp > pair.expiry, "Ruler: not ready"); pair.rcToken.burnByRuler(msg.sender, _rcTokenAmt); IERC20 pairedToken = IERC20(_paired); uint256 defaultedLoanAmt = pair.rrToken.totalSupply(); if (defaultedLoanAmt == 0) { // no default, send paired Token to sender // no fees accrued as it is accrued on Borrower payment _sendAmtPostFeesOptionalAccrue(pairedToken, _rcTokenAmt, pair.feeRate, false /* accrue */); } else { // rcTokens eligible to collect at expiry (converted from total collateral received, redeemed collateral not counted) == total loan amount at the moment of expiry uint256 rcTokensEligibleAtExpiry = _getRTokenAmtFromColAmt(pair.colTotal, _col, _paired, pair.mintRatio); // paired token amount to pay = rcToken amount * (1 - default ratio) uint256 pairedTokenAmtToCollect = _rcTokenAmt * (rcTokensEligibleAtExpiry - defaultedLoanAmt) / rcTokensEligibleAtExpiry; // no fees accrued as it is accrued on Borrower payment _sendAmtPostFeesOptionalAccrue(pairedToken, pairedTokenAmtToCollect, pair.feeRate, false /* accrue */); // default collateral amount to pay = converted collateral amount (from rcTokenAmt) * default ratio uint256 colAmount = _getColAmtFromRTokenAmt(_rcTokenAmt, _col, address(pair.rcToken), pair.mintRatio); uint256 colAmountToCollect = colAmount * defaultedLoanAmt / rcTokensEligibleAtExpiry; // accrue fees on defaulted collateral since it was never accrued _sendAmtPostFeesOptionalAccrue(IERC20(_col), colAmountToCollect, pair.feeRate, true /* accrue */); } emit Collect(msg.sender, _col, _paired,_expiry, _mintRatio, _rcTokenAmt); } function collectFees(IERC20[] calldata _tokens) external override onlyOwner { for (uint256 i = 0; i < _tokens.length; i++) { IERC20 token = _tokens[i]; uint256 fee = feesMap[address(token)]; feesMap[address(token)] = 0; _safeTransfer(token, feeReceiver, fee); } } /** * @notice add a new Ruler Pair * - Paired Token cannot be a deflationary token * - minColRatio is not respected if collateral is alreay added * - all Ratios are 1e18 */ function addPair( address _col, address _paired, uint48 _expiry, string calldata _expiryStr, uint256 _mintRatio, string calldata _mintRatioStr, uint256 _feeRate ) external override onlyOwner { require(pairs[_col][_paired][_expiry][_mintRatio].mintRatio == 0, "Ruler: pair exists"); require(_mintRatio > 0, "Ruler: _mintRatio <= 0"); require(_feeRate < 0.1 ether, "Ruler: fee rate must be < 10%"); require(_expiry > block.timestamp, "Ruler: expiry in the past"); require(minColRatioMap[_col] > 0, "Ruler: col not listed"); if (minColRatioMap[_paired] == 0) { collaterals.push(_paired); // auto add paired token to collateral list minColRatioMap[_paired] = 1.05 ether; // default paired token to 105% collateralization ratio as most of them are stablecoins, can be updated later. } Pair memory pair = Pair({ active: true, feeRate: _feeRate, mintRatio: _mintRatio, expiry: _expiry, pairedToken: _paired, rcToken: IRERC20(_createRToken(_col, _paired, _expiry, _expiryStr, _mintRatioStr, "RC_")), rrToken: IRERC20(_createRToken(_col, _paired, _expiry, _expiryStr, _mintRatioStr, "RR_")), colTotal: 0 }); pairs[_col][_paired][_expiry][_mintRatio] = pair; pairList[_col].push(pair); emit PairAdded(_col, _paired, _expiry, _mintRatio); } /** * @notice allow flash loan borrow allowed tokens up to all core contracts' holdings * _receiver will received the requested amount, and need to payback the loan amount + fees * _receiver must implement IERC3156FlashBorrower * no deflationary tokens */ function flashLoan( IERC3156FlashBorrower _receiver, address _token, uint256 _amount, bytes calldata _data ) public override onlyNotPaused returns (bool) { require(minColRatioMap[_token] > 0, "Ruler: token not allowed"); IERC20 token = IERC20(_token); uint256 tokenBalBefore = token.balanceOf(address(this)); token.safeTransfer(address(_receiver), _amount); uint256 fees = flashFee(_token, _amount); require( _receiver.onFlashLoan(msg.sender, _token, _amount, fees, _data) == FLASHLOAN_CALLBACK_SUCCESS, "IERC3156: Callback failed" ); // receive loans and fees token.safeTransferFrom(address(_receiver), address(this), _amount + fees); require(token.balanceOf(address(this)) - tokenBalBefore >= fees, "Ruler: not enough fees"); feesMap[_token] = feesMap[_token] + fees; emit FlashLoan(_token, address(_receiver), _amount); return true; } /// @notice flashloan rate can be anything function setFlashLoanRate(uint256 _newRate) external override onlyOwner { emit FlashLoanRateUpdated(flashLoanRate, _newRate); flashLoanRate = _newRate; } /// @notice add new or update existing collateral function updateCollateral(address _col, uint256 _minColRatio) external override onlyOwner { require(_minColRatio > 0, "Ruler: min colRatio < 0"); emit CollateralUpdated(_col, minColRatioMap[_col], _minColRatio); if (minColRatioMap[_col] == 0) { collaterals.push(_col); } minColRatioMap[_col] = _minColRatio; } function setPairActive( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, bool _active ) external override onlyOwner { pairs[_col][_paired][_expiry][_mintRatio].active = _active; } function setFeeReceiver(address _address) external override onlyOwner { require(_address != address(0), "Ruler: address cannot be 0"); emit AddressUpdated('feeReceiver', feeReceiver, _address); feeReceiver = _address; } /// @dev update this will only affect pools deployed after function setRERC20Impl(address _newImpl) external override onlyOwner { require(_newImpl != address(0), "Ruler: _newImpl cannot be 0"); emit RERC20ImplUpdated(rERC20Impl, _newImpl); rERC20Impl = _newImpl; } function setPaused(bool _paused) external override { require(msg.sender == owner() || msg.sender == responder, "Ruler: not owner/responder"); emit PausedStatusUpdated(paused, _paused); paused = _paused; } function setResponder(address _address) external override onlyOwner { require(_address != address(0), "Ruler: address cannot be 0"); emit AddressUpdated('responder', responder, _address); responder = _address; } function setOracle(address _address) external override onlyOwner { require(_address != address(0), "Ruler: address cannot be 0"); emit AddressUpdated('oracle', address(oracle), _address); oracle = IOracle(_address); } /// @notice flashloan rate can be anything function setDepositPauseWindow(uint256 _newWindow) external override onlyOwner { emit DepositPauseWindow(depositPauseWindow, _newWindow); depositPauseWindow = _newWindow; } /// @notice redeemFee rate can be anything < 10% function setRedeemFeeRate(uint256 _newFeeRate) external override onlyOwner { require(_newFeeRate < 0.1 ether, "Ruler: fee rate must be < 10%"); emit RedeemFeeRateUpdated(redeemFeeRate, _newFeeRate); redeemFeeRate = _newFeeRate; } function getCollaterals() external view override returns (address[] memory) { return collaterals; } function getPairList(address _col) external view override returns (Pair[] memory) { Pair[] memory colPairList = pairList[_col]; Pair[] memory _pairs = new Pair[](colPairList.length); for (uint256 i = 0; i < colPairList.length; i++) { Pair memory pair = colPairList[i]; _pairs[i] = pairs[_col][pair.pairedToken][pair.expiry][pair.mintRatio]; } return _pairs; } /// @notice amount that is eligible to collect function viewCollectible( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt ) external view override returns (uint256 colAmtToCollect, uint256 pairedAmtToCollect) { Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio]; if (pair.mintRatio == 0 || block.timestamp < pair.expiry) return (colAmtToCollect, pairedAmtToCollect); uint256 defaultedLoanAmt = pair.rrToken.totalSupply(); if (defaultedLoanAmt == 0) { // no default, transfer paired Token pairedAmtToCollect = _rcTokenAmt; } else { // rcTokens eligible to collect at expiry (converted from total collateral received, redeemed collateral not counted) == total loan amount at the moment of expiry uint256 rcTokensEligibleAtExpiry = _getRTokenAmtFromColAmt(pair.colTotal, _col, _paired, pair.mintRatio); // paired token amount to pay = rcToken amount * (1 - default ratio) pairedAmtToCollect = _rcTokenAmt * (rcTokensEligibleAtExpiry - defaultedLoanAmt) * (1e18 - pair.feeRate) / 1e18 / rcTokensEligibleAtExpiry; // default collateral amount to pay = converted collateral amount (from rcTokenAmt) * default ratio uint256 colAmount = _getColAmtFromRTokenAmt(_rcTokenAmt, _col, address(pair.rcToken), pair.mintRatio); colAmtToCollect = colAmount * defaultedLoanAmt * (1e18 - pair.feeRate) / 1e18 / rcTokensEligibleAtExpiry; } } function maxFlashLoan(address _token) external view override returns (uint256) { return IERC20(_token).balanceOf(address(this)); } /// @notice returns the amount of fees charges by for the loan amount. 0 means no fees charged, may not have the token function flashFee(address _token, uint256 _amount) public view override returns (uint256 _fees) { require(minColRatioMap[_token] > 0, "RulerCore: token not supported"); _fees = _amount * flashLoanRate / 1e18; } /// @notice version of current Ruler Core hardcoded function version() external pure override returns (string memory) { return '1.0.3'; } function _safeTransfer(IERC20 _token, address _account, uint256 _amount) private { uint256 bal = _token.balanceOf(address(this)); if (bal < _amount) { _token.safeTransfer(_account, bal); } else { _token.safeTransfer(_account, _amount); } } function _sendAmtPostFeesOptionalAccrue(IERC20 _token, uint256 _amount, uint256 _feeRate, bool _accrue) private { uint256 fees = _amount * _feeRate / 1e18; _safeTransfer(_token, msg.sender, _amount - fees); if (_accrue) { feesMap[address(_token)] = feesMap[address(_token)] + fees; } } function _createRToken( address _col, address _paired, uint256 _expiry, string calldata _expiryStr, string calldata _mintRatioStr, string memory _prefix ) private returns (address proxyAddr) { uint8 decimals = uint8(IERC20(_paired).decimals()); require(decimals > 0, "RulerCore: paired decimals is 0"); string memory symbol = string(abi.encodePacked( _prefix, IERC20(_col).symbol(), "_", _mintRatioStr, "_", IERC20(_paired).symbol(), "_", _expiryStr )); bytes32 salt = keccak256(abi.encodePacked(_col, _paired, _expiry, _mintRatioStr, _prefix)); proxyAddr = Clones.cloneDeterministic(rERC20Impl, salt); IRTokenProxy(proxyAddr).initialize("Ruler Protocol rToken", symbol, decimals); emit RTokenCreated(proxyAddr); } function _getRTokenAmtFromColAmt(uint256 _colAmt, address _col, address _paired, uint256 _mintRatio) private view returns (uint256) { uint8 colDecimals = IERC20(_col).decimals(); // pairedDecimals is the same as rToken decimals uint8 pairedDecimals = IERC20(_paired).decimals(); return _colAmt * _mintRatio * (10 ** pairedDecimals) / (10 ** colDecimals) / 1e18; } function _getColAmtFromRTokenAmt(uint256 _rTokenAmt, address _col, address _rToken, uint256 _mintRatio) private view returns (uint256) { uint8 colDecimals = IERC20(_col).decimals(); // pairedDecimals == rToken decimals uint8 rTokenDecimals = IERC20(_rToken).decimals(); return _rTokenAmt * (10 ** colDecimals) * 1e18 / _mintRatio / (10 ** rTokenDecimals); } function _permit(address _token, Permit calldata permit) private { IERC20Permit(_token).permit( permit.owner, permit.spender, permit.amount, permit.deadline, permit.v, permit.r, permit.s ); } function _validateDepositInputs(address _col, Pair memory _pair) private view { require(_pair.mintRatio != 0, "Ruler: pair does not exist"); require(_pair.active, "Ruler: pair inactive"); require(_pair.expiry - depositPauseWindow > block.timestamp, "Ruler: deposit ended"); // Oracle price is not required, the consequence is low since it will just allow users to deposit collateral (which can be collected thro repay before expiry. If default, early repayments will be diluted if (address(oracle) != address(0)) { uint256 colPrice = oracle.getPriceUSD(_col); if (colPrice != 0) { uint256 pairedPrice = oracle.getPriceUSD(_pair.pairedToken); if (pairedPrice != 0) { // colPrice / mintRatio (1e18) / pairedPrice > min collateralization ratio (1e18), if yes, revert deposit require(colPrice * 1e36 > minColRatioMap[_col] * _pair.mintRatio * pairedPrice, "Ruler: collateral price too low"); } } } } } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; /** * @title Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `amount` 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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.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 { 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: No License pragma solidity ^0.8.0; interface IERC3156FlashBorrower { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./IERC3156FlashBorrower.sol"; interface IERC3156FlashLender { /** * @dev The amount of currency available to be lent. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan( address token ) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee( address token, uint256 amount ) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "../ERC20/IERC20.sol"; /** * @title RERC20 contract interface, implements {IERC20}. See {RERC20}. * @author crypto-pumpkin */ interface IRERC20 is IERC20 { /// @notice access restriction - owner (R) function mint(address _account, uint256 _amount) external returns (bool); function burnByRuler(address _account, uint256 _amount) external returns (bool); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; /** * @title Interface of the RTokens Proxy. */ interface IRTokenProxy { function initialize(string calldata _name, string calldata _symbol, uint8 _decimals) external; } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./IRERC20.sol"; import "./IOracle.sol"; /** * @title IRulerCore contract interface. See {RulerCore}. * @author crypto-pumpkin */ interface IRulerCore { event RTokenCreated(address); event CollateralUpdated(address col, uint256 old, uint256 _new); event PairAdded(address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio); event MarketMakeDeposit(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event Deposit(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event Repay(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event Redeem(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event Collect(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event AddressUpdated(string _type, address old, address _new); event PausedStatusUpdated(bool old, bool _new); event RERC20ImplUpdated(address rERC20Impl, address newImpl); event FlashLoanRateUpdated(uint256 old, uint256 _new); // v1.0.1 event FlashLoan(address _token, address _borrower, uint256 _amount); // v1.0.2 event DepositPauseWindow(uint256 old, uint256 _new); event RedeemFeeRateUpdated(uint256 old, uint256 _new); struct Pair { bool active; uint48 expiry; address pairedToken; IRERC20 rcToken; // ruler capitol token, e.g. RC_Dai_wBTC_2_2021 IRERC20 rrToken; // ruler repayment token, e.g. RR_Dai_wBTC_2_2021 uint256 mintRatio; // 1e18, price of collateral / collateralization ratio uint256 feeRate; // 1e18 uint256 colTotal; } struct Permit { address owner; address spender; uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } // state vars function oracle() external view returns (IOracle); function version() external pure returns (string memory); function flashLoanRate() external view returns (uint256); function paused() external view returns (bool); function responder() external view returns (address); function feeReceiver() external view returns (address); function rERC20Impl() external view returns (address); function collaterals(uint256 _index) external view returns (address); function minColRatioMap(address _col) external view returns (uint256); function feesMap(address _token) external view returns (uint256); function pairs(address _col, address _paired, uint48 _expiry, uint256 _mintRatio) external view returns ( bool active, uint48 expiry, address pairedToken, IRERC20 rcToken, IRERC20 rrToken, uint256 mintRatio, uint256 feeRate, uint256 colTotal ); function depositPauseWindow() external view returns (uint256); function redeemFeeRate() external view returns (uint256); // extra view function getCollaterals() external view returns (address[] memory); function getPairList(address _col) external view returns (Pair[] memory); function viewCollectible( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt ) external view returns (uint256 colAmtToCollect, uint256 pairedAmtToCollect); // user action - only when not paused function mmDeposit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt ) external; function mmDepositWithPermit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt, Permit calldata _pairedPermit ) external; function deposit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt ) external; function depositWithPermit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, Permit calldata _colPermit ) external; function redeem( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rTokenAmt ) external; function repay( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rrTokenAmt ) external; function repayWithPermit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rrTokenAmt, Permit calldata _pairedPermit ) external; function collect( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt ) external; // access restriction - owner (dev) function collectFees(IERC20[] calldata _tokens) external; // access restriction - owner (dev) & responder function setPaused(bool _paused) external; // access restriction - owner (dev) function addPair( address _col, address _paired, uint48 _expiry, string calldata _expiryStr, uint256 _mintRatio, string calldata _mintRatioStr, uint256 _feeRate ) external; function setPairActive( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, bool _active ) external; function updateCollateral(address _col, uint256 _minColRatio) external; function setFeeReceiver(address _addr) external; function setResponder(address _addr) external; function setRERC20Impl(address _addr) external; function setOracle(address _addr) external; function setFlashLoanRate(uint256 _newRate) external; function setDepositPauseWindow(uint256 _newWindow) external; function setRedeemFeeRate(uint256 _newFeeRate) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IOracle { function getPriceUSD(address _asset) external view returns (uint256 price); function getPricesUSD(address[] calldata _assets) external view returns (uint256[] memory prices); // admin functions function updateFeedETH(address _asset, address _feed) external; function updateFeedUSD(address _asset, address _feed) external; function setSushiKeeperOracle(address _sushiOracle) external; function setUniKeeperOracle(address _uniOracle) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address payable) { address payable addr; require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); // solhint-disable-next-line no-inline-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) ); return address(uint160(uint256(_data))); } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version 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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; 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. * @author crypto-pumpkin * * By initialization, the owner account will be the one that called initializeOwner. 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 Initializable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Ruler: Initializes the contract setting the deployer as the initial owner. */ function initializeOwner() internal initializer { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_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.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; function initializeReentrancyGuard () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
deposit collateral to a Ruler Pair, sender receives rcTokens and rrTokens receive collateral mint rTokens for reveiced collateral
function deposit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt ) public override onlyNotPaused nonReentrant { Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio]; _validateDepositInputs(_col, pair); IERC20 collateral = IERC20(_col); uint256 colBalBefore = collateral.balanceOf(address(this)); collateral.safeTransferFrom(msg.sender, address(this), _colAmt); uint256 received = collateral.balanceOf(address(this)) - colBalBefore; require(received > 0, "Ruler: transfer failed"); pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal + received; uint256 mintAmount = _getRTokenAmtFromColAmt(received, _col, _paired, pair.mintRatio); pair.rcToken.mint(msg.sender, mintAmount); pair.rrToken.mint(msg.sender, mintAmount); emit Deposit(msg.sender, _col, _paired, _expiry, _mintRatio, received); }
509,718
contract SoccerBet { enum Team { A, B } struct BettingParty { Team bettedTeam; uint amount; address account; } BettingParty A; BettingParty B; address oracle; uint spareAmount; function SoccerBet(address bettingPartyA, address bettingPartyB) { oracle = msg.sender; A.account = bettingPartyA; B.account = bettingPartyB; A.amount = 0; B.amount = 0; spareAmount = msg.value; } function depositFunds(Team t) { if (msg.sender == A.account) { //Is the caller betting party A A.amount += msg.value; A.bettedTeam = t; } else if (msg.sender == B.account) { //Or is the caller betting party B B.amount += msg.value; B.bettedTeam = t; } else { //Just in off chance someone sent some money to this account, //lets store it and distribute it to the winner spareAmount += msg.value; } } /** * We are going to allow setting of the outcome as long as * one party has deposited money. It is upon the Oracle to not * set the outcome of the contract before both parties have * gotten a chance to deposit money. * */ function setOutcome(Team t, uint8 posession) { //We just need to calculate the losing party's earnings uint loserEarnings = 0; //Send money logic here //Winner gets money of the losing party * posession of winning side / 100 if (A.bettedTeam == t) { loserEarnings = B.amount - (B.amount * posession/100); B.account.send(loserEarnings); //Kill the contract, and send all the money to the winner, which is: //B.amount * (1 - posession)/100 suicide(A.account); } else if (B.bettedTeam == t) { loserEarnings = A.amount - (A.amount * posession/100); A.account.send(loserEarnings); //Kill the contract, and send all the money to the winner, which is: //A.amount * (1 - posession)/100 suicide(B.account); } } }
Is the caller betting party AOr is the caller betting party BJust in off chance someone sent some money to this account,lets store it and distribute it to the winner
function depositFunds(Team t) { if (msg.sender == A.account) { A.amount += msg.value; A.bettedTeam = t; B.amount += msg.value; B.bettedTeam = t; spareAmount += msg.value; } }
2,488,346
./full_match/5/0x9bd74652Dcac567963f4c18E99F715CcCF597784/sources/project_/contracts/piMarket.sol
Fetches the collection validator royalty. _collectionAddress The address of the collection. _tokenId The Id of the token./
function getCollectionValidatorRoyalty( address _collectionAddress, uint256 _tokenId ) public view returns (LibShare.Share[] memory) { return CollectionMethods(_collectionAddress).getValidatorRoyalties( _tokenId ); }
1,864,127
./full_match/1/0x25127685dC35d4dc96C7fEAC7370749d004C5040/sources/unibot_token.sol
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; }
17,004,628
./full_match/3/0x1AEf93FCB062b44F7F609E71A8f204AA91ec626D/sources/contracts/UniswapV2Router02.sol
bytes4(keccak256(bytes('approve(address,uint256)')));
function safeApprove(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); }
8,235,298
./partial_match/4/0xA9db4aDEC65723826f56524AE5520ba11b47482D/sources/contracts/utils/libraries/EnumerableSet.sol
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)))); }
8,535,750
./partial_match/1/0xbA1D34B9daae6370b09360B19910e93A60E1345e/sources/HokkPremium.sol
send to amount to caller
function withdrawUSDCFunds(uint256 amount) public { require(myUSDCDeposit[msg.sender] > 0, "Deposit amount must be greater than 0"); require(myUSDCLockupPeriod[msg.sender] < block.timestamp, "Lockup has not expired"); require(myUSDCDeposit[msg.sender] >= amount, "Insufficient amount"); myUSDCDeposit[msg.sender] = myUSDCDeposit[msg.sender].sub(amount); totalUSDCDeposit = totalUSDCDeposit.sub(amount); }
15,680,145
./partial_match/1/0x25fF2FdE7df1A433E09749C952f7e09aD3C27951/sources/contracts/NounsDescriptorV2.sol
Given a token ID and seed, construct a base64 encoded data URI for an official Nouns DAO noun./
function dataURI(uint256 tokenId, INounsSeeder.Seed memory seed) public view override returns (string memory) { string memory nounId = tokenId.toString(); string memory name = string(abi.encodePacked('Noun ', nounId)); string memory description = string(abi.encodePacked('Noun ', nounId, ' is a member of the Nouns DAO')); return genericDataURI(name, description, seed); }
4,259,345
./partial_match/5/0xb9C126bEA56df1eDd3e0aBc2AFA753C7EB73a1E0/sources/DeporDEAO.sol
add haspledgeUota if(userCurrentPledgeQuota[_sellerAddr].hasUsedQuota >= )
function buyToken(address _sellerAddr, uint256 _needBuy) public { uint256 senderAvailableUSDT = usdt.balanceOf(msg.sender); uint256 needUSDT = _needBuy.mul(dpoPriceIn1000).div(1000); require(senderAvailableUSDT >= needUSDT, "Not Enough USDT for buy DPO"); uint256 sellerId; uint256 sellerLevel; uint256 sellerDcp; (sellerId, , , , sellerLevel, sellerDcp, , , ) = userBook .queryUserByAddr(_sellerAddr); require(sellerId != 0, "agent not exists"); uint256 sellerRewardUSDTAmount = needUSDT.mul(returnRate[sellerLevel]).div(1000); uint256 usdtToDepor = needUSDT.sub(sellerRewardUSDTAmount); if (userCurrentPledgeQuota[_sellerAddr].state == 1) { if ( block.number - userCurrentPledgeQuota[_sellerAddr].startBlock >= userCurrentPledgeQuota[_sellerAddr].expireBlock ) { userCurrentPledgeQuota[_sellerAddr].state = 2; uint256 effectDCP = userCurrentPledgeQuota[_sellerAddr].effectDCP; userBook.subUserDCP(_sellerAddr, effectDCP); dcpRecorder.recordDCPSub(_sellerAddr, effectDCP); } require( queryUserTotalCanSellAmount(_sellerAddr) >= _needBuy, "Total Quota not enought!" ); uint256 _userPledgeCanSellAmount = queryUserPledgeCanSellAmount(_sellerAddr); if (_userPledgeCanSellAmount >= _needBuy) { userCurrentPledgeQuota[_sellerAddr].hasUsedQuota = userCurrentPledgeQuota[_sellerAddr].hasUsedQuota + _needBuy; if (_userPledgeCanSellAmount == _needBuy) { userCurrentPledgeQuota[_sellerAddr].state = 3; userBook.addUserDCP( _sellerAddr, userCurrentPledgeQuota[_sellerAddr].effectDCP ); dcpRecorder.recordDCPAdd( _sellerAddr, userCurrentPledgeQuota[_sellerAddr].effectDCP ); } .hasUsedQuota = _userPledgeCanSellAmount.add( userCurrentPledgeQuota[_sellerAddr].hasUsedQuota ); uint256 useCreditPledgeQuota = _needBuy.sub(_userPledgeCanSellAmount); hasUserCreditPledgeQuota[_sellerAddr][ sellerLevel ] = useCreditPledgeQuota.add( hasUserCreditPledgeQuota[_sellerAddr][sellerLevel] ); if (userCurrentPledgeQuota[_sellerAddr].state == 1) { userCurrentPledgeQuota[_sellerAddr].state = 3; if (_userPledgeCanSellAmount > 0) { userBook.addUserDCP( _sellerAddr, userCurrentPledgeQuota[_sellerAddr].effectDCP ); dcpRecorder.recordDCPAdd( _sellerAddr, userCurrentPledgeQuota[_sellerAddr].effectDCP ); } } } require( _needBuy <= queryUserCreditCanSellAmount(_sellerAddr), "credit Quota Not enough!" ); hasUserCreditPledgeQuota[_sellerAddr][sellerLevel] = _needBuy.add( hasUserCreditPledgeQuota[_sellerAddr][sellerLevel] ); } usdt.transferFrom(msg.sender, _sellerAddr, sellerRewardUSDTAmount); deaoRecorder.recordDPOSell( msg.sender, _sellerAddr, sellerRewardUSDTAmount, _needBuy, sellerLevel ); }
16,839,206
pragma solidity ^0.6.0; import "./BeaconContract.sol"; contract Beacon{ function getLatestRandomness()external view returns(uint256,bytes32){} } contract FusionLedgerTimeSeriesOracle { address public oracleAddress; address public BeaconContractAddress=0x79474439753C7c70011C3b00e06e559378bAD040; constructor (address _oracleAddress) public { oracleAddress = _oracleAddress; } function setBeaconContractAddress(address _address) public { BeaconContractAddress=_address; } function generateRandomNumber() public view returns(bytes32){ uint blockNumber; bytes32 randomNumber; Beacon beacon=Beacon(BeaconContractAddress); (blockNumber,randomNumber)=beacon.getLatestRandomness(); return randomNumber; } //Time Series Average Index uint public time_series_average_number; //function setting Time Series Avarge from the Data Source function setTimeSeriesAverage(uint _number) public { time_series_average_number = block.timestamp + _number; } //getter for the Time Sries Average Index function getTimeSeriesAverage() public view returns (uint) { require(msg.sender == oracleAddress); if ((bytes32(block.number))> generateRandomNumber()) { return time_series_average_number; } } }
getter for the Time Sries Average Index
function getTimeSeriesAverage() public view returns (uint) { require(msg.sender == oracleAddress); if ((bytes32(block.number))> generateRandomNumber()) { return time_series_average_number; } }
13,077,579
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./interfaces/IPoolFactory.sol"; import "./interfaces/IPoolMaster.sol"; import "./interfaces/IAuction.sol"; import "./libraries/Decimal.sol"; contract Auction is IAuction, ERC721Upgradeable, OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using Decimal for uint256; /// @notice PoolFactory contract IPoolFactory public factory; /// @notice Debt auction duration (in seconds) uint256 public auctionDuration; /// @notice Minimal ratio of initial bid to pool insurance (as 18-digit decimal) uint256 public minBidFactor; /// @notice Mapping of addresses to flags if they are whitelisted bidders mapping(address => bool) public isWhitelistedBidder; struct AuctionInfo { uint256 end; uint96 tokenId; address lastBidder; uint256 lastBid; } /// @notice Mapping of pool addresses to their debt auction info mapping(address => AuctionInfo) public auctionInfo; struct TokenInfo { address pool; uint256 borrowsAtClaim; uint256 interestRate; } /// @notice Mapping of token IDs to their token info mapping(uint256 => TokenInfo) public tokenInfo; /// @notice Last token ID uint96 public lastTokenId; // EVENTS /// @notice Event emitted when debt auction is started for some pool event AuctionStarted(address indexed pool, address indexed bidder); /// @notice Event emitted when bid is placed for some pool event Bid(address indexed pool, address indexed bidder, uint256 amount); /// @notice Event emitted when some address status as whitelisted bidder is changed event WhitelistedBidderSet(address bidder, bool whitelisted); /// @notice Event emitted when auction duration is set event AuctionDurationSet(uint256 duration); // CONSTRUCTOR /** * @notice Upgradeable contract constructor * @param factory_ Address of the PoolFactory * @param auctionDuration_ Auction duration value * @param minBidFactor_ Min bid factor value */ function initialize( address factory_, uint256 auctionDuration_, uint256 minBidFactor_ ) external initializer { __Ownable_init(); __ERC721_init("Clearpool Debt", "CPDEBT"); factory = IPoolFactory(factory_); auctionDuration = auctionDuration_; minBidFactor = minBidFactor_; } // PUBLIC FUNCTIONS /// @notice Makes a bid on a pool /// @param pool Address of a pool /// @param amount Amount of the bid function bid(address pool, uint256 amount) external { require(factory.isPool(pool), "PNE"); require(isWhitelistedBidder[msg.sender], "NWB"); if (auctionInfo[pool].lastBidder == address(0)) { _startAuction(pool, amount); } require(block.timestamp < auctionInfo[pool].end, "AF"); require(amount > auctionInfo[pool].lastBid, "NBG"); IERC20Upgradeable currency = IERC20Upgradeable( IPoolMaster(pool).currency() ); if (auctionInfo[pool].lastBidder != address(0)) { currency.safeTransfer( auctionInfo[pool].lastBidder, auctionInfo[pool].lastBid ); } currency.safeTransferFrom(msg.sender, address(this), amount); auctionInfo[pool].lastBidder = msg.sender; auctionInfo[pool].lastBid = amount; emit Bid(pool, msg.sender, amount); } /// @notice Claims ownership of a pool if caller has won a auction /// @param pool Address of a pool function claimDebtOwnership(address pool) external { require(block.timestamp >= auctionInfo[pool].end, "ANF"); require(auctionInfo[pool].tokenId == 0, "AC"); require(msg.sender == auctionInfo[pool].lastBidder, "NLB"); lastTokenId++; _mint(msg.sender, lastTokenId); tokenInfo[lastTokenId] = TokenInfo({ pool: pool, borrowsAtClaim: IPoolMaster(pool).borrows(), interestRate: IPoolMaster(pool).getBorrowRate() }); auctionInfo[pool].tokenId = lastTokenId; IPoolMaster(pool).processDebtClaim(); IERC20Upgradeable(IPoolMaster(pool).currency()).safeTransfer( pool, auctionInfo[pool].lastBid ); } // RESTRICTED FUNCTIONS /// @notice Function is used to set whitelisted status for some bidder (restricted to owner) /// @param bidder Address of the bidder /// @param whitelisted True if bidder should be whitelisted false otherwise function setWhitelistedBidder(address bidder, bool whitelisted) external onlyOwner { isWhitelistedBidder[bidder] = whitelisted; emit WhitelistedBidderSet(bidder, whitelisted); } /// @notice Function is used to set new value for auction duration /// @param auctionDuration_ Auction duration in seconds function setAuctionDuration(uint256 auctionDuration_) external onlyOwner { auctionDuration = auctionDuration_; emit AuctionDurationSet(auctionDuration_); } // VIEW FUNCTIONS /// @notice Returns owner of a debt /// @param pool Address of a pool /// @return Address of the owner function ownerOfDebt(address pool) external view returns (address) { return auctionInfo[pool].tokenId != 0 ? ownerOf(auctionInfo[pool].tokenId) : address(0); } /// @notice Returns state of a pool auction /// @param pool Address of a pool /// @return state of a pool auction function state(address pool) external view returns (State) { if (IPoolMaster(pool).state() != IPoolMaster.State.Default) { return State.None; } else if (auctionInfo[pool].lastBidder == address(0)) { return State.NotStarted; } else if (block.timestamp < auctionInfo[pool].end) { return State.Active; } else if ( block.timestamp >= auctionInfo[pool].end && auctionInfo[pool].tokenId == 0 ) { return State.Finished; } else { return State.Closed; } } // PRIVATE FUNCTIONS /// @notice Private function that starts auction for a pool /// @param poolAddress Address of the pool function _startAuction(address poolAddress, uint256 amount) private { IPoolMaster pool = IPoolMaster(poolAddress); require(pool.state() == IPoolMaster.State.Default, "NID"); require(amount >= pool.insurance().mulDecimal(minBidFactor), "LMB"); pool.processAuctionStart(); auctionInfo[poolAddress].end = block.timestamp + auctionDuration; emit AuctionStarted(poolAddress, msg.sender); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IPoolFactory { function getPoolSymbol(address currency, address manager) external view returns (string memory); function isPool(address pool) external view returns (bool); function interestRateModel() external view returns (address); function auction() external view returns (address); function treasury() external view returns (address); function reserveFactor() external view returns (uint256); function insuranceFactor() external view returns (uint256); function warningUtilization() external view returns (uint256); function provisionalDefaultUtilization() external view returns (uint256); function warningGracePeriod() external view returns (uint256); function maxInactivePeriod() external view returns (uint256); function periodToStartAuction() external view returns (uint256); function owner() external view returns (address); function closePool() external; function burnStake() external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IPoolMaster { function manager() external view returns (address); function currency() external view returns (address); function borrows() external view returns (uint256); function insurance() external view returns (uint256); function getBorrowRate() external view returns (uint256); function getSupplyRate() external view returns (uint256); enum State { Active, Warning, ProvisionalDefault, Default, Closed } function state() external view returns (State); function initialize(address manager_, address currency_) external; function setRewardPerBlock(uint256 rewardPerBlock_) external; function withdrawReward(address account) external returns (uint256); function transferReserves() external; function processAuctionStart() external; function processDebtClaim() external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface IAuction { function bid(address pool, uint256 amount) external; function ownerOfDebt(address pool) external view returns (address); /// @notice States of auction /// @dev None: A pool is not default and auction can't be started /// @dev NotStarted: A pool is default and auction can be started /// @dev Active: An auction is started /// @dev Finished: An auction is finished but NFT is not claimed /// @dev Closed: An auction is finished and NFT is claimed enum State { None, NotStarted, Active, Finished, Closed } function state(address pool) external view returns (State); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; library Decimal { /// @notice Number one as 18-digit decimal uint256 internal constant ONE = 1e18; /** * @notice Internal function for 10-digits decimal division * @param number Integer number * @param decimal Decimal number * @return Returns multiplied numbers */ function mulDecimal(uint256 number, uint256 decimal) internal pure returns (uint256) { return (number * decimal) / ONE; } /** * @notice Internal function for 10-digits decimal multiplication * @param number Integer number * @param decimal Decimal number * @return Returns integer number divided by second */ function divDecimal(uint256 number, uint256 decimal) internal pure returns (uint256) { return (number * ONE) / decimal; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Claims ownership of a pool if caller has won a auction pool Address of a pool
function claimDebtOwnership(address pool) external { require(block.timestamp >= auctionInfo[pool].end, "ANF"); require(auctionInfo[pool].tokenId == 0, "AC"); require(msg.sender == auctionInfo[pool].lastBidder, "NLB"); lastTokenId++; _mint(msg.sender, lastTokenId); tokenInfo[lastTokenId] = TokenInfo({ pool: pool, borrowsAtClaim: IPoolMaster(pool).borrows(), interestRate: IPoolMaster(pool).getBorrowRate() }); auctionInfo[pool].tokenId = lastTokenId; IPoolMaster(pool).processDebtClaim(); IERC20Upgradeable(IPoolMaster(pool).currency()).safeTransfer( pool, auctionInfo[pool].lastBid ); }
5,857,804
./partial_match/1/0x56bc8603C801ad8703E53E7De63F5BbC61d4EE2e/sources/GoldenVoyagerParty.sol
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); pragma solidity >=0.6.0 <0.8.0; }
4,463,474
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface Proxy { function UPGRADETO703(address newImplementation) external; //inject NONSTANDARD NAMING } contract sbUpgrader { event UPGRADED524(address indexed proxyAddress, address indexed implementationAddress); //inject NONSTANDARD NAMING address public admin; address public pendingAdmin; address public superAdmin; address public pendingSuperAdmin; constructor(address adminAddress, address superAdminAddress) public { admin = adminAddress; superAdmin = superAdminAddress; } // ADMIN // ************************************************************************************* function SETPENDINGADMIN799(address newPendingAdmin) public { //inject NONSTANDARD NAMING require(msg.sender == admin, 'not admin'); pendingAdmin = newPendingAdmin; } function ACCEPTADMIN491() public { //inject NONSTANDARD NAMING require(msg.sender == pendingAdmin && msg.sender != address(0), 'not pendingAdmin'); admin = pendingAdmin; pendingAdmin = address(0); } function SETPENDINGSUPERADMIN182(address newPendingSuperAdmin) public { //inject NONSTANDARD NAMING require(msg.sender == superAdmin, 'not superAdmin'); pendingSuperAdmin = newPendingSuperAdmin; } function ACCEPTSUPERADMIN116() public { //inject NONSTANDARD NAMING require(msg.sender == pendingSuperAdmin && msg.sender != address(0), 'not pendingSuperAdmin'); superAdmin = pendingSuperAdmin; pendingSuperAdmin = address(0); } // UPGRADE // ************************************************************************************* function UPGRADE150(address proxyAddress, address implementationAddress) external { //inject NONSTANDARD NAMING require(msg.sender == admin || msg.sender == superAdmin, 'not admin'); Proxy proxy = Proxy(proxyAddress); proxy.UPGRADETO703(implementationAddress); emit UPGRADED524(proxyAddress, implementationAddress); } }
inject NONSTANDARD NAMING
function SETPENDINGSUPERADMIN182(address newPendingSuperAdmin) public {
12,611,261
/* * Copyright 2020 ConsenSys Software Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.7.1; contract PriceOracle { uint256 price; address owner; constructor() { owner = msg.sender; } /** * Set the price. This is a not-lockable location. As such, this must only be set as * part of a single-blockchain call. * * @param _newPrice updated price */ function setPrice(uint256 _newPrice) external { require(owner == msg.sender, "Only owner"); price = _newPrice; } function getPrice() external view returns (uint256) { return price; } }
Set the price. This is a not-lockable location. As such, this must only be set as part of a single-blockchain call. _newPrice updated price/
function setPrice(uint256 _newPrice) external { require(owner == msg.sender, "Only owner"); price = _newPrice; }
12,600,142
// Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] // MIT 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/token/ERC20/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/MVM/iMVM_DiscountOracle.sol // MIT pragma solidity ^0.8.9; interface iMVM_DiscountOracle{ function setDiscount( uint256 _discount ) external; function setMinL2Gas( uint256 _minL2Gas ) external; function setWhitelistedXDomainSender( address _sender, bool _isWhitelisted ) external; function isXDomainSenderAllowed( address _sender ) view external returns(bool); function setAllowAllXDomainSenders( bool _allowAllXDomainSenders ) external; function getMinL2Gas() view external returns(uint256); function getDiscount() view external returns(uint256); function processL2SeqGas(address sender, uint256 _chainId) external payable; } // File contracts/libraries/resolver/Lib_AddressManager.sol // MIT pragma solidity ^0.8.9; /* External Imports */ /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet(string indexed _name, address _newAddress, address _oldAddress); /************* * Variables * *************/ mapping(bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress(string memory _name, address _address) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet(_name, _address, oldAddress); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress(string memory _name) external view returns (address) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash(string memory _name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_name)); } } // File contracts/libraries/resolver/Lib_AddressResolver.sol // MIT pragma solidity ^0.8.9; /* Library Imports */ /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor(address _libAddressManager) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve(string memory _name) public view returns (address) { return libAddressManager.getAddress(_name); } } // File contracts/libraries/rlp/Lib_RLPReader.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 internal constant MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory) { (uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value."); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require(itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length."); (uint256 itemOffset, uint256 itemLength, ) = _decodeLength( RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset }) ); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList(bytes memory _in) internal pure returns (RLPItem[] memory) { return readList(toRLPItem(_in)); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(RLPItem memory _in) internal pure returns (bytes memory) { (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value."); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes(bytes memory _in) internal pure returns (bytes memory) { return readBytes(toRLPItem(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(RLPItem memory _in) internal pure returns (string memory) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString(bytes memory _in) internal pure returns (string memory) { return readString(toRLPItem(_in)); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(RLPItem memory _in) internal pure returns (bytes32) { require(_in.length <= 33, "Invalid RLP bytes32 value."); (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in); require(itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value."); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32(bytes memory _in) internal pure returns (bytes32) { return readBytes32(toRLPItem(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(RLPItem memory _in) internal pure returns (uint256) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256(bytes memory _in) internal pure returns (uint256) { return readUint256(toRLPItem(_in)); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(RLPItem memory _in) internal pure returns (bool) { require(_in.length == 1, "Invalid RLP boolean value."); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require(out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool(bytes memory _in) internal pure returns (bool) { return readBool(toRLPItem(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(RLPItem memory _in) internal pure returns (address) { if (_in.length == 1) { return address(0); } require(_in.length == 21, "Invalid RLP address value."); return address(uint160(readUint256(_in))); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress(bytes memory _in) internal pure returns (address) { return readAddress(toRLPItem(_in)); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength(RLPItem memory _in) private pure returns ( uint256, uint256, RLPItemType ) { require(_in.length > 0, "RLP item cannot be null."); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require(_in.length > strLen, "Invalid RLP short string."); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require(_in.length > lenOfStrLen, "Invalid RLP long string length."); uint256 strLen; assembly { // Pick out the string length. strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen))) } require(_in.length > lenOfStrLen + strLen, "Invalid RLP long string."); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require(_in.length > listLen, "Invalid RLP short list."); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require(_in.length > lenOfListLen, "Invalid RLP long list length."); uint256 listLen; assembly { // Pick out the list length. listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen))) } require(_in.length > lenOfListLen + listLen, "Invalid RLP long list."); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns (bytes memory) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask; unchecked { mask = 256**(32 - (_length % 32)) - 1; } assembly { mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask))) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy(RLPItem memory _in) private pure returns (bytes memory) { return _copy(_in.ptr, 0, _in.length); } } // File contracts/libraries/rlp/Lib_RLPWriter.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes(bytes memory _in) internal pure returns (bytes memory) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList(bytes[] memory _in) internal pure returns (bytes memory) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString(string memory _in) internal pure returns (bytes memory) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress(address _in) internal pure returns (bytes memory) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint(uint256 _in) internal pure returns (bytes memory) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool(bool _in) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = bytes1(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55); for (i = 1; i <= lenLen; i++) { encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary(uint256 _x) private pure returns (bytes memory) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask; unchecked { mask = 256**(32 - len) - 1; } assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for (i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20) } _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // File contracts/libraries/utils/Lib_BytesUtils.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_start + _length >= _start, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) { if (_start >= _bytes.length) { return bytes(""); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32(bytes memory _bytes) internal pure returns (bytes32) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes } function toUint256(bytes memory _bytes) internal pure returns (uint256) { return uint256(toBytes32(_bytes)); } function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles(bytes memory _bytes) internal pure returns (bytes memory) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } } // File contracts/libraries/utils/Lib_Bytes32Utils.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool(bytes32 _in) internal pure returns (bool) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool(bool _in) internal pure returns (bytes32) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress(bytes32 _in) internal pure returns (address) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress(address _in) internal pure returns (bytes32) { return bytes32(uint256(uint160(_in))); } } // File contracts/libraries/codec/Lib_OVMCodec.sol // MIT pragma solidity ^0.8.9; /* Library Imports */ /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction(Transaction memory _transaction) internal pure returns (bytes memory) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction(Transaction memory _transaction) internal pure returns (bytes32) { return keccak256(encodeTransaction(_transaction)); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount(bytes memory _encoded) internal pure returns (EVMAccount memory) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) internal pure returns (bytes32) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // File contracts/libraries/utils/Lib_MerkleTree.sol // MIT pragma solidity ^0.8.9; /** * @title Lib_MerkleTree * @author River Keefer */ library Lib_MerkleTree { /********************** * Internal Functions * **********************/ /** * Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number * of leaves passed in is not a power of two, it pads out the tree with zero hashes. * If you do not know the original length of elements for the tree you are verifying, then * this may allow empty leaves past _elements.length to pass a verification check down the line. * Note that the _elements argument is modified, therefore it must not be used again afterwards * @param _elements Array of hashes from which to generate a merkle root. * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). */ function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) { require(_elements.length > 0, "Lib_MerkleTree: Must provide at least one leaf hash."); if (_elements.length == 1) { return _elements[0]; } uint256[16] memory defaults = [ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563, 0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d, 0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d, 0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8, 0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da, 0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5, 0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7, 0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead, 0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10, 0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82, 0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516, 0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c, 0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e, 0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab, 0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862, 0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10 ]; // Reserve memory space for our hashes. bytes memory buf = new bytes(64); // We'll need to keep track of left and right siblings. bytes32 leftSibling; bytes32 rightSibling; // Number of non-empty nodes at the current depth. uint256 rowSize = _elements.length; // Current depth, counting from 0 at the leaves uint256 depth = 0; // Common sub-expressions uint256 halfRowSize; // rowSize / 2 bool rowSizeIsOdd; // rowSize % 2 == 1 while (rowSize > 1) { halfRowSize = rowSize / 2; rowSizeIsOdd = rowSize % 2 == 1; for (uint256 i = 0; i < halfRowSize; i++) { leftSibling = _elements[(2 * i)]; rightSibling = _elements[(2 * i) + 1]; assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[i] = keccak256(buf); } if (rowSizeIsOdd) { leftSibling = _elements[rowSize - 1]; rightSibling = bytes32(defaults[depth]); assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[halfRowSize] = keccak256(buf); } rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0); depth++; } return _elements[0]; } /** * Verifies a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _root The Merkle root to verify against. * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 * (bottom of the tree). * @param _totalLeaves The total number of leaves originally passed into. * @return Whether or not the merkle branch and leaf passes verification. */ function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) internal pure returns (bool) { require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero."); require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds."); require( _siblings.length == _ceilLog2(_totalLeaves), "Lib_MerkleTree: Total siblings does not correctly correspond to total leaves." ); bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot)); } else { computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i])); } _index >>= 1; } return _root == computedRoot; } /********************* * Private Functions * *********************/ /** * Calculates the integer ceiling of the log base 2 of an input. * @param _in Unsigned input to calculate the log. * @return ceil(log_base_2(_in)) */ function _ceilLog2(uint256 _in) private pure returns (uint256) { require(_in > 0, "Lib_MerkleTree: Cannot compute ceil(log_2) of 0."); if (_in == 1) { return 0; } // Find the highest set bit (will be floor(log_2)). // Borrowed with <3 from https://github.com/ethereum/solidity-examples uint256 val = _in; uint256 highest = 0; for (uint256 i = 128; i >= 1; i >>= 1) { if (val & (((uint256(1) << i) - 1) << i) != 0) { highest += i; val >>= i; } } // Increment by one if this is not a perfect logarithm. if ((uint256(1) << highest) != _in) { highest += 1; } return highest; } } // File contracts/L1/rollup/IChainStorageContainer.sol // MIT pragma solidity >0.5.0 <0.9.0; /** * @title IChainStorageContainer */ interface IChainStorageContainer { /******************** * Public Functions * ********************/ /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadata(bytes27 _globalMetadata) external; /** * Retrieves the container's global metadata field. * @return Container global metadata field. */ function getGlobalMetadata() external view returns (bytes27); /** * Retrieves the number of objects stored in the container. * @return Number of objects in the container. */ function length() external view returns (uint256); /** * Pushes an object into the container. * @param _object A 32 byte value to insert into the container. */ function push(bytes32 _object) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function push(bytes32 _object, bytes27 _globalMetadata) external; /** * Set an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _index position. * @param _object A 32 byte value to insert into the container. */ function setByChainId( uint256 _chainId, uint256 _index, bytes32 _object ) external; /** * Retrieves an object from the container. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function get(uint256 _index) external view returns (bytes32); /** * Removes all objects after and including a given index. * @param _index Object index to delete from. */ function deleteElementsAfterInclusive(uint256 _index) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata) external; /** * Sets the container's global metadata field. We're using `bytes27` here because we use five * bytes to maintain the length of the underlying data structure, meaning we have an extra * 27 bytes to store arbitrary data. * @param _chainId identity for the l2 chain. * @param _globalMetadata New global metadata to set. */ function setGlobalMetadataByChainId( uint256 _chainId, bytes27 _globalMetadata ) external; /** * Retrieves the container's global metadata field. * @param _chainId identity for the l2 chain. * @return Container global metadata field. */ function getGlobalMetadataByChainId( uint256 _chainId ) external view returns ( bytes27 ); /** * Retrieves the number of objects stored in the container. * @param _chainId identity for the l2 chain. * @return Number of objects in the container. */ function lengthByChainId( uint256 _chainId ) external view returns ( uint256 ); /** * Pushes an object into the container. * @param _chainId identity for the l2 chain. * @param _object A 32 byte value to insert into the container. */ function pushByChainId( uint256 _chainId, bytes32 _object ) external; /** * Pushes an object into the container. Function allows setting the global metadata since * we'll need to touch the "length" storage slot anyway, which also contains the global * metadata (it's an optimization). * @param _chainId identity for the l2 chain. * @param _object A 32 byte value to insert into the container. * @param _globalMetadata New global metadata for the container. */ function pushByChainId( uint256 _chainId, bytes32 _object, bytes27 _globalMetadata ) external; /** * Retrieves an object from the container. * @param _chainId identity for the l2 chain. * @param _index Index of the particular object to access. * @return 32 byte object value. */ function getByChainId( uint256 _chainId, uint256 _index ) external view returns ( bytes32 ); /** * Removes all objects after and including a given index. * @param _chainId identity for the l2 chain. * @param _index Object index to delete from. */ function deleteElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index ) external; /** * Removes all objects after and including a given index. Also allows setting the global * metadata field. * @param _chainId identity for the l2 chain. * @param _index Object index to delete from. * @param _globalMetadata New global metadata for the container. */ function deleteElementsAfterInclusiveByChainId( uint256 _chainId, uint256 _index, bytes27 _globalMetadata ) external; } // File contracts/L1/rollup/IStateCommitmentChain.sol // MIT pragma solidity >0.5.0 <0.9.0; /* Library Imports */ /** * @title IStateCommitmentChain */ interface IStateCommitmentChain { /********** * Events * **********/ event StateBatchAppended( uint256 _chainId, uint256 indexed _batchIndex, bytes32 _batchRoot, uint256 _batchSize, uint256 _prevTotalElements, bytes _extraData ); event StateBatchDeleted( uint256 _chainId, uint256 indexed _batchIndex, bytes32 _batchRoot ); /******************** * Public Functions * ********************/ function batches() external view returns (IChainStorageContainer); /** * Retrieves the total number of elements submitted. * @return _totalElements Total submitted elements. */ function getTotalElements() external view returns (uint256 _totalElements); /** * Retrieves the total number of batches submitted. * @return _totalBatches Total submitted batches. */ function getTotalBatches() external view returns (uint256 _totalBatches); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestamp() external view returns (uint256 _lastSequencerTimestamp); /** * Appends a batch of state roots to the chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatch(bytes32[] calldata _batch, uint256 _shouldStartAtElement) external; /** * Deletes all state roots after (and including) a given batch. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external; /** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns (bool _verified); /** * Checks whether a given batch is still inside its fraud proof window. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) external view returns ( bool _inside ); /******************** * chain id added func * ********************/ /** * Retrieves the total number of elements submitted. * @param _chainId identity for the l2 chain. * @return _totalElements Total submitted elements. */ function getTotalElementsByChainId(uint256 _chainId) external view returns ( uint256 _totalElements ); /** * Retrieves the total number of batches submitted. * @param _chainId identity for the l2 chain. * @return _totalBatches Total submitted batches. */ function getTotalBatchesByChainId(uint256 _chainId) external view returns ( uint256 _totalBatches ); /** * Retrieves the timestamp of the last batch submitted by the sequencer. * @param _chainId identity for the l2 chain. * @return _lastSequencerTimestamp Last sequencer batch timestamp. */ function getLastSequencerTimestampByChainId(uint256 _chainId) external view returns ( uint256 _lastSequencerTimestamp ); /** * Appends a batch of state roots to the chain. * @param _chainId identity for the l2 chain. * @param _batch Batch of state roots. * @param _shouldStartAtElement Index of the element at which this batch should start. */ function appendStateBatchByChainId( uint256 _chainId, bytes32[] calldata _batch, uint256 _shouldStartAtElement, string calldata proposer ) external; /** * Deletes all state roots after (and including) a given batch. * @param _chainId identity for the l2 chain. * @param _batchHeader Header of the batch to start deleting from. */ function deleteStateBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external; /** * Verifies a batch inclusion proof. * @param _chainId identity for the l2 chain. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */ function verifyStateCommitmentByChainId( uint256 _chainId, bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) external view returns ( bool _verified ); /** * Checks whether a given batch is still inside its fraud proof window. * @param _chainId identity for the l2 chain. * @param _batchHeader Header of the batch to check. * @return _inside Whether or not the batch is inside the fraud proof window. */ function insideFraudProofWindowByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) external view returns ( bool _inside ); } // File contracts/MVM/MVM_Verifier.sol // MIT pragma solidity ^0.8.9; /* Contract Imports */ /* External Imports */ contract MVM_Verifier is Lib_AddressResolver{ // second slot address public metis; enum SETTLEMENT {NOT_ENOUGH_VERIFIER, SAME_ROOT, AGREE, DISAGREE, PASS} event NewChallenge(uint256 cIndex, uint256 chainID, Lib_OVMCodec.ChainBatchHeader header, uint256 timestamp); event Verify1(uint256 cIndex, address verifier); event Verify2(uint256 cIndex, address verifier); event Finalize(uint256 cIndex, address sender, SETTLEMENT result); event Penalize(address sender, uint256 stakeLost); event Reward(address target, uint256 amount); event Claim(address sender, uint256 amount); event Withdraw(address sender, uint256 amount); event Stake(address verifier, uint256 amount); event SlashSequencer(uint256 chainID, address seq); /************* * Constants * *************/ string constant public CONFIG_OWNER_KEY = "METIS_MANAGER"; //challenge info struct Challenge { address challenger; uint256 chainID; uint256 index; Lib_OVMCodec.ChainBatchHeader header; uint256 timestamp; uint256 numQualifiedVerifiers; uint256 numVerifiers; address[] verifiers; bool done; } mapping (address => uint256) public verifier_stakes; mapping (uint256 => mapping (address=>bytes)) private challenge_keys; mapping (uint256 => mapping (address=>bytes)) private challenge_key_hashes; mapping (uint256 => mapping (address=>bytes)) private challenge_hashes; mapping (address => uint256) public rewards; mapping (address => uint8) public absence_strikes; mapping (address => uint8) public consensus_strikes; // only one active challenge for each chain chainid=>cIndex mapping (uint256 => uint256) public chain_under_challenge; // white list mapping (address => bool) public whitelist; bool useWhiteList; address[] public verifiers; Challenge[] public challenges; uint public verifyWindow = 3600 * 24; // 24 hours of window to complete the each verify phase uint public activeChallenges; uint256 public minStake; uint256 public seqStake; uint256 public numQualifiedVerifiers; uint FAIL_THRESHOLD = 2; // 1 time grace uint ABSENCE_THRESHOLD = 4; // 2 times grace modifier onlyManager { require( msg.sender == resolve(CONFIG_OWNER_KEY), "MVM_Verifier: Function can only be called by the METIS_MANAGER." ); _; } modifier onlyWhitelisted { require(isWhiteListed(msg.sender), "only whitelisted verifiers can call"); _; } modifier onlyStaked { require(isSufficientlyStaked(msg.sender), "insufficient stake"); _; } constructor( ) Lib_AddressResolver(address(0)) { } // add stake as a verifier function verifierStake(uint256 stake) public onlyWhitelisted{ require(activeChallenges == 0, "stake is currently prohibited"); //ongoing challenge require(stake > 0, "zero stake not allowed"); require(IERC20(metis).transferFrom(msg.sender, address(this), stake), "transfer metis failed"); uint256 previousBalance = verifier_stakes[msg.sender]; verifier_stakes[msg.sender] += stake; require(isSufficientlyStaked(msg.sender), "insufficient stake to qualify as a verifier"); if (previousBalance == 0) { numQualifiedVerifiers++; verifiers.push(msg.sender); } emit Stake(msg.sender, stake); } // start a new challenge // @param chainID chainid // @param header chainbatch header // @param proposedHash encrypted hash of the correct state // @param keyhash hash of the decryption key // // @dev why do we ask for key and keyhash? because we want verifiers compute the state instead // of just copying from other verifiers. function newChallenge(uint256 chainID, Lib_OVMCodec.ChainBatchHeader calldata header, bytes calldata proposedHash, bytes calldata keyhash) public onlyWhitelisted onlyStaked { uint tempIndex = chain_under_challenge[chainID] - 1; require(tempIndex == 0 || block.timestamp - challenges[tempIndex].timestamp > verifyWindow * 2, "there is an ongoing challenge"); if (tempIndex > 0) { finalize(tempIndex); } IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain")); // while the root is encrypted, the timestamp is available in the extradata field of the header require(stateChain.insideFraudProofWindow(header), "the batch is outside of the fraud proof window"); Challenge memory c; c.chainID = chainID; c.challenger = msg.sender; c.timestamp = block.timestamp; c.header = header; challenges.push(c); uint cIndex = challenges.length - 1; // house keeping challenge_hashes[cIndex][msg.sender] = proposedHash; challenge_key_hashes[cIndex][msg.sender] = keyhash; challenges[cIndex].numVerifiers++; // the challenger // this will prevent stake change activeChallenges++; chain_under_challenge[chainID] = cIndex + 1; // +1 because 0 means no in-progress challenge emit NewChallenge(cIndex, chainID, header, block.timestamp); } // phase 1 of the verify, provide an encrypted hash and the hash of the decryption key // @param cIndex index of the challenge // @param hash encrypted hash of the correct state (for the index referred in the challenge) // @param keyhash hash of the decryption key function verify1(uint256 cIndex, bytes calldata hash, bytes calldata keyhash) public onlyWhitelisted onlyStaked{ require(challenge_hashes[cIndex][msg.sender].length == 0, "verify1 already completed for the sender"); challenge_hashes[cIndex][msg.sender] = hash; challenge_key_hashes[cIndex][msg.sender] = keyhash; challenges[cIndex].numVerifiers++; emit Verify1(cIndex, msg.sender); } // phase 2 of the verify, provide the actual key to decrypt the hash // @param cIndex index of the challenge // @param key the decryption key function verify2(uint256 cIndex, bytes calldata key) public onlyStaked onlyWhitelisted{ require(challenges[cIndex].numVerifiers == numQualifiedVerifiers || block.timestamp - challenges[cIndex].timestamp > verifyWindow, "phase 2 not ready"); require(challenge_hashes[cIndex][msg.sender].length > 0, "you didn't participate in phase 1"); if (challenge_keys[cIndex][msg.sender].length > 0) { finalize(cIndex); return; } //verify whether the key matches the keyhash initially provided. require(sha256(key) == bytes32(challenge_key_hashes[cIndex][msg.sender]), "key and keyhash don't match"); if (msg.sender == challenges[cIndex].challenger) { //decode the root in the header too challenges[cIndex].header.batchRoot = bytes32(decrypt(abi.encodePacked(challenges[cIndex].header.batchRoot), key)); } challenge_keys[cIndex][msg.sender] = key; challenge_hashes[cIndex][msg.sender] = decrypt(challenge_hashes[cIndex][msg.sender], key); challenges[cIndex].verifiers.push(msg.sender); emit Verify2(cIndex, msg.sender); finalize(cIndex); } function finalize(uint256 cIndex) internal { Challenge storage challenge = challenges[cIndex]; require(challenge.done == false, "challenge is closed"); if (challenge.verifiers.length != challenge.numVerifiers && block.timestamp - challenge.timestamp < verifyWindow * 2) { // not ready to finalize. do nothing return; } IStateCommitmentChain stateChain = IStateCommitmentChain(resolve("StateCommitmentChain")); bytes32 proposedHash = bytes32(challenge_hashes[cIndex][challenge.challenger]); uint reward = 0; address[] memory agrees = new address[](challenge.verifiers.length); uint numAgrees = 0; address[] memory disagrees = new address[](challenge.verifiers.length); uint numDisagrees = 0; for (uint256 i = 0; i < verifiers.length; i++) { if (!isSufficientlyStaked(verifiers[i]) || !isWhiteListed(verifiers[i])) { // not qualified as a verifier continue; } //record the agreement if (bytes32(challenge_hashes[cIndex][verifiers[i]]) == proposedHash) { //agree with the challenger if (absence_strikes[verifiers[i]] > 0) { absence_strikes[verifiers[i]] -= 1; // slowly clear the strike } agrees[numAgrees] = verifiers[i]; numAgrees++; } else if (challenge_keys[cIndex][verifiers[i]].length == 0) { //absent absence_strikes[verifiers[i]] += 2; if (absence_strikes[verifiers[i]] > ABSENCE_THRESHOLD) { reward += penalize(verifiers[i]); } } else { //disagree with the challenger if (absence_strikes[verifiers[i]] > 0) { absence_strikes[verifiers[i]] -= 1; // slowly clear the strike } disagrees[numDisagrees] = verifiers[i]; numDisagrees++; } } if (Lib_OVMCodec.hashBatchHeader(challenge.header) != stateChain.batches().getByChainId(challenge.chainID, challenge.header.batchIndex)) { // wrong header, penalize the challenger reward += penalize(challenge.challenger); // reward the disagrees. but no penalty on agrees because the input // is garbage. distributeReward(reward, disagrees, challenge.verifiers.length - 1); emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE); } else if (challenge.verifiers.length < numQualifiedVerifiers * 75 / 100) { // the absent verifiers get a absense strike. no other penalties. already done emit Finalize(cIndex, msg.sender, SETTLEMENT.NOT_ENOUGH_VERIFIER); } else if (proposedHash != challenge.header.batchRoot) { if (numAgrees <= numDisagrees) { // no consensus, challenge failed. for (uint i = 0; i < numAgrees; i++) { consensus_strikes[agrees[i]] += 2; if (consensus_strikes[agrees[i]] > FAIL_THRESHOLD) { reward += penalize(agrees[i]); } } distributeReward(reward, disagrees, disagrees.length); emit Finalize(cIndex, msg.sender, SETTLEMENT.DISAGREE); } else { // reached agreement. delete the batch root and slash the sequencer if the header is still valid if(stateChain.insideFraudProofWindow(challenge.header)) { // this header needs to be within the window stateChain.deleteStateBatchByChainId(challenge.chainID, challenge.header); // temporary for the p1 of the decentralization roadmap if (seqStake > 0) { reward += seqStake; for (uint i = 0; i < numDisagrees; i++) { consensus_strikes[disagrees[i]] += 2; if (consensus_strikes[disagrees[i]] > FAIL_THRESHOLD) { reward += penalize(disagrees[i]); } } distributeReward(reward, agrees, agrees.length); } emit Finalize(cIndex, msg.sender, SETTLEMENT.AGREE); } else { //not in the window anymore. let it pass... no penalty emit Finalize(cIndex, msg.sender, SETTLEMENT.PASS); } } } else { //wasteful challenge, add consensus_strikes to the challenger consensus_strikes[challenge.challenger] += 2; if (consensus_strikes[challenge.challenger] > FAIL_THRESHOLD) { reward += penalize(challenge.challenger); } distributeReward(reward, challenge.verifiers, challenge.verifiers.length - 1); emit Finalize(cIndex, msg.sender, SETTLEMENT.SAME_ROOT); } challenge.done = true; activeChallenges--; chain_under_challenge[challenge.chainID] = 0; } function depositSeqStake(uint256 amount) public onlyManager { require(IERC20(metis).transferFrom(msg.sender, address(this), amount), "transfer metis failed"); seqStake += amount; emit Stake(msg.sender, amount); } function withdrawSeqStake(address to) public onlyManager { require(seqStake > 0, "no stake"); emit Withdraw(msg.sender, seqStake); uint256 amount = seqStake; seqStake = 0; require(IERC20(metis).transfer(to, amount), "transfer metis failed"); } function claim() public { require(rewards[msg.sender] > 0, "no reward to claim"); uint256 amount = rewards[msg.sender]; rewards[msg.sender] = 0; require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed"); emit Claim(msg.sender, amount); } function withdraw(uint256 amount) public { require(activeChallenges == 0, "withdraw is currently prohibited"); //ongoing challenge uint256 balance = verifier_stakes[msg.sender]; require(balance >= amount, "insufficient stake to withdraw"); if (balance - amount < minStake && balance >= minStake) { numQualifiedVerifiers--; deleteVerifier(msg.sender); } verifier_stakes[msg.sender] -= amount; require(IERC20(metis).transfer(msg.sender, amount), "token transfer failed"); } function setMinStake( uint256 _minStake ) public onlyManager { minStake = _minStake; uint num = 0; if (verifiers.length > 0) { address[] memory arr = new address[](verifiers.length); for (uint i = 0; i < verifiers.length; ++i) { if (verifier_stakes[verifiers[i]] >= minStake) { arr[num] = verifiers[i]; num++; } } if (num < verifiers.length) { delete verifiers; for (uint i = 0; i < num; i++) { verifiers.push(arr[i]); } } } numQualifiedVerifiers = num; } // helper function isWhiteListed(address verifier) view public returns(bool){ return !useWhiteList || whitelist[verifier]; } function isSufficientlyStaked (address target) view public returns(bool) { return (verifier_stakes[target] >= minStake); } // set the length of the time windows for each verification phase function setVerifyWindow (uint256 window) onlyManager public { verifyWindow = window; } // add the verifier to the whitelist function setWhiteList(address verifier, bool allowed) public onlyManager { whitelist[verifier] = allowed; useWhiteList = true; } // allow everyone to be the verifier function disableWhiteList() public onlyManager { useWhiteList = false; } function setThreshold(uint absence_threshold, uint fail_threshold) public onlyManager { ABSENCE_THRESHOLD = absence_threshold; FAIL_THRESHOLD = fail_threshold; } function getMerkleRoot(bytes32[] calldata elements) pure public returns (bytes32) { return Lib_MerkleTree.getMerkleRoot(elements); } //helper fucntion to encrypt data function encrypt(bytes calldata data, bytes calldata key) pure public returns (bytes memory) { bytes memory encryptedData = data; uint j = 0; for (uint i = 0; i < encryptedData.length; i++) { if (j == key.length) { j = 0; } encryptedData[i] = encryptByte(encryptedData[i], uint8(key[j])); j++; } return encryptedData; } function encryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) { uint16 temp16 = uint16(uint8(b)); temp16 += k; if (temp16 > 255) { temp16 -= 256; } return bytes1(uint8(temp16)); } // helper fucntion to decrypt the data function decrypt(bytes memory data, bytes memory key) pure public returns (bytes memory) { bytes memory decryptedData = data; uint j = 0; for (uint i = 0; i < decryptedData.length; i++) { if (j == key.length) { j = 0; } decryptedData[i] = decryptByte(decryptedData[i], uint8(key[j])); j++; } return decryptedData; } function decryptByte(bytes1 b, uint8 k) pure internal returns (bytes1) { uint16 temp16 = uint16(uint8(b)); if (temp16 > k) { temp16 -= k; } else { temp16 = 256 - k; } return bytes1(uint8(temp16)); } // calculate the rewards function distributeReward(uint256 amount, address[] memory list, uint num) internal { uint reward = amount / num; if (reward == 0) { return; } uint total = 0; for (uint i; i < list.length; i++) { if (isSufficientlyStaked(list[i])) { rewards[list[i]] += reward; total += reward; emit Reward(list[i], reward); } } if (total < amount) { if (isSufficientlyStaked(list[0])) { rewards[list[0]] += total - amount; emit Reward(list[0], total - amount); } else { rewards[list[1]] += total - amount; emit Reward(list[1], total - amount); } } } // slash the verifier stake function penalize(address target) internal returns(uint256) { uint256 stake = verifier_stakes[target]; verifier_stakes[target] = 0; numQualifiedVerifiers--; deleteVerifier(target); emit Penalize(target, stake); return stake; } function deleteVerifier(address target) internal { bool hasVerifier = false; uint pos = 0; for (uint i = 0; i < verifiers.length; i++){ if (verifiers[i] == target) { hasVerifier = true; pos = i; break; } } if (hasVerifier) { for (uint i = pos; i < verifiers.length-1; i++) { verifiers[i] = verifiers[i+1]; } verifiers.pop(); } } }
Verifies a merkle branch for the given leaf hash. Assumes the original length of leaves generated is a known, correct input, and does not return true for indices extending past that index (even if _siblings would be otherwise valid.) _root The Merkle root to verify against. _leaf The leaf hash to verify inclusion of. _index The index in the tree of this leaf. _siblings Array of sibline nodes in the inclusion proof, starting from depth 0 (bottom of the tree). _totalLeaves The total number of leaves originally passed into. return Whether or not the merkle branch and leaf passes verification./
function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings, uint256 _totalLeaves ) internal pure returns (bool) { require(_totalLeaves > 0, "Lib_MerkleTree: Total leaves must be greater than zero."); require(_index < _totalLeaves, "Lib_MerkleTree: Index out of bounds."); require( _siblings.length == _ceilLog2(_totalLeaves), "Lib_MerkleTree: Total siblings does not correctly correspond to total leaves." ); bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot)); computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i])); } _index >>= 1; } return _root == computedRoot; }
366,190
pragma solidity ^0.4.18; import "zeppelin-solidity/contracts/token/ERC721/ERC721.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "./StorageConsumer.sol"; /** * @title ERC721TokenKeyed * Generic implementation for the required functionality of the ERC721 standard */ contract ERC721TokenKeyed is StorageConsumer, ERC721 { using SafeMath for uint256; function ERC721TokenKeyed(BaseStorage storage_) StorageConsumer(storage_) public {} /** * @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 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 _storage.getUint("totalTokens"); } /** * @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) { return _storage.getUint(keccak256("ownerBalances", _owner)); } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { uint256 _ownerBalance = balanceOf(_owner); uint256[] memory _tokens = new uint256[](_ownerBalance); for (uint256 i = 0; i < _ownerBalance; i++) { _tokens[i] = getOwnedToken(_owner, i); } return _tokens; } /** * @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 = getTokenOwner(_tokenId); require(owner != address(0)); return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return getTokenApproval(_tokenId); } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @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 onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { setTokenApproval(_tokenId, _to); Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Mint token function * @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)); addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Burns a specific token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal { if (approvedFor(_tokenId) != 0) { clearApproval(msg.sender, _tokenId); } removeToken(msg.sender, _tokenId); Transfer(msg.sender, 0x0, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to get token owner by token ID * @param tokenId uint256 ID of the token to get the owner for * @return address The address that owns the token an with ID of tokenId */ function getTokenOwner(uint256 tokenId) private view returns (address) { return _storage.getAddress(keccak256("tokenOwners", tokenId)); } /** * @dev Internal function to get an approved address for a token * @param tokenId uint256 ID of the token to get the approved address for * @return address The approved address for the token */ function getTokenApproval(uint256 tokenId) private view returns (address) { return _storage.getAddress(keccak256("tokenApprovals", tokenId)); } /** * @dev Internal function to get an ID value from list of owned token ID's * @param owner address The owner of the token list * @param tokenIndex uint256 The index of the token ID value within the list * @return uint256 The token ID for the given owner and token index */ function getOwnedToken(address owner, uint256 tokenIndex) private view returns (uint256) { return _storage.getUint(keccak256("ownedTokens", owner, tokenIndex)); } /** * @dev Internal function to get the index of a token ID within the owned tokens list * @param tokenId uint256 ID of the token to get the index for * @return uint256 The index of the token for the given ID */ function getOwnedTokenIndex(uint256 tokenId) private view returns (uint256) { return _storage.getUint(keccak256("ownedTokensIndex", tokenId)); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); setTokenApproval(_tokenId, 0); Approval(_owner, 0, _tokenId); } /** * @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 addToken(address _to, uint256 _tokenId) private { require(getTokenOwner(_tokenId) == address(0)); setTokenOwner(_tokenId, _to); uint256 length = balanceOf(_to); pushOwnedToken(_to, _tokenId); setOwnedTokenIndex(_tokenId, length); incrementTotalTokens(); } /** * @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 removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = getOwnedTokenIndex(_tokenId); uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = getOwnedToken(_from, lastTokenIndex); setTokenOwner(_tokenId, 0); setOwnedToken(_from, tokenIndex, lastToken); setOwnedToken(_from, lastTokenIndex, 0); // 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 decrementOwnerBalance(_from); setOwnedTokenIndex(_tokenId, 0); setOwnedTokenIndex(lastToken, tokenIndex); decrementTotalTokens(); } /** * @dev Internal function to increase totalTokens by 1 */ function incrementTotalTokens() private { _storage.setUint("totalTokens", totalSupply().add(1)); } /** * @dev Internal function to decrease totalTokens by 1 */ function decrementTotalTokens() private { _storage.setUint("totalTokens", totalSupply().sub(1)); } /** * @dev Internal function to set token owner by token ID * @param tokenId uint256 ID of the token to set the owner for * @param tokenOwner address The address of the token owner */ function setTokenOwner(uint256 tokenId, address tokenOwner) private { _storage.setAddress(keccak256("tokenOwners", tokenId), tokenOwner); } /** * @dev Internal function to set an approved address for a token * @param tokenId uint256 ID of the token to set the approved address for * @param approvedAddress address The approved address to set for the token */ function setTokenApproval(uint256 tokenId, address approvedAddress) private { _storage.setAddress(keccak256("tokenApprovals", tokenId), approvedAddress); } /** * @dev Internal function to increment an owner's token balance by 1 * @param owner address The owner's address */ function incrementOwnerBalance(address owner) private { _storage.setUint(keccak256("ownerBalances", owner), balanceOf(owner).add(1)); } /** * @dev Internal function to decrement an owner's token balance by 1 * @param owner address The owner's address */ function decrementOwnerBalance(address owner) private { _storage.setUint(keccak256("ownerBalances", owner), balanceOf(owner).sub(1)); } /** * @dev Internal function to set an ID value within a list of owned token ID's * @param owner address The owner of the token list * @param tokenIndex uint256 The index to set within the owned token list * @param tokenId uint256 The ID of the token to set */ function setOwnedToken(address owner, uint256 tokenIndex, uint256 tokenId) private { _storage.setUint(keccak256("ownedTokens", owner, tokenIndex), tokenId); } /** * @dev Internal function to append an ID value to a list of owned token ID's * @param owner address The owner of the token list * @param tokenId uint256 The token ID to append */ function pushOwnedToken(address owner, uint256 tokenId) private { _storage.setUint(keccak256("ownedTokens", owner, balanceOf(owner)), tokenId); incrementOwnerBalance(owner); } /** * @dev Internal function to set the index of a token ID within the owned tokens list * @param tokenId uint256 ID of the token to set the index for * @param tokenIndex uint256 The token index to set for the given token ID */ function setOwnedTokenIndex(uint256 tokenId, uint256 tokenIndex) private { _storage.setUint(keccak256("ownedTokensIndex", tokenId), tokenIndex); } }
Internal function to increment an owner's token balance by 1 owner address The owner's address/
function incrementOwnerBalance(address owner) private { _storage.setUint(keccak256("ownerBalances", owner), balanceOf(owner).add(1)); }
958,641
./partial_match/56/0x2b28688e290aF66Fbf67280937399140B5F1Dda3/sources/BerryMaster.sol
This function upates the minimun dispute fee as a function of the amount of staked miners/
function updateMinDisputeFee(BerryStorage.BerryStorageStruct storage self) public { uint256 stakeAmount = self.uintVars[keccak256("stakeAmount")]; uint256 targetMiners = self.uintVars[keccak256("targetMiners")]; self.uintVars[keccak256("disputeFee")] = SafeMath.max(15e18, (stakeAmount-(stakeAmount*(SafeMath.min(targetMiners,self.uintVars[keccak256("stakerCount")])*1000)/ targetMiners)/1000)); }
11,057,037
/* ORACLIZE_API Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >= 0.5.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI! // Dummy contract only used to emit to end-user they are using wrong solc contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external; } contract OraclizeI { address public cbAddress; function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string memory _datasource) public returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice); function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } contract OraclizeAddrResolverI { function getAddress() public returns (address _address); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { using CBOR for Buffer.buffer; OraclizeI oraclize; OraclizeAddrResolverI OAR; uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string oraclize_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; modifier oraclizeAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { oraclize_setNetwork(networkID_auto); } if (address(oraclize) != OAR.getAddress()) { oraclize = OraclizeI(OAR.getAddress()); } _; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { return oraclize_setNetwork(); _networkID; // silence the warning and remain backwards compatible } function oraclize_setNetworkName(string memory _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string memory _networkName) { return oraclize_network_name; } function oraclize_setNetwork() internal returns (bool _networkSet) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 _myid, string memory _result) public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public { return; _myid; _result; _proof; // Silence compiler warnings } function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(0, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(_timestamp, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); } function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) { return oraclize.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(_gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) { return oraclize.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint subindex = 0; for (uint i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { oraclize_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[_queryId]; } else return false; // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } // Verify if sessionPubkeyHash was verified already, if not.. let's do it! if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license Duplicate Solidity's ecrecover, but catching the CALL return value */ function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) { /* We do our own memory management here. Solidity uses memory offset 0x40 to store the current end of memory. We write past it (as writes are memory extensions), but don't update the offset so Solidity will reuse it. The memory used here is only needed for this context. FIXME: inline assembly can't access return values */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /* The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /* Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. There is no 'mload8' to do this, but that would be nicer. */ v := byte(0, mload(add(_sig, 96))) /* Alternative solution: 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' v := and(mload(add(_sig, 65)), 255) */ } /* albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] geth uses [0, 1] and some clients have followed. This might change, see: https://github.com/ethereum/go-ethereum/issues/2053 */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } /* END ORACLIZE_API */ /** * @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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } contract Ownable { mapping(address => bool) owners; event OwnerAdded(address indexed newOwner); event OwnerDeleted(address indexed owner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owners[msg.sender] = true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(msg.sender)); _; } function addOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0)); owners[_newOwner] = true; emit OwnerAdded(_newOwner); } function delOwner(address _owner) external onlyOwner { require(owners[_owner]); owners[_owner] = false; emit OwnerDeleted(_owner); } function isOwner(address _owner) public view returns (bool) { return owners[_owner]; } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor() internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is ReentrancyGuard, Ownable, usingOraclize { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; uint public minPurchase = 5 ether; uint public maxPurchase = 20 ether; uint256 private _cap; uint256 private _openingTime; uint256 private _closingTime; bool private _paused; bool private _finalized; bool private _kycEnabled; mapping (address => bool) public KYC; string public oraclize_url = "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0"; uint public oraclizeTime; mapping (bytes32 => bool) public pendingQueries; uint public refPercent = 10; mapping (address => uint) public refTokens; uint[] public depositBlocks; uint public lastCheckedBlock = 0; mapping (uint => uint) public winBlocks; struct Deposit { uint value; bool executed; } mapping (address => mapping (uint => Deposit)) public userDeposits; mapping (address => uint[]) public userBlocks; mapping (address => uint) public userLastCheckedBlock; mapping (uint => address[]) public blockUsers; event CrowdsaleFinalized(); event TokensPurchased(address indexed beneficiary, uint256 value, uint256 amount); event Paused(); event Unpaused(); event NewOraclizeQuery(string description); event NewKrakenPriceTicker(string price); event NewDeposit(uint indexed blockNum, address user, uint value); event NewWinBlock(uint depositBlocks, uint hashBlock); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen() && !_paused); _; } constructor(uint256 rate, address token) public { require(rate > 0); require(token != address(0)); _rate = rate; _token = IERC20(token); _cap = 10000 ether; //TODO _openingTime = now; _closingTime = _openingTime + 90 days; _paused = false; _finalized = false; _kycEnabled = true; oraclizeTime = 14400; } function () external payable { buyTokens(address(0)); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. */ function buyTokens(address _ref) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(msg.sender, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(msg.sender, tokens); if (_ref != address(0) && _ref != msg.sender) { uint _refTokens = tokens.mul(refPercent).div(100); refTokens[_ref] = refTokens[_ref].add(_refTokens); } emit TokensPurchased(msg.sender, weiAmount, tokens); if (depositBlocks.length == 0 || depositBlocks[depositBlocks.length -1] != block.number) { depositBlocks.push(block.number); } userDeposits[msg.sender][block.number].value = userDeposits[msg.sender][block.number].value.add(msg.value); if (userBlocks[msg.sender].length == 0 || userBlocks[msg.sender][userBlocks[msg.sender].length -1] != block.number) { userBlocks[msg.sender].push(block.number); blockUsers[block.number].push(msg.sender); } emit NewDeposit(block.number, msg.sender, msg.value); checkBlocks(); } function __callback(bytes32 myid, string memory result, bytes memory proof) public { if (msg.sender != oraclize_cbAddress()) revert(); require (pendingQueries[myid] == true); proof; emit NewKrakenPriceTicker(result); uint USD = parseInt(result); uint tokenPriceInWei = (1 ether / USD) / 100; //0.01 USD _rate = 1 ether / tokenPriceInWei; updatePrice(); delete pendingQueries[myid]; } function updatePrice() public payable { uint queryPrice = oraclize_getPrice("URL"); if (queryPrice > address(this).balance) { emit NewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit NewOraclizeQuery("Oraclize query was sent, standing by for the answer.."); bytes32 queryId = oraclize_query(oraclizeTime, "URL", oraclize_url); pendingQueries[queryId] = true; } } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) onlyWhileOpen internal view { require(beneficiary != address(0)); require(weiAmount >= minPurchase && weiAmount <= maxPurchase); require(weiRaised().add(weiAmount) <= _cap); if (_kycEnabled) { require(KYC[beneficiary]); } } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } function withdrawRefTokens() public { require(hasClosed()); require(refTokens[msg.sender] > 0); _token.safeTransfer(msg.sender, refTokens[msg.sender]); refTokens[msg.sender] = 0; } //NEED EXECUTE EVERY ~20mins function checkBlocks() public { for (uint i = lastCheckedBlock; i < depositBlocks.length; i++) { uint blockNum = depositBlocks[i] + 1; if (blockNum < block.number && blockNum >= block.number - 256) { uint rnd = generateRnd(abi.encodePacked(blockhash(blockNum))); if (rnd > 25) { winBlocks[depositBlocks[i]] = rnd; emit NewWinBlock(depositBlocks[i], blockNum); } lastCheckedBlock++; } } } function getPrize() public { checkBlocks(); for (uint i = userLastCheckedBlock[msg.sender]; i < userBlocks[msg.sender].length; i++) { uint blockNum = userBlocks[msg.sender][i]; if (winBlocks[blockNum] > 0 && userDeposits[msg.sender][blockNum].value > 0 && !userDeposits[msg.sender][blockNum].executed) { uint rate = getRate(winBlocks[blockNum]); uint val = userDeposits[msg.sender][blockNum].value.mul(rate).div(100); require(address(this).balance >= val); userDeposits[msg.sender][blockNum].executed = true; msg.sender.transfer(val); } userLastCheckedBlock[msg.sender]++; } } function getPrizeByBlock(uint _block) public { checkBlocks(); require(winBlocks[_block] > 0 && userDeposits[msg.sender][_block].value > 0 && !userDeposits[msg.sender][_block].executed); uint rate = getRate(winBlocks[_block]); uint val = userDeposits[msg.sender][_block].value.mul(rate).div(100); require(address(this).balance >= val); userDeposits[msg.sender][_block].executed = true; msg.sender.transfer(val); } function getRate(uint _rnd) internal pure returns (uint) { if (_rnd > 25 && _rnd < 51) { return 15; } if (_rnd > 50 && _rnd < 71) { return 25; } if (_rnd > 70 && _rnd < 86) { return 50; } if (_rnd > 85 && _rnd < 96) { return 100; } if (_rnd > 95) { return 200; } } function generateRnd(bytes memory _hash) public pure returns(uint) { uint _max = 100; return uint256(keccak256(_hash)) % _max.add(1); } function getBlockUserCount(uint _block) public view returns (uint) { return blockUsers[_block].length; } function getBlockUsers(uint _block) public view returns (address[] memory) { return blockUsers[_block]; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require(!_finalized); require(hasClosed()); _finalized = true; //_finalization(); emit CrowdsaleFinalized(); } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super._finalization() to ensure the chain of finalization is * executed entirely. */ // function _finalization() internal { // // } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @return the cap of the crowdsale. */ function cap() public view returns(uint256) { return _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised() >= _cap; } /** * @return the crowdsale opening time. */ function openingTime() public view returns(uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns(uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > _closingTime; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function addKYC(address _user) onlyOwner public { KYC[_user] = true; } function delKYC(address _user) onlyOwner public { KYC[_user] = false; } function setMinPurchase(uint _val) onlyOwner public { minPurchase = _val; } function setMaxPurchase(uint _val) onlyOwner public { maxPurchase = _val; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner { _paused = true; emit Paused(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner { _paused = false; emit Unpaused(); } function setKycEnabled(bool _enabled) onlyOwner public { _kycEnabled = _enabled; } function setOraclizTime(uint _time) onlyOwner public { oraclizeTime = _time; } function addBalanceForOraclize() payable external { // } function setGasPrice(uint _newPrice) onlyOwner public { oraclize_setCustomGasPrice(_newPrice * 1 wei); } function setOraclizeUrl(string memory _url) onlyOwner public { oraclize_url = _url; } function setRate(uint _price) onlyOwner public { _rate = _price; } function withdraw(address payable _to, uint _val) onlyOwner public { require(_to != address(0)); require(_val >= address(this).balance); _to.transfer(_val); } /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address payable _to, address _claimToken) external onlyOwner { require(_to != address(0)); if (_claimToken == address(0)) { _to.transfer(address(this).balance); return; } IERC20 claimToken = IERC20(_claimToken); uint balance = claimToken.balanceOf(address(this)); claimToken.safeTransfer(_to, balance); } }
ERC20 interface/
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
5,456,520
./full_match/5/0xdF3D542D51dA747b305cabC8b2515015BeE290c1/sources/contracts/RaiseFundContract.sol
get the startup index
function getFundRaiseGoal(address startup) public view returns (uint) { uint startupIndex = getStartupIndex(startup); return campaigns[startupIndex].goal; }
1,863,536
./full_match/1/0x6C1C3012f6Ac0dBB750e33f93E1bA350012A6653/sources/contracts/periphery/manager/PoolManagerLocker.sol
Restricted base price update mechanism/
function changeBasePrice(uint128 /*newBasePrice*/ ) public pure override { revert PoolManagerUnsupportedOperation(); }
3,043,350
/** *Submitted for verification at Etherscan.io on 2022-03-05 */ // Verified using https://dapp.tools // hevm: flattened sources of /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/ConverterFeed.sol pragma solidity =0.6.7; ////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/ConverterFeed.sol /* pragma solidity 0.6.7; */ abstract contract ConverterFeedLike_1 { function getResultWithValidity() virtual external view returns (uint256,bool); function updateResult(address) virtual external; } contract ConverterFeed { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "ConverterFeed/account-not-authorized"); _; } // --- General Vars --- // Base feed you want to convert into another currency. ie: (RAI/ETH) ConverterFeedLike_1 public targetFeed; // Feed user for conversion. (i.e: Using the example above and ETH/USD willoutput RAI price in USD) ConverterFeedLike_1 public denominationFeed; // This is the denominator for computing uint256 public converterFeedScalingFactor; // Manual flag that can be set by governance and indicates if a result is valid or not uint256 public validityFlag; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters( bytes32 parameter, address addr ); event ModifyParameters( bytes32 parameter, uint256 val ); event FailedUpdate(address feed, bytes out); constructor( address targetFeed_, address denominationFeed_, uint256 converterFeedScalingFactor_ ) public { require(targetFeed_ != address(0), "ConverterFeed/null-target-feed"); require(denominationFeed_ != address(0), "ConverterFeed/null-denomination-feed"); require(converterFeedScalingFactor_ > 0, "ConverterFeed/null-scaling-factor"); authorizedAccounts[msg.sender] = 1; targetFeed = ConverterFeedLike_1(targetFeed_); denominationFeed = ConverterFeedLike_1(denominationFeed_); validityFlag = 1; converterFeedScalingFactor = converterFeedScalingFactor_; // Emit events emit AddAuthorization(msg.sender); emit ModifyParameters(bytes32("validityFlag"), 1); emit ModifyParameters(bytes32("converterFeedScalingFactor"), converterFeedScalingFactor_); emit ModifyParameters(bytes32("targetFeed"), targetFeed_); emit ModifyParameters(bytes32("denominationFeed"), denominationFeed_); } // --- General Utils -- function both(bool x, bool y) private pure returns (bool z) { assembly{ z := and(x, y)} } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } // --- Math --- function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- /** * @notice Modify uint256 parameters * @param parameter Name of the parameter to modify * @param data New parameter value **/ function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "validityFlag") { require(either(data == 1, data == 0), "ConverterFeed/invalid-data"); validityFlag = data; } else if (parameter == "scalingFactor") { require(data > 0, "ConverterFeed/invalid-data"); converterFeedScalingFactor = data; } else revert("ConverterFeed/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Modify uint256 parameters * @param parameter Name of the parameter to modify * @param data New parameter value **/ function modifyParameters(bytes32 parameter, address data) external isAuthorized { require(data != address(0), "ConverterFeed/invalid-data"); if (parameter == "targetFeed") { targetFeed = ConverterFeedLike_1(data); } else if (parameter == "denominationFeed") { denominationFeed = ConverterFeedLike_1(data); } else revert("ConverterFeed/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /** * @notice Updates both feeds **/ function updateResult(address feeReceiver) external { try targetFeed.updateResult(feeReceiver) {} catch (bytes memory out) { emit FailedUpdate(address(targetFeed), out); } try denominationFeed.updateResult(feeReceiver) {} catch (bytes memory out) { emit FailedUpdate(address(denominationFeed), out); } } // --- Getters --- /** * @notice Fetch the latest medianPrice (for maxWindow) or revert if is is null **/ function read() external view returns (uint256) { (uint256 value, bool valid) = getResultWithValidity(); require(valid, "ConverterFeed/invalid-price-feed"); return value; } /** * @notice Fetch the latest medianPrice and whether it is null or not **/ function getResultWithValidity() public view returns (uint256 value, bool valid) { (uint256 targetValue, bool targetValid) = targetFeed.getResultWithValidity(); (uint256 denominationValue, bool denominationValid) = denominationFeed.getResultWithValidity(); value = multiply(targetValue, denominationValue) / converterFeedScalingFactor; valid = both( both(targetValid, denominationValid), both(validityFlag == 1, value > 0) ); } }
Modify uint256 parameters parameter Name of the parameter to modify data New parameter value/
function modifyParameters(bytes32 parameter, address data) external isAuthorized { require(data != address(0), "ConverterFeed/invalid-data"); if (parameter == "targetFeed") { targetFeed = ConverterFeedLike_1(data); denominationFeed = ConverterFeedLike_1(data); } else revert("ConverterFeed/modify-unrecognized-param"); emit ModifyParameters(parameter, data); }
15,430,165
./full_match/5/0xE3edE07AB47EFC691B11FC98E5242E2DA80ba27a/sources/contract-v2/module/NTS-Multi.sol
Team staking status check
function _calRewardTeam(uint16 _staketeam) internal view returns (uint256 _Reward){ if(inStakedteam[_staketeam].stakeowner != msg.sender){ return 0; } uint16[] memory _boostIds = inStakedteam[_staketeam].boostIds; uint256 _lastUpdateBlock = inStakedteam[_staketeam].lastUpdateBlock; uint256 _tmhcReward = ((block.timestamp - _lastUpdateBlock) * rewardPerHour) / 3600; uint256 _totlaReward = _tmhcReward; for(uint16 i = 0; i < _boostIds.length; i ++) { uint16 _boostId = _boostIds[i]; uint8 _boostGrade = momoGrades[_boostId]; uint8 _boostRate = gradesBonus[_boostGrade]; _totlaReward = _totlaReward + ((_tmhcReward * _boostRate) / 100); } return _totlaReward; }
1,913,153
// SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ERC165} from "@solidstate/contracts/introspection/ERC165.sol"; import {ERC1155Enumerable} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol"; import {IERC20Metadata} from "@solidstate/contracts/token/ERC20/metadata/IERC20Metadata.sol"; import {Multicall} from "@solidstate/contracts/utils/Multicall.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {PoolInternal} from "./PoolInternal.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolBase is PoolInternal, ERC1155Enumerable, ERC165, Multicall { constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 feePremium64x64, int128 feeApy64x64 ) PoolInternal( ivolOracle, weth, premiaMining, feeReceiver, feeDiscountAddress, feePremium64x64, feeApy64x64 ) {} /** * @notice see IPoolBase; inheritance not possible due to linearization issues */ function name() external view returns (string memory) { PoolStorage.Layout storage l = PoolStorage.layout(); return string( abi.encodePacked( IERC20Metadata(l.underlying).symbol(), " / ", IERC20Metadata(l.base).symbol(), " - Premia Options Pool" ) ); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(PoolInternal, ERC1155Enumerable) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from './IERC165.sol'; import { ERC165Storage } from './ERC165Storage.sol'; /** * @title ERC165 implementation */ abstract contract ERC165 is IERC165 { using ERC165Storage for ERC165Storage.Layout; /** * @inheritdoc IERC165 */ function supportsInterface(bytes4 interfaceId) public view returns (bool) { return ERC165Storage.layout().isSupportedInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155Base, ERC1155BaseInternal } from '../base/ERC1155Base.sol'; import { IERC1155Enumerable } from './IERC1155Enumerable.sol'; import { ERC1155EnumerableInternal, ERC1155EnumerableStorage } from './ERC1155EnumerableInternal.sol'; /** * @title ERC1155 implementation including enumerable and aggregate functions */ abstract contract ERC1155Enumerable is IERC1155Enumerable, ERC1155Base, ERC1155EnumerableInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @inheritdoc IERC1155Enumerable */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply(id); } /** * @inheritdoc IERC1155Enumerable */ function totalHolders(uint256 id) public view virtual returns (uint256) { return _totalHolders(id); } /** * @inheritdoc IERC1155Enumerable */ function accountsByToken(uint256 id) public view virtual returns (address[] memory) { return _accountsByToken(id); } /** * @inheritdoc IERC1155Enumerable */ function tokensByAccount(address account) public view virtual returns (uint256[] memory) { return _tokensByAccount(account); } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155EnumerableInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155BaseInternal, ERC1155EnumerableInternal) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC20 metadata interface */ interface IERC20Metadata { /** * @notice return token name * @return token name */ function name() external view returns (string memory); /** * @notice return token symbol * @return token symbol */ function symbol() external view returns (string memory); /** * @notice return token decimals, generally used only for display purposes * @return token decimals */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IMulticall } from './IMulticall.sol'; /** * @title Utility contract for supporting processing of multiple function calls in a single transaction */ abstract contract Multicall is IMulticall { /** * @inheritdoc IMulticall */ function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); unchecked { for (uint256 i; i < data.length; i++) { (bool success, bytes memory returndata) = address(this) .delegatecall(data[i]); if (success) { results[i] = returndata; } else { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } } return results; } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol"; import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; library PoolStorage { using ABDKMath64x64 for int128; using PoolStorage for PoolStorage.Layout; enum TokenType { UNDERLYING_FREE_LIQ, BASE_FREE_LIQ, UNDERLYING_RESERVED_LIQ, BASE_RESERVED_LIQ, LONG_CALL, SHORT_CALL, LONG_PUT, SHORT_PUT } struct PoolSettings { address underlying; address base; address underlyingOracle; address baseOracle; } struct QuoteArgsInternal { address feePayer; // address of the fee payer uint64 maturity; // timestamp of option maturity int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price uint256 contractSize; // size of option contract bool isCall; // true for call, false for put } struct QuoteResultInternal { int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee) int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size } struct BatchData { uint256 eta; uint256 totalPendingDeposits; } bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.Pool"); uint256 private constant C_DECAY_BUFFER = 12 hours; uint256 private constant C_DECAY_INTERVAL = 4 hours; struct Layout { // ERC20 token addresses address base; address underlying; // AggregatorV3Interface oracle addresses address baseOracle; address underlyingOracle; // token metadata uint8 underlyingDecimals; uint8 baseDecimals; // minimum amounts uint256 baseMinimum; uint256 underlyingMinimum; // deposit caps uint256 _deprecated_basePoolCap; uint256 _deprecated_underlyingPoolCap; // market state int128 _deprecated_steepness64x64; int128 cLevelBase64x64; int128 cLevelUnderlying64x64; uint256 cLevelBaseUpdatedAt; uint256 cLevelUnderlyingUpdatedAt; uint256 updatedAt; // User -> isCall -> depositedAt mapping(address => mapping(bool => uint256)) depositedAt; mapping(address => mapping(bool => uint256)) divestmentTimestamps; // doubly linked list of free liquidity intervals // isCall -> User -> User mapping(bool => mapping(address => address)) liquidityQueueAscending; mapping(bool => mapping(address => address)) liquidityQueueDescending; // minimum resolution price bucket => price mapping(uint256 => int128) bucketPrices64x64; // sequence id (minimum resolution price bucket / 256) => price update sequence mapping(uint256 => uint256) priceUpdateSequences; // isCall -> batch data mapping(bool => BatchData) nextDeposits; // user -> batch timestamp -> isCall -> pending amount mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits; EnumerableSet.UintSet tokenIds; // user -> isCallPool -> total value locked of user (Used for liquidity mining) mapping(address => mapping(bool => uint256)) userTVL; // isCallPool -> total value locked mapping(bool => uint256) totalTVL; // steepness values int128 steepnessBase64x64; int128 steepnessUnderlying64x64; // User -> isCallPool -> isBuybackEnabled mapping(address => mapping(bool => bool)) isBuybackEnabled; // LongTokenId -> averageC mapping(uint256 => int128) avgCLevel64x64; // APY fee tracking // underwriter -> shortTokenId -> amount mapping(address => mapping(uint256 => uint256)) feesReserved; // shortTokenId -> 64x64 fixed point representation of apy fee mapping(uint256 => int128) feeReserveRates; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } /** * @notice calculate ERC1155 token id for given option parameters * @param tokenType TokenType enum * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @return tokenId token id */ function formatTokenId( TokenType tokenType, uint64 maturity, int128 strike64x64 ) internal pure returns (uint256 tokenId) { tokenId = (uint256(tokenType) << 248) + (uint256(maturity) << 128) + uint256(int256(strike64x64)); } /** * @notice derive option maturity and strike price from ERC1155 token id * @param tokenId token id * @return tokenType TokenType enum * @return maturity timestamp of option maturity * @return strike64x64 option strike price */ function parseTokenId(uint256 tokenId) internal pure returns ( TokenType tokenType, uint64 maturity, int128 strike64x64 ) { assembly { tokenType := shr(248, tokenId) maturity := shr(128, tokenId) strike64x64 := tokenId } } function getTokenType(bool isCall, bool isLong) internal pure returns (TokenType tokenType) { if (isCall) { tokenType = isLong ? TokenType.LONG_CALL : TokenType.SHORT_CALL; } else { tokenType = isLong ? TokenType.LONG_PUT : TokenType.SHORT_PUT; } } function getPoolToken(Layout storage l, bool isCall) internal view returns (address token) { token = isCall ? l.underlying : l.base; } function getTokenDecimals(Layout storage l, bool isCall) internal view returns (uint8 decimals) { decimals = isCall ? l.underlyingDecimals : l.baseDecimals; } function getMinimumAmount(Layout storage l, bool isCall) internal view returns (uint256 minimumAmount) { minimumAmount = isCall ? l.underlyingMinimum : l.baseMinimum; } /** * @notice get the total supply of free liquidity tokens, minus pending deposits * @param l storage layout struct * @param isCall whether query is for call or put pool * @return 64x64 fixed point representation of total free liquidity */ function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall) internal view returns (int128) { uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); return ABDKMath64x64Token.fromDecimals( ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.totalPendingDeposits(isCall), l.getTokenDecimals(isCall) ); } function getReinvestmentStatus( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { uint256 timestamp = l.divestmentTimestamps[account][isCallPool]; return timestamp == 0 || timestamp > block.timestamp; } function addUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (_isInQueue(account, asc, desc)) return; address last = desc[address(0)]; asc[last] = account; desc[account] = last; desc[address(0)] = account; } function removeUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (!_isInQueue(account, asc, desc)) return; address prev = desc[account]; address next = asc[account]; asc[prev] = next; desc[next] = prev; delete asc[account]; delete desc[account]; } function isInQueue( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; return _isInQueue(account, asc, desc); } function _isInQueue( address account, mapping(address => address) storage asc, mapping(address => address) storage desc ) private view returns (bool) { return asc[account] != address(0) || desc[address(0)] == account; } /** * @notice get current C-Level, without accounting for pending adjustments * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getRawCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64; } /** * @notice get current C-Level, accounting for unrealized decay * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getDecayAdjustedCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { // get raw C-Level from storage cLevel64x64 = l.getRawCLevel64x64(isCall); // account for C-Level decay cLevel64x64 = l.applyCLevelDecayAdjustment(cLevel64x64, isCall); } /** * @notice get updated C-Level and pool liquidity level, accounting for decay and pending deposits * @param l storage layout struct * @param isCall whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level * @return liquidity64x64 64x64 fixed point representation of new liquidity amount */ function getRealPoolState(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64, int128 liquidity64x64) { PoolStorage.BatchData storage batchData = l.nextDeposits[isCall]; int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCall); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); if ( batchData.totalPendingDeposits > 0 && batchData.eta != 0 && block.timestamp >= batchData.eta ) { liquidity64x64 = ABDKMath64x64Token .fromDecimals( batchData.totalPendingDeposits, l.getTokenDecimals(isCall) ) .add(oldLiquidity64x64); cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, liquidity64x64, isCall ); } else { cLevel64x64 = oldCLevel64x64; liquidity64x64 = oldLiquidity64x64; } } /** * @notice calculate updated C-Level, accounting for unrealized decay * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for decay * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after accounting for decay */ function applyCLevelDecayAdjustment( Layout storage l, int128 oldCLevel64x64, bool isCall ) internal view returns (int128 cLevel64x64) { uint256 timeElapsed = block.timestamp - (isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt); // do not apply C decay if less than 24 hours have elapsed if (timeElapsed > C_DECAY_BUFFER) { timeElapsed -= C_DECAY_BUFFER; } else { return oldCLevel64x64; } int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu( timeElapsed, C_DECAY_INTERVAL ); uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); uint256 tvl = l.totalTVL[isCall]; int128 utilization = ABDKMath64x64.divu( tvl - (ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.totalPendingDeposits(isCall)), tvl ); return OptionMath.calculateCLevelDecay( OptionMath.CalculateCLevelDecayArgs( timeIntervalsElapsed64x64, oldCLevel64x64, utilization, 0xb333333333333333, // 0.7 0xe666666666666666, // 0.9 0x10000000000000000, // 1.0 0x10000000000000000, // 1.0 0xe666666666666666, // 0.9 0x56fc2a2c515da32ea // 2e ) ); } /** * @notice calculate updated C-Level, accounting for change in liquidity * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for liquidity change * @param oldLiquidity64x64 64x64 fixed point representation of previous liquidity * @param newLiquidity64x64 64x64 fixed point representation of current liquidity * @param isCallPool whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function applyCLevelLiquidityChangeAdjustment( Layout storage l, int128 oldCLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal view returns (int128 cLevel64x64) { int128 steepness64x64 = isCallPool ? l.steepnessUnderlying64x64 : l.steepnessBase64x64; // fallback to deprecated storage value if side-specific value is not set if (steepness64x64 == 0) steepness64x64 = l._deprecated_steepness64x64; cLevel64x64 = OptionMath.calculateCLevel( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, steepness64x64 ); if (cLevel64x64 < 0xb333333333333333) { cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7 } } /** * @notice set C-Level to arbitrary pre-calculated value * @param cLevel64x64 new C-Level of pool * @param isCallPool whether to update C-Level for call or put pool */ function setCLevel( Layout storage l, int128 cLevel64x64, bool isCallPool ) internal { if (isCallPool) { l.cLevelUnderlying64x64 = cLevel64x64; l.cLevelUnderlyingUpdatedAt = block.timestamp; } else { l.cLevelBase64x64 = cLevel64x64; l.cLevelBaseUpdatedAt = block.timestamp; } } function setOracles( Layout storage l, address baseOracle, address underlyingOracle ) internal { require( AggregatorV3Interface(baseOracle).decimals() == AggregatorV3Interface(underlyingOracle).decimals(), "Pool: oracle decimals must match" ); l.baseOracle = baseOracle; l.underlyingOracle = underlyingOracle; } function fetchPriceUpdate(Layout storage l) internal view returns (int128 price64x64) { int256 priceUnderlying = AggregatorInterface(l.underlyingOracle) .latestAnswer(); int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer(); return ABDKMath64x64.divi(priceUnderlying, priceBase); } /** * @notice set price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to update * @param price64x64 64x64 fixed point representation of price */ function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64 ) internal { uint256 bucket = timestamp / (1 hours); l.bucketPrices64x64[bucket] = price64x64; l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255)); } /** * @notice get price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdate(Layout storage l, uint256 timestamp) internal view returns (int128) { return l.bucketPrices64x64[timestamp / (1 hours)]; } /** * @notice get first price update available following given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdateAfter(Layout storage l, uint256 timestamp) internal view returns (int128) { // price updates are grouped into hourly buckets uint256 bucket = timestamp / (1 hours); // divide by 256 to get the index of the relevant price update sequence uint256 sequenceId = bucket >> 8; // get position within sequence relevant to current price update uint256 offset = bucket & 255; // shift to skip buckets from earlier in sequence uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >> offset; // iterate through future sequences until a price update is found // sequence corresponding to current timestamp used as upper bound uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours); while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) { sequence = l.priceUpdateSequences[++sequenceId]; } // if no price update is found (sequence == 0) function will return 0 // this should never occur, as each relevant external function triggers a price update // the most significant bit of the sequence corresponds to the offset of the relevant bucket uint256 msb; for (uint256 i = 128; i > 0; i >>= 1) { if (sequence >> i > 0) { msb += i; sequence >>= i; } } return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1]; } function totalPendingDeposits(Layout storage l, bool isCallPool) internal view returns (uint256) { return l.nextDeposits[isCallPool].totalPendingDeposits; } function pendingDepositsOf( Layout storage l, address account, bool isCallPool ) internal view returns (uint256) { return l.pendingDeposits[account][l.nextDeposits[isCallPool].eta][ isCallPool ]; } function contractSizeToBaseTokenAmount( Layout storage l, uint256 contractSize, int128 price64x64, bool isCallPool ) internal view returns (uint256 tokenAmount) { if (isCallPool) { tokenAmount = contractSize; } else { uint256 value = price64x64.mulu(contractSize); int128 value64x64 = ABDKMath64x64Token.fromDecimals( value, l.underlyingDecimals ); tokenAmount = ABDKMath64x64Token.toDecimals( value64x64, l.baseDecimals ); } } function setBuybackEnabled( Layout storage l, bool state, bool isCallPool ) internal { l.isBuybackEnabled[msg.sender][isCallPool] = state; } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {IERC173} from "@solidstate/contracts/access/IERC173.sol"; import {OwnableStorage} from "@solidstate/contracts/access/OwnableStorage.sol"; import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol"; import {ERC1155EnumerableInternal, ERC1155EnumerableStorage, EnumerableSet} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol"; import {IWETH} from "@solidstate/contracts/utils/IWETH.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; import {IFeeDiscount} from "../staking/IFeeDiscount.sol"; import {IPoolEvents} from "./IPoolEvents.sol"; import {IPremiaMining} from "../mining/IPremiaMining.sol"; import {IVolatilitySurfaceOracle} from "../oracle/IVolatilitySurfaceOracle.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolInternal is IPoolEvents, ERC1155EnumerableInternal { using ABDKMath64x64 for int128; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; struct Interval { uint256 contractSize; uint256 tokenAmount; uint256 payment; uint256 apyFee; } address internal immutable WETH_ADDRESS; address internal immutable PREMIA_MINING_ADDRESS; address internal immutable FEE_RECEIVER_ADDRESS; address internal immutable FEE_DISCOUNT_ADDRESS; address internal immutable IVOL_ORACLE_ADDRESS; int128 internal immutable FEE_PREMIUM_64x64; int128 internal immutable FEE_APY_64x64; uint256 internal immutable UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 internal immutable BASE_FREE_LIQ_TOKEN_ID; uint256 internal immutable UNDERLYING_RESERVED_LIQ_TOKEN_ID; uint256 internal immutable BASE_RESERVED_LIQ_TOKEN_ID; uint256 internal constant INVERSE_BASIS_POINT = 1e4; uint256 internal constant BATCHING_PERIOD = 260; // Minimum APY for capital locked up to underwrite options. // The quote will return a minimum price corresponding to this APY int128 internal constant MIN_APY_64x64 = 0x4ccccccccccccccd; // 0.3 // Multiply sell quote by this constant int128 internal constant SELL_COEFFICIENT_64x64 = 0xb333333333333333; // 0.7 constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 feePremium64x64, int128 feeApy64x64 ) { IVOL_ORACLE_ADDRESS = ivolOracle; WETH_ADDRESS = weth; PREMIA_MINING_ADDRESS = premiaMining; FEE_RECEIVER_ADDRESS = feeReceiver; // PremiaFeeDiscount contract address FEE_DISCOUNT_ADDRESS = feeDiscountAddress; FEE_PREMIUM_64x64 = feePremium64x64; FEE_APY_64x64 = feeApy64x64; UNDERLYING_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_FREE_LIQ, 0, 0 ); BASE_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_FREE_LIQ, 0, 0 ); UNDERLYING_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_RESERVED_LIQ, 0, 0 ); BASE_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_RESERVED_LIQ, 0, 0 ); } modifier onlyProtocolOwner() { require( msg.sender == IERC173(OwnableStorage.layout().owner).owner(), "Not protocol owner" ); _; } function _fetchFeeDiscount64x64(address feePayer) internal view returns (int128 discount64x64) { if (FEE_DISCOUNT_ADDRESS != address(0)) { discount64x64 = ABDKMath64x64.divu( IFeeDiscount(FEE_DISCOUNT_ADDRESS).getDiscount(feePayer), INVERSE_BASIS_POINT ); } } function _withdrawFees(bool isCall) internal returns (uint256 amount) { uint256 tokenId = _getReservedLiquidityTokenId(isCall); amount = _balanceOf(FEE_RECEIVER_ADDRESS, tokenId); if (amount > 0) { _burn(FEE_RECEIVER_ADDRESS, tokenId, amount); _pushTo( FEE_RECEIVER_ADDRESS, PoolStorage.layout().getPoolToken(isCall), amount ); emit FeeWithdrawal(isCall, amount); } } /** * @notice calculate price of option contract * @param args structured quote arguments * @return result quote result */ function _quotePurchasePrice(PoolStorage.QuoteArgsInternal memory args) internal view returns (PoolStorage.QuoteResultInternal memory result) { require( args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0, "invalid args" ); PoolStorage.Layout storage l = PoolStorage.layout(); int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( args.contractSize, l.underlyingDecimals ); (int128 adjustedCLevel64x64, int128 oldLiquidity64x64) = l .getRealPoolState(args.isCall); require(oldLiquidity64x64 > 0, "no liq"); int128 timeToMaturity64x64 = ABDKMath64x64.divu( args.maturity - block.timestamp, 365 days ); int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle( IVOL_ORACLE_ADDRESS ).getAnnualizedVolatility64x64( l.base, l.underlying, args.spot64x64, args.strike64x64, timeToMaturity64x64 ); require(annualizedVolatility64x64 > 0, "vol = 0"); int128 collateral64x64 = args.isCall ? contractSize64x64 : contractSize64x64.mul(args.strike64x64); ( int128 price64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) = OptionMath.quotePrice( OptionMath.QuoteArgs( annualizedVolatility64x64.mul(annualizedVolatility64x64), args.strike64x64, args.spot64x64, timeToMaturity64x64, adjustedCLevel64x64, oldLiquidity64x64, oldLiquidity64x64.sub(collateral64x64), 0x10000000000000000, // 64x64 fixed point representation of 1 MIN_APY_64x64, args.isCall ) ); result.baseCost64x64 = args.isCall ? price64x64.mul(contractSize64x64).div(args.spot64x64) : price64x64.mul(contractSize64x64); result.feeCost64x64 = result.baseCost64x64.mul(FEE_PREMIUM_64x64); result.cLevel64x64 = cLevel64x64; result.slippageCoefficient64x64 = slippageCoefficient64x64; result.feeCost64x64 -= result.feeCost64x64.mul( _fetchFeeDiscount64x64(args.feePayer) ); } function _quoteSalePrice(PoolStorage.QuoteArgsInternal memory args) internal view returns (int128 baseCost64x64, int128 feeCost64x64) { require( args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0, "invalid args" ); PoolStorage.Layout storage l = PoolStorage.layout(); int128 timeToMaturity64x64 = ABDKMath64x64.divu( args.maturity - block.timestamp, 365 days ); int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle( IVOL_ORACLE_ADDRESS ).getAnnualizedVolatility64x64( l.base, l.underlying, args.spot64x64, args.strike64x64, timeToMaturity64x64 ); require(annualizedVolatility64x64 > 0, "vol = 0"); int128 blackScholesPrice64x64 = OptionMath._blackScholesPrice( annualizedVolatility64x64.mul(annualizedVolatility64x64), args.strike64x64, args.spot64x64, timeToMaturity64x64, args.isCall ); int128 exerciseValue64x64 = ABDKMath64x64Token.fromDecimals( _calculateExerciseValue( l, args.contractSize, args.spot64x64, args.strike64x64, args.isCall ), l.baseDecimals ); int128 sellCLevel64x64; { uint256 longTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(args.isCall, true), args.maturity, args.strike64x64 ); // Initialize to avg value, and replace by current if avg not set or current is lower sellCLevel64x64 = l.avgCLevel64x64[longTokenId]; { (int128 currentCLevel64x64, ) = l.getRealPoolState(args.isCall); if ( sellCLevel64x64 == 0 || currentCLevel64x64 < sellCLevel64x64 ) { sellCLevel64x64 = currentCLevel64x64; } } } int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( args.contractSize, l.underlyingDecimals ); baseCost64x64 = SELL_COEFFICIENT_64x64 .mul(sellCLevel64x64) .mul( blackScholesPrice64x64.mul(contractSize64x64).sub( exerciseValue64x64 ) ) .add(exerciseValue64x64); if (args.isCall) { baseCost64x64 = baseCost64x64.div(args.spot64x64); } feeCost64x64 = baseCost64x64.mul(FEE_PREMIUM_64x64); feeCost64x64 -= feeCost64x64.mul(_fetchFeeDiscount64x64(args.feePayer)); baseCost64x64 -= feeCost64x64; } function _getAvailableBuybackLiquidity(uint256 shortTokenId) internal view returns (uint256 totalLiquidity) { PoolStorage.Layout storage l = PoolStorage.layout(); EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage .layout() .accountsByToken[shortTokenId]; (PoolStorage.TokenType tokenType, , ) = PoolStorage.parseTokenId( shortTokenId ); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL; uint256 length = accounts.length(); for (uint256 i = 0; i < length; i++) { address lp = accounts.at(i); if (l.isBuybackEnabled[lp][isCall]) { totalLiquidity += _balanceOf(lp, shortTokenId); } } } /** * @notice burn corresponding long and short option tokens * @param l storage layout struct * @param account holder of tokens to annihilate * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to annihilate * @return collateralFreed amount of collateral freed, including APY fee rebate */ function _annihilate( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize ) internal returns (uint256 collateralFreed) { uint256 longTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, true), maturity, strike64x64 ); uint256 shortTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, false), maturity, strike64x64 ); uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); // calculate unconsumed APY fee so that it may be refunded uint256 intervalApyFee = _calculateApyFee( l, shortTokenId, tokenAmount, maturity ); _burn(account, longTokenId, contractSize); uint256 rebate = _fulfillApyFee( l, account, shortTokenId, contractSize, intervalApyFee, isCall ); _burn(account, shortTokenId, contractSize); collateralFreed = tokenAmount + rebate + intervalApyFee; emit Annihilate(shortTokenId, contractSize); } /** * @notice deposit underlying currency, underwriting calls of that currency with respect to base currency * @param amount quantity of underlying currency to deposit * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @param creditMessageValue whether to apply message value as credit towards transfer */ function _deposit( uint256 amount, bool isCallPool, bool creditMessageValue ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); // Reset gradual divestment timestamp delete l.divestmentTimestamps[msg.sender][isCallPool]; _processPendingDeposits(l, isCallPool); l.depositedAt[msg.sender][isCallPool] = block.timestamp; _addUserTVL(l, msg.sender, isCallPool, amount); _pullFrom(l, msg.sender, amount, isCallPool, creditMessageValue); _addToDepositQueue(msg.sender, amount, isCallPool); emit Deposit(msg.sender, isCallPool, amount); } /** * @notice purchase option * @param l storage layout struct * @param account recipient of purchased option * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize size of option contract * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to purchase long position * @return feeCost quantity of tokens required to pay fees */ function _purchase( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns (uint256 baseCost, uint256 feeCost) { require(maturity > block.timestamp, "expired"); require(contractSize >= l.underlyingMinimum, "too small"); { uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); uint256 freeLiquidityTokenId = _getFreeLiquidityTokenId(isCall); require( tokenAmount <= _totalSupply(freeLiquidityTokenId) - l.totalPendingDeposits(isCall) - (_balanceOf(account, freeLiquidityTokenId) - l.pendingDepositsOf(account, isCall)), "insuf liq" ); } PoolStorage.QuoteResultInternal memory quote = _quotePurchasePrice( PoolStorage.QuoteArgsInternal( account, maturity, strike64x64, newPrice64x64, contractSize, isCall ) ); baseCost = ABDKMath64x64Token.toDecimals( quote.baseCost64x64, l.getTokenDecimals(isCall) ); feeCost = ABDKMath64x64Token.toDecimals( quote.feeCost64x64, l.getTokenDecimals(isCall) ); uint256 longTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, true), maturity, strike64x64 ); _updateCLevelAverage(l, longTokenId, contractSize, quote.cLevel64x64); // mint long option token for buyer _mint(account, longTokenId, contractSize); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); // burn free liquidity tokens from other underwriters _mintShortTokenLoop( l, account, maturity, strike64x64, contractSize, baseCost, isCall ); int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCall); // mint reserved liquidity tokens for fee receiver _processAvailableFunds( FEE_RECEIVER_ADDRESS, feeCost, isCall, true, false ); emit Purchase( account, longTokenId, contractSize, baseCost, feeCost, newPrice64x64 ); } /** * @notice reassign short position to new underwriter * @param l storage layout struct * @param account holder of positions to be reassigned * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to reassign * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to reassign short position * @return feeCost quantity of tokens required to pay fees * @return netCollateralFreed quantity of liquidity freed */ function _reassign( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns ( uint256 baseCost, uint256 feeCost, uint256 netCollateralFreed ) { (baseCost, feeCost) = _purchase( l, account, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); uint256 totalCollateralFreed = _annihilate( l, account, maturity, strike64x64, isCall, contractSize ); netCollateralFreed = totalCollateralFreed - baseCost - feeCost; } /** * @notice exercise option on behalf of holder * @dev used for processing of expired options if passed holder is zero address * @param holder owner of long option tokens to exercise * @param longTokenId long option token id * @param contractSize quantity of tokens to exercise */ function _exercise( address holder, uint256 longTokenId, uint256 contractSize ) internal { uint64 maturity; int128 strike64x64; bool isCall; bool onlyExpired = holder == address(0); { PoolStorage.TokenType tokenType; (tokenType, maturity, strike64x64) = PoolStorage.parseTokenId( longTokenId ); require( tokenType == PoolStorage.TokenType.LONG_CALL || tokenType == PoolStorage.TokenType.LONG_PUT, "invalid type" ); require(!onlyExpired || maturity < block.timestamp, "not expired"); isCall = tokenType == PoolStorage.TokenType.LONG_CALL; } PoolStorage.Layout storage l = PoolStorage.layout(); int128 spot64x64 = _update(l); if (maturity < block.timestamp) { spot64x64 = l.getPriceUpdateAfter(maturity); } require( onlyExpired || ( isCall ? (spot64x64 > strike64x64) : (spot64x64 < strike64x64) ), "not ITM" ); uint256 exerciseValue = _calculateExerciseValue( l, contractSize, spot64x64, strike64x64, isCall ); if (onlyExpired) { // burn long option tokens from multiple holders // transfer profit to and emit Exercise event for each holder in loop _burnLongTokenLoop( contractSize, exerciseValue, longTokenId, isCall ); } else { // burn long option tokens from sender _burnLongTokenInterval( holder, longTokenId, contractSize, exerciseValue, isCall ); } // burn short option tokens from multiple underwriters _burnShortTokenLoop( l, maturity, strike64x64, contractSize, exerciseValue, isCall, false ); } function _calculateExerciseValue( PoolStorage.Layout storage l, uint256 contractSize, int128 spot64x64, int128 strike64x64, bool isCall ) internal view returns (uint256 exerciseValue) { // calculate exercise value if option is in-the-money if (isCall) { if (spot64x64 > strike64x64) { exerciseValue = spot64x64.sub(strike64x64).div(spot64x64).mulu( contractSize ); } } else { if (spot64x64 < strike64x64) { exerciseValue = l.contractSizeToBaseTokenAmount( contractSize, strike64x64.sub(spot64x64), false ); } } } function _mintShortTokenLoop( PoolStorage.Layout storage l, address buyer, uint64 maturity, int128 strike64x64, uint256 contractSize, uint256 premium, bool isCall ) internal { uint256 shortTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, false), maturity, strike64x64 ); uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); // calculate anticipated APY fee so that it may be reserved uint256 apyFee = _calculateApyFee( l, shortTokenId, tokenAmount, maturity ); while (tokenAmount > 0) { address underwriter = l.liquidityQueueAscending[isCall][address(0)]; uint256 balance = _balanceOf( underwriter, _getFreeLiquidityTokenId(isCall) ); // if underwriter is in process of divestment, remove from queue if (!l.getReinvestmentStatus(underwriter, isCall)) { _burn(underwriter, _getFreeLiquidityTokenId(isCall), balance); _processAvailableFunds( underwriter, balance, isCall, true, false ); _subUserTVL(l, underwriter, isCall, balance); continue; } // if underwriter has insufficient liquidity, remove from queue if (balance < l.getMinimumAmount(isCall)) { l.removeUnderwriter(underwriter, isCall); continue; } // move interval to end of queue if underwriter is buyer if (underwriter == buyer) { l.removeUnderwriter(underwriter, isCall); l.addUnderwriter(underwriter, isCall); continue; } balance -= l.pendingDepositsOf(underwriter, isCall); Interval memory interval; // amount of liquidity provided by underwriter, accounting for reinvested premium interval.tokenAmount = (balance * (tokenAmount + premium - apyFee)) / tokenAmount; // skip underwriters whose liquidity is pending deposit processing if (interval.tokenAmount == 0) continue; // truncate interval if underwriter has excess liquidity available if (interval.tokenAmount > tokenAmount) interval.tokenAmount = tokenAmount; // calculate derived interval variables interval.contractSize = (contractSize * interval.tokenAmount) / tokenAmount; interval.payment = (premium * interval.tokenAmount) / tokenAmount; interval.apyFee = (apyFee * interval.tokenAmount) / tokenAmount; _mintShortTokenInterval( l, underwriter, buyer, shortTokenId, interval, isCall ); tokenAmount -= interval.tokenAmount; contractSize -= interval.contractSize; premium -= interval.payment; apyFee -= interval.apyFee; } } function _mintShortTokenInterval( PoolStorage.Layout storage l, address underwriter, address longReceiver, uint256 shortTokenId, Interval memory interval, bool isCallPool ) internal { // track prepaid APY fees _reserveApyFee(l, underwriter, shortTokenId, interval.apyFee); // if payment is equal to collateral amount plus APY fee, this is a manual underwrite bool isManualUnderwrite = interval.payment == interval.tokenAmount + interval.apyFee; if (!isManualUnderwrite) { // burn free liquidity tokens from underwriter _burn( underwriter, _getFreeLiquidityTokenId(isCallPool), interval.tokenAmount + interval.apyFee - interval.payment ); } // mint short option tokens for underwriter _mint(underwriter, shortTokenId, interval.contractSize); _addUserTVL( l, underwriter, isCallPool, interval.payment - interval.apyFee ); emit Underwrite( underwriter, longReceiver, shortTokenId, interval.contractSize, isManualUnderwrite ? 0 : interval.payment, isManualUnderwrite ); } function _burnLongTokenLoop( uint256 contractSize, uint256 exerciseValue, uint256 longTokenId, bool isCallPool ) internal { EnumerableSet.AddressSet storage holders = ERC1155EnumerableStorage .layout() .accountsByToken[longTokenId]; while (contractSize > 0) { address longTokenHolder = holders.at(holders.length() - 1); uint256 intervalContractSize = _balanceOf( longTokenHolder, longTokenId ); // truncate interval if holder has excess long position size if (intervalContractSize > contractSize) intervalContractSize = contractSize; uint256 intervalExerciseValue = (exerciseValue * intervalContractSize) / contractSize; _burnLongTokenInterval( longTokenHolder, longTokenId, intervalContractSize, intervalExerciseValue, isCallPool ); contractSize -= intervalContractSize; exerciseValue -= intervalExerciseValue; } } function _burnLongTokenInterval( address holder, uint256 longTokenId, uint256 contractSize, uint256 exerciseValue, bool isCallPool ) internal { _burn(holder, longTokenId, contractSize); if (exerciseValue > 0) { _processAvailableFunds( holder, exerciseValue, isCallPool, true, true ); } emit Exercise(holder, longTokenId, contractSize, exerciseValue, 0); } function _burnShortTokenLoop( PoolStorage.Layout storage l, uint64 maturity, int128 strike64x64, uint256 contractSize, uint256 payment, bool isCall, bool onlyBuybackLiquidity ) internal { uint256 shortTokenId = PoolStorage.formatTokenId( PoolStorage.getTokenType(isCall, false), maturity, strike64x64 ); uint256 tokenAmount = l.contractSizeToBaseTokenAmount( contractSize, strike64x64, isCall ); // calculate unconsumed APY fee so that it may be refunded uint256 apyFee = _calculateApyFee( l, shortTokenId, tokenAmount, maturity ); EnumerableSet.AddressSet storage underwriters = ERC1155EnumerableStorage .layout() .accountsByToken[shortTokenId]; uint256 index = underwriters.length(); while (contractSize > 0) { address underwriter = underwriters.at(--index); // skip underwriters who do not provide buyback liqudity, if applicable if ( onlyBuybackLiquidity && !l.isBuybackEnabled[underwriter][isCall] ) continue; Interval memory interval; // amount of liquidity provided by underwriter interval.contractSize = _balanceOf(underwriter, shortTokenId); // truncate interval if underwriter has excess short position size if (interval.contractSize > contractSize) interval.contractSize = contractSize; // calculate derived interval variables interval.tokenAmount = (tokenAmount * interval.contractSize) / contractSize; interval.payment = (payment * interval.contractSize) / contractSize; interval.apyFee = (apyFee * interval.contractSize) / contractSize; _burnShortTokenInterval( l, underwriter, shortTokenId, interval, isCall, onlyBuybackLiquidity ); contractSize -= interval.contractSize; tokenAmount -= interval.tokenAmount; payment -= interval.payment; apyFee -= interval.apyFee; } } function _burnShortTokenInterval( PoolStorage.Layout storage l, address underwriter, uint256 shortTokenId, Interval memory interval, bool isCallPool, bool isSale ) internal { // track prepaid APY fees uint256 refundWithRebate = interval.apyFee + _fulfillApyFee( l, underwriter, shortTokenId, interval.contractSize, interval.apyFee, isCallPool ); // burn short option tokens from underwriter _burn(underwriter, shortTokenId, interval.contractSize); bool divest = !l.getReinvestmentStatus(underwriter, isCallPool); _processAvailableFunds( underwriter, interval.tokenAmount - interval.payment + refundWithRebate, isCallPool, divest, false ); if (divest) { _subUserTVL(l, underwriter, isCallPool, interval.tokenAmount); } else { if (refundWithRebate > interval.payment) { _addUserTVL( l, underwriter, isCallPool, refundWithRebate - interval.payment ); } else if (interval.payment > refundWithRebate) { _subUserTVL( l, underwriter, isCallPool, interval.payment - refundWithRebate ); } } if (isSale) { emit AssignSale( underwriter, shortTokenId, interval.tokenAmount - interval.payment, interval.contractSize ); } else { emit AssignExercise( underwriter, shortTokenId, interval.tokenAmount - interval.payment, interval.contractSize, 0 ); } } function _calculateApyFee( PoolStorage.Layout storage l, uint256 shortTokenId, uint256 tokenAmount, uint64 maturity ) internal view returns (uint256 apyFee) { if (block.timestamp < maturity) { int128 apyFeeRate64x64 = _totalSupply(shortTokenId) == 0 ? FEE_APY_64x64 : l.feeReserveRates[shortTokenId]; apyFee = apyFeeRate64x64.mulu( (tokenAmount * (maturity - block.timestamp)) / (365 days) ); } } function _reserveApyFee( PoolStorage.Layout storage l, address underwriter, uint256 shortTokenId, uint256 amount ) internal { l.feesReserved[underwriter][shortTokenId] += amount; emit APYFeeReserved(underwriter, shortTokenId, amount); } /** * @notice credit fee receiver with fees earned and calculate rebate for underwriter * @dev short tokens which have acrrued fee must not be burned or transferred until after this helper is called * @param l storage layout struct * @param underwriter holder of short position who reserved fees * @param shortTokenId short token id whose reserved fees to pay and rebate * @param intervalContractSize size of position for which to calculate accrued fees * @param intervalApyFee quantity of fees reserved but not yet accrued * @param isCallPool true for call, false for put */ function _fulfillApyFee( PoolStorage.Layout storage l, address underwriter, uint256 shortTokenId, uint256 intervalContractSize, uint256 intervalApyFee, bool isCallPool ) internal returns (uint256 rebate) { if (intervalApyFee == 0) return 0; // calculate proportion of fees reserved corresponding to interval uint256 feesReserved = l.feesReserved[underwriter][shortTokenId]; uint256 intervalFeesReserved = (feesReserved * intervalContractSize) / _balanceOf(underwriter, shortTokenId); // deduct fees for time not elapsed l.feesReserved[underwriter][shortTokenId] -= intervalFeesReserved; // apply rebate to fees accrued rebate = _fetchFeeDiscount64x64(underwriter).mulu( intervalFeesReserved - intervalApyFee ); // credit fee receiver with fees paid uint256 intervalFeesPaid = intervalFeesReserved - intervalApyFee - rebate; _processAvailableFunds( FEE_RECEIVER_ADDRESS, intervalFeesPaid, isCallPool, true, false ); emit APYFeePaid(underwriter, shortTokenId, intervalFeesPaid); } function _addToDepositQueue( address account, uint256 amount, bool isCallPool ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); _mint(account, _getFreeLiquidityTokenId(isCallPool), amount); uint256 nextBatch = (block.timestamp / BATCHING_PERIOD) * BATCHING_PERIOD + BATCHING_PERIOD; l.pendingDeposits[account][nextBatch][isCallPool] += amount; PoolStorage.BatchData storage batchData = l.nextDeposits[isCallPool]; batchData.totalPendingDeposits += amount; batchData.eta = nextBatch; } function _processPendingDeposits(PoolStorage.Layout storage l, bool isCall) internal { PoolStorage.BatchData storage batchData = l.nextDeposits[isCall]; if (batchData.eta == 0 || block.timestamp < batchData.eta) return; int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel( l, oldLiquidity64x64, oldLiquidity64x64.add( ABDKMath64x64Token.fromDecimals( batchData.totalPendingDeposits, l.getTokenDecimals(isCall) ) ), isCall ); delete l.nextDeposits[isCall]; } function _getFreeLiquidityTokenId(bool isCall) internal view returns (uint256 freeLiqTokenId) { freeLiqTokenId = isCall ? UNDERLYING_FREE_LIQ_TOKEN_ID : BASE_FREE_LIQ_TOKEN_ID; } function _getReservedLiquidityTokenId(bool isCall) internal view returns (uint256 reservedLiqTokenId) { reservedLiqTokenId = isCall ? UNDERLYING_RESERVED_LIQ_TOKEN_ID : BASE_RESERVED_LIQ_TOKEN_ID; } function _setCLevel( PoolStorage.Layout storage l, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal { int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCallPool); int128 cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, isCallPool ); l.setCLevel(cLevel64x64, isCallPool); emit UpdateCLevel( isCallPool, cLevel64x64, oldLiquidity64x64, newLiquidity64x64 ); } function _updateCLevelAverage( PoolStorage.Layout storage l, uint256 longTokenId, uint256 contractSize, int128 cLevel64x64 ) internal { int128 supply64x64 = ABDKMath64x64Token.fromDecimals( _totalSupply(longTokenId), l.underlyingDecimals ); int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( contractSize, l.underlyingDecimals ); l.avgCLevel64x64[longTokenId] = l .avgCLevel64x64[longTokenId] .mul(supply64x64) .add(cLevel64x64.mul(contractSize64x64)) .div(supply64x64.add(contractSize64x64)); } /** * @notice calculate and store updated market state * @param l storage layout struct * @return newPrice64x64 64x64 fixed point representation of current spot price */ function _update(PoolStorage.Layout storage l) internal returns (int128 newPrice64x64) { if (l.updatedAt == block.timestamp) { return (l.getPriceUpdate(block.timestamp)); } newPrice64x64 = l.fetchPriceUpdate(); if (l.getPriceUpdate(block.timestamp) == 0) { l.setPriceUpdate(block.timestamp, newPrice64x64); } l.updatedAt = block.timestamp; _processPendingDeposits(l, true); _processPendingDeposits(l, false); } /** * @notice transfer ERC20 tokens to message sender * @param token ERC20 token address * @param amount quantity of token to transfer */ function _pushTo( address to, address token, uint256 amount ) internal { if (amount == 0) return; require(IERC20(token).transfer(to, amount), "ERC20 transfer failed"); } /** * @notice transfer ERC20 tokens from message sender * @param l storage layout struct * @param from address from which tokens are pulled from * @param amount quantity of token to transfer * @param isCallPool whether funds correspond to call or put pool * @param creditMessageValue whether to attempt to treat message value as credit */ function _pullFrom( PoolStorage.Layout storage l, address from, uint256 amount, bool isCallPool, bool creditMessageValue ) internal { uint256 credit; if (creditMessageValue) { credit = _creditMessageValue(amount, isCallPool); } if (amount > credit) { credit += _creditReservedLiquidity( from, amount - credit, isCallPool ); } if (amount > credit) { require( IERC20(l.getPoolToken(isCallPool)).transferFrom( from, address(this), amount - credit ), "ERC20 transfer failed" ); } } /** * @notice transfer or reinvest available user funds * @param account owner of funds * @param amount quantity of funds available * @param isCallPool whether funds correspond to call or put pool * @param divest whether to reserve funds or reinvest * @param transferOnDivest whether to transfer divested funds to owner */ function _processAvailableFunds( address account, uint256 amount, bool isCallPool, bool divest, bool transferOnDivest ) internal { if (divest) { if (transferOnDivest) { _pushTo( account, PoolStorage.layout().getPoolToken(isCallPool), amount ); } else { _mint( account, _getReservedLiquidityTokenId(isCallPool), amount ); } } else { _addToDepositQueue(account, amount, isCallPool); } } /** * @notice validate that pool accepts ether deposits and calculate credit amount from message value * @param amount total deposit quantity * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @return credit quantity of credit to apply */ function _creditMessageValue(uint256 amount, bool isCallPool) internal returns (uint256 credit) { if (msg.value > 0) { require( PoolStorage.layout().getPoolToken(isCallPool) == WETH_ADDRESS, "not WETH deposit" ); if (msg.value > amount) { unchecked { (bool success, ) = payable(msg.sender).call{ value: msg.value - amount }(""); require(success, "ETH refund failed"); credit = amount; } } else { credit = msg.value; } IWETH(WETH_ADDRESS).deposit{value: credit}(); } } /** * @notice calculate credit amount from reserved liquidity * @param account address whose reserved liquidity to use as credit * @param amount total deposit quantity * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @return credit quantity of credit to apply */ function _creditReservedLiquidity( address account, uint256 amount, bool isCallPool ) internal returns (uint256 credit) { uint256 reservedLiqTokenId = _getReservedLiquidityTokenId(isCallPool); uint256 balance = _balanceOf(account, reservedLiqTokenId); if (balance > 0) { credit = balance > amount ? amount : balance; _burn(account, reservedLiqTokenId, credit); } } function _mint( address account, uint256 tokenId, uint256 amount ) internal { _mint(account, tokenId, amount, ""); } function _addUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, userTVL + amount, totalTVL ); l.userTVL[user][isCallPool] = userTVL + amount; l.totalTVL[isCallPool] = totalTVL + amount; } function _subUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; uint256 newUserTVL; uint256 newTotalTVL; if (userTVL > amount) { newUserTVL = userTVL - amount; } if (totalTVL > amount) { newTotalTVL = totalTVL - amount; } IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, newUserTVL, totalTVL ); l.userTVL[user][isCallPool] = newUserTVL; l.totalTVL[isCallPool] = newTotalTVL; } /** * @notice ERC1155 hook: track eligible underwriters * @param operator transaction sender * @param from token sender * @param to token receiver * @param ids token ids transferred * @param amounts token quantities transferred * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); PoolStorage.Layout storage l = PoolStorage.layout(); for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; if (amount == 0) continue; if (from == address(0)) { l.tokenIds.add(id); } if (to == address(0) && _totalSupply(id) == 0) { l.tokenIds.remove(id); } // prevent transfer of free and reserved liquidity during waiting period if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID || id == BASE_RESERVED_LIQ_TOKEN_ID ) { if (from != address(0) && to != address(0)) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID; require( l.depositedAt[from][isCallPool] + (1 days) < block.timestamp, "liq lock 1d" ); } } if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID ) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 minimum = l.getMinimumAmount(isCallPool); if (from != address(0)) { uint256 balance = _balanceOf(from, id); if (balance > minimum && balance <= amount + minimum) { require( balance - l.pendingDepositsOf(from, isCallPool) >= amount, "Insuf balance" ); l.removeUnderwriter(from, isCallPool); } if (to != address(0)) { _subUserTVL(l, from, isCallPool, amount); _addUserTVL(l, to, isCallPool, amount); } } if (to != address(0)) { uint256 balance = _balanceOf(to, id); if (balance <= minimum && balance + amount >= minimum) { l.addUnderwriter(to, isCallPool); } } } // Update userTVL on SHORT options transfers (PoolStorage.TokenType tokenType, , ) = PoolStorage.parseTokenId( id ); if ( tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.SHORT_PUT ) { _beforeShortTokenTransfer(l, from, to, id, amount); } } } function _beforeShortTokenTransfer( PoolStorage.Layout storage l, address from, address to, uint256 id, uint256 amount ) private { // total supply has already been updated, so compare to amount rather than 0 if (from == address(0) && _totalSupply(id) == amount) { l.feeReserveRates[id] = FEE_APY_64x64; } if (to == address(0) && _totalSupply(id) == 0) { delete l.feeReserveRates[id]; } if (from != address(0) && to != address(0)) { ( PoolStorage.TokenType tokenType, uint64 maturity, int128 strike64x64 ) = PoolStorage.parseTokenId(id); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL; uint256 collateral = l.contractSizeToBaseTokenAmount( amount, strike64x64, isCall ); uint256 intervalApyFee = _calculateApyFee( l, id, collateral, maturity ); uint256 rebate = _fulfillApyFee( l, from, id, amount, intervalApyFee, isCall ); _reserveApyFee(l, to, id, intervalApyFee); bool divest = !l.getReinvestmentStatus(from, isCall); if (rebate > 0) { _processAvailableFunds(from, rebate, isCall, divest, false); } _subUserTVL( l, from, isCall, divest ? collateral : collateral - rebate ); _addUserTVL(l, to, isCall, collateral); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC165 interface registration interface * @dev see https://eips.ethereum.org/EIPS/eip-165 */ interface IERC165 { /** * @notice query whether contract has registered support for given interface * @param interfaceId interface id * @return bool whether interface is supported */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC165Storage { struct Layout { mapping(bytes4 => bool) supportedInterfaces; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC165'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function isSupportedInterface(Layout storage l, bytes4 interfaceId) internal view returns (bool) { return l.supportedInterfaces[interfaceId]; } function setSupportedInterface( Layout storage l, bytes4 interfaceId, bool status ) internal { require(interfaceId != 0xffffffff, 'ERC165: invalid interface id'); l.supportedInterfaces[interfaceId] = status; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Set implementation with enumeration functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license) */ library EnumerableSet { struct Set { bytes32[] _values; // 1-indexed to allow 0 to signify nonexistence mapping(bytes32 => uint256) _indexes; } struct Bytes32Set { Set _inner; } struct AddressSet { Set _inner; } struct UintSet { Set _inner; } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function indexOf(Bytes32Set storage set, bytes32 value) internal view returns (uint256) { return _indexOf(set._inner, value); } function indexOf(AddressSet storage set, address value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(uint256(uint160(value)))); } function indexOf(UintSet storage set, uint256 value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(value)); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } 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]; } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _indexOf(Set storage set, bytes32 value) private view returns (uint256) { unchecked { return set._indexes[value] - 1; } } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { unchecked { bytes32 last = set._values[set._values.length - 1]; // move last value to now-vacant index set._values[valueIndex - 1] = last; set._indexes[last] = valueIndex; } // clear last index set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155 } from '../IERC1155.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from './ERC1155BaseInternal.sol'; /** * @title Base ERC1155 contract * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155Base is IERC1155, ERC1155BaseInternal { /** * @inheritdoc IERC1155 */ function balanceOf(address account, uint256 id) public view virtual returns (uint256) { return _balanceOf(account, id); } /** * @inheritdoc IERC1155 */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual returns (uint256[] memory) { require( accounts.length == ids.length, 'ERC1155: accounts and ids length mismatch' ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; uint256[] memory batchBalances = new uint256[](accounts.length); unchecked { for (uint256 i; i < accounts.length; i++) { require( accounts[i] != address(0), 'ERC1155: batch balance query for the zero address' ); batchBalances[i] = balances[ids[i]][accounts[i]]; } } return batchBalances; } /** * @inheritdoc IERC1155 */ function isApprovedForAll(address account, address operator) public view virtual returns (bool) { return ERC1155BaseStorage.layout().operatorApprovals[account][operator]; } /** * @inheritdoc IERC1155 */ function setApprovalForAll(address operator, bool status) public virtual { require( msg.sender != operator, 'ERC1155: setting approval status for self' ); ERC1155BaseStorage.layout().operatorApprovals[msg.sender][ operator ] = status; emit ApprovalForAll(msg.sender, operator, status); } /** * @inheritdoc IERC1155 */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransfer(msg.sender, from, to, id, amount, data); } /** * @inheritdoc IERC1155 */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransferBatch(msg.sender, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC1155 enumerable and aggregate function interface */ interface IERC1155Enumerable { /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function totalSupply(uint256 id) external view returns (uint256); /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function totalHolders(uint256 id) external view returns (uint256); /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function accountsByToken(uint256 id) external view returns (address[] memory); /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function tokensByAccount(address account) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from '../base/ERC1155BaseInternal.sol'; import { ERC1155EnumerableStorage } from './ERC1155EnumerableStorage.sol'; /** * @title ERC1155Enumerable internal functions */ abstract contract ERC1155EnumerableInternal is ERC1155BaseInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function _totalSupply(uint256 id) internal view virtual returns (uint256) { return ERC1155EnumerableStorage.layout().totalSupply[id]; } /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function _totalHolders(uint256 id) internal view virtual returns (uint256) { return ERC1155EnumerableStorage.layout().accountsByToken[id].length(); } /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function _accountsByToken(uint256 id) internal view virtual returns (address[] memory) { EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage .layout() .accountsByToken[id]; address[] memory addresses = new address[](accounts.length()); unchecked { for (uint256 i; i < accounts.length(); i++) { addresses[i] = accounts.at(i); } } return addresses; } /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function _tokensByAccount(address account) internal view virtual returns (uint256[] memory) { EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage .layout() .tokensByAccount[account]; uint256[] memory ids = new uint256[](tokens.length()); unchecked { for (uint256 i; i < tokens.length(); i++) { ids[i] = tokens.at(i); } } return ids; } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155BaseInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from != to) { ERC1155EnumerableStorage.Layout storage l = ERC1155EnumerableStorage .layout(); mapping(uint256 => EnumerableSet.AddressSet) storage tokenAccounts = l.accountsByToken; EnumerableSet.UintSet storage fromTokens = l.tokensByAccount[from]; EnumerableSet.UintSet storage toTokens = l.tokensByAccount[to]; for (uint256 i; i < ids.length; ) { uint256 amount = amounts[i]; if (amount > 0) { uint256 id = ids[i]; if (from == address(0)) { l.totalSupply[id] += amount; } else if (_balanceOf(from, id) == amount) { tokenAccounts[id].remove(from); fromTokens.remove(id); } if (to == address(0)) { l.totalSupply[id] -= amount; } else if (_balanceOf(to, id) == 0) { tokenAccounts[id].add(to); toTokens.add(id); } } unchecked { i++; } } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155Internal } from './IERC1155Internal.sol'; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice ERC1155 interface * @dev see https://github.com/ethereum/EIPs/issues/1155 */ interface IERC1155 is IERC1155Internal, IERC165 { /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @notice query the balances of given tokens held by given addresses * @param accounts addresss to query * @param ids tokens to query * @return token balances */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @notice query approval status of given operator with respect to given address * @param account address to query for approval granted * @param operator address to query for approval received * @return whether operator is approved to spend tokens held by account */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @notice grant approval to or revoke approval from given operator to spend held tokens * @param operator address whose approval status to update * @param status whether operator should be considered approved */ function setApprovalForAll(address operator, bool status) external; /** * @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param ids list of token IDs * @param amounts list of quantities of tokens to transfer * @param data data payload */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @title ERC1155 transfer receiver interface */ interface IERC1155Receiver is IERC165 { /** * @notice validate receipt of ERC1155 transfer * @param operator executor of transfer * @param from sender of tokens * @param id token ID received * @param value quantity of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @notice validate receipt of ERC1155 batch transfer * @param operator executor of transfer * @param from sender of tokens * @param ids token IDs received * @param values quantities of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ 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; import { AddressUtils } from '../../../utils/AddressUtils.sol'; import { IERC1155Internal } from '../IERC1155Internal.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseStorage } from './ERC1155BaseStorage.sol'; /** * @title Base ERC1155 internal functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155BaseInternal is IERC1155Internal { using AddressUtils for address; /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function _balanceOf(address account, uint256 id) internal view virtual returns (uint256) { require( account != address(0), 'ERC1155: balance query for the zero address' ); return ERC1155BaseStorage.layout().balances[id][account]; } /** * @notice mint given quantity of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); _beforeTokenTransfer( msg.sender, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data ); ERC1155BaseStorage.layout().balances[id][account] += amount; emit TransferSingle(msg.sender, address(0), account, id, amount); } /** * @notice mint given quantity of tokens for given address * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _safeMint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { _mint(account, id, amount, data); _doSafeTransferAcceptanceCheck( msg.sender, address(0), account, id, amount, data ); } /** * @notice mint batch of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _mintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer( msg.sender, address(0), account, ids, amounts, data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; ) { balances[ids[i]][account] += amounts[i]; unchecked { i++; } } emit TransferBatch(msg.sender, address(0), account, ids, amounts); } /** * @notice mint batch of tokens for given address * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _safeMintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _mintBatch(account, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( msg.sender, address(0), account, ids, amounts, data ); } /** * @notice burn given quantity of tokens held by given address * @param account holder of tokens to burn * @param id token ID * @param amount quantity of tokens to burn */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); _beforeTokenTransfer( msg.sender, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), '' ); mapping(address => uint256) storage balances = ERC1155BaseStorage .layout() .balances[id]; unchecked { require( balances[account] >= amount, 'ERC1155: burn amount exceeds balances' ); balances[account] -= amount; } emit TransferSingle(msg.sender, account, address(0), id, amount); } /** * @notice burn given batch of tokens held by given address * @param account holder of tokens to burn * @param ids token IDs * @param amounts quantities of tokens to burn */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, ''); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; require( balances[id][account] >= amounts[i], 'ERC1155: burn amount exceeds balance' ); balances[id][account] -= amounts[i]; } } emit TransferBatch(msg.sender, account, address(0), ids, amounts); } /** * @notice transfer tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _transfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); _beforeTokenTransfer( operator, sender, recipient, _asSingletonArray(id), _asSingletonArray(amount), data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { uint256 senderBalance = balances[id][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[id][sender] = senderBalance - amount; } balances[id][recipient] += amount; emit TransferSingle(operator, sender, recipient, id, amount); } /** * @notice transfer tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _safeTransfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { _transfer(operator, sender, recipient, id, amount, data); _doSafeTransferAcceptanceCheck( operator, sender, recipient, id, amount, data ); } /** * @notice transfer batch of tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _transferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(operator, sender, recipient, ids, amounts, data); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; ) { uint256 token = ids[i]; uint256 amount = amounts[i]; unchecked { uint256 senderBalance = balances[token][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[token][sender] = senderBalance - amount; i++; } // balance increase cannot be unchecked because ERC1155Base neither tracks nor validates a totalSupply balances[token][recipient] += amount; } emit TransferBatch(operator, sender, recipient, ids, amounts); } /** * @notice transfer batch of tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _safeTransferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _transferBatch(operator, sender, recipient, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( operator, sender, recipient, ids, amounts, data ); } /** * @notice wrap given element in array of length 1 * @param element element to wrap * @return singleton array */ function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155Received.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155BatchReceived.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice ERC1155 hook, called before all transfers including mint and burn * @dev function should be overridden and new implementation must call super * @dev called for both single and batch transfers * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice Partial ERC1155 interface needed by internal functions */ interface IERC1155Internal { event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll( address indexed account, address indexed operator, bool approved ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { UintUtils } from './UintUtils.sol'; library AddressUtils { using UintUtils for uint256; function toString(address account) internal pure returns (string memory) { return uint256(uint160(account)).toHexString(20); } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable account, uint256 amount) internal { (bool success, ) = account.call{ value: amount }(''); require(success, 'AddressUtils: failed to send value'); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'AddressUtils: failed low-level call'); } function functionCall( address target, bytes memory data, string memory error ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, error); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'AddressUtils: failed low-level call with value' ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) internal returns (bytes memory) { require( address(this).balance >= value, 'AddressUtils: insufficient balance for call' ); return _functionCallWithValue(target, data, value, error); } function _functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) private returns (bytes memory) { require( isContract(target), 'AddressUtils: function call to non-contract' ); (bool success, bytes memory returnData) = target.call{ value: value }( data ); if (success) { return returnData; } else if (returnData.length > 0) { assembly { let returnData_size := mload(returnData) revert(add(32, returnData), returnData_size) } } else { revert(error); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC1155BaseStorage { struct Layout { mapping(uint256 => mapping(address => uint256)) balances; mapping(address => mapping(address => bool)) operatorApprovals; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Base'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title utility functions for uint256 operations * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ library UintUtils { bytes16 private constant HEX_SYMBOLS = '0123456789abcdef'; function toString(uint256 value) internal pure returns (string memory) { 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); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 length = 0; for (uint256 temp = value; temp != 0; temp >>= 8) { unchecked { length++; } } return toHexString(value, 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'; unchecked { for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_SYMBOLS[value & 0xf]; value >>= 4; } } require(value == 0, 'UintUtils: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; library ERC1155EnumerableStorage { struct Layout { mapping(uint256 => uint256) totalSupply; mapping(uint256 => EnumerableSet.AddressSet) accountsByToken; mapping(address => EnumerableSet.UintSet) tokensByAccount; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Enumerable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Interface for the Multicall utility contract */ interface IMulticall { /** * @notice batch function calls to the contract and return the results of each * @param data array of function call data payloads * @return results array of function call results */ function multicall(bytes[] calldata data) external returns (bytes[] memory results); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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 ); } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 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 signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library ABDKMath64x64Token { using ABDKMath64x64 for int128; /** * @notice convert 64x64 fixed point representation of token amount to decimal * @param value64x64 64x64 fixed point representation of token amount * @param decimals token display decimals * @return value decimal representation of token amount */ function toDecimals(int128 value64x64, uint8 decimals) internal pure returns (uint256 value) { value = value64x64.mulu(10**decimals); } /** * @notice convert decimal representation of token amount to 64x64 fixed point * @param value decimal representation of token amount * @param decimals token display decimals * @return value64x64 64x64 fixed point representation of token amount */ function fromDecimals(uint256 value, uint8 decimals) internal pure returns (int128 value64x64) { value64x64 = ABDKMath64x64.divu(value, 10**decimals); } /** * @notice convert 64x64 fixed point representation of token amount to wei (18 decimals) * @param value64x64 64x64 fixed point representation of token amount * @return value wei representation of token amount */ function toWei(int128 value64x64) internal pure returns (uint256 value) { value = toDecimals(value64x64, 18); } /** * @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point * @param value wei representation of token amount * @return value64x64 64x64 fixed point representation of token amount */ function fromWei(uint256 value) internal pure returns (int128 value64x64) { value64x64 = fromDecimals(value, 18); } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library OptionMath { using ABDKMath64x64 for int128; struct QuoteArgs { int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years) int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase int128 oldPoolState; // 64x64 fixed point representation of current state of the pool int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options bool isCall; // whether to price "call" or "put" option } struct CalculateCLevelDecayArgs { int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate int128 utilizationLowerBound64x64; int128 utilizationUpperBound64x64; int128 cLevelLowerBound64x64; int128 cLevelUpperBound64x64; int128 cConvergenceULowerBound64x64; int128 cConvergenceUUpperBound64x64; } // 64x64 fixed point integer constants int128 internal constant ONE_64x64 = 0x10000000000000000; int128 internal constant THREE_64x64 = 0x30000000000000000; // 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989 int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989 int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989 /** * @notice recalculate C-Level based on change in liquidity * @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update * @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update * @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update * @param steepness64x64 64x64 fixed point representation of steepness coefficient * @return 64x64 fixed point representation of new C-Level */ function calculateCLevel( int128 initialCLevel64x64, int128 oldPoolState64x64, int128 newPoolState64x64, int128 steepness64x64 ) external pure returns (int128) { return newPoolState64x64 .sub(oldPoolState64x64) .div( oldPoolState64x64 > newPoolState64x64 ? oldPoolState64x64 : newPoolState64x64 ) .mul(steepness64x64) .neg() .exp() .mul(initialCLevel64x64); } /** * @notice calculate the price of an option using the Premia Finance model * @param args arguments of quotePrice * @return premiaPrice64x64 64x64 fixed point representation of Premia option price * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase */ function quotePrice(QuoteArgs memory args) external pure returns ( int128 premiaPrice64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) { int128 deltaPoolState64x64 = args .newPoolState .sub(args.oldPoolState) .div(args.oldPoolState) .mul(args.steepness64x64); int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp(); int128 blackScholesPrice64x64 = _blackScholesPrice( args.varianceAnnualized64x64, args.strike64x64, args.spot64x64, args.timeToMaturity64x64, args.isCall ); cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64); slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div( deltaPoolState64x64 ); premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul( slippageCoefficient64x64 ); int128 intrinsicValue64x64; if (args.isCall && args.strike64x64 < args.spot64x64) { intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64); } else if (!args.isCall && args.strike64x64 > args.spot64x64) { intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64); } int128 collateralValue64x64 = args.isCall ? args.spot64x64 : args.strike64x64; int128 minPrice64x64 = intrinsicValue64x64.add( collateralValue64x64.mul(args.minAPY64x64).mul( args.timeToMaturity64x64 ) ); if (minPrice64x64 > premiaPrice64x64) { premiaPrice64x64 = minPrice64x64; } } /** * @notice calculate the decay of C-Level based on heat diffusion function * @param args structured CalculateCLevelDecayArgs * @return cLevelDecayed64x64 C-Level after accounting for decay */ function calculateCLevelDecay(CalculateCLevelDecayArgs memory args) external pure returns (int128 cLevelDecayed64x64) { int128 convFHighU64x64 = (args.utilization64x64 >= args.utilizationUpperBound64x64 && args.oldCLevel64x64 <= args.cLevelLowerBound64x64) ? ONE_64x64 : int128(0); int128 convFLowU64x64 = (args.utilization64x64 <= args.utilizationLowerBound64x64 && args.oldCLevel64x64 >= args.cLevelUpperBound64x64) ? ONE_64x64 : int128(0); cLevelDecayed64x64 = args .oldCLevel64x64 .sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64)) .sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)) .mul( convFLowU64x64 .mul(ONE_64x64.sub(args.utilization64x64)) .add(convFHighU64x64.mul(args.utilization64x64)) .mul(args.timeIntervalsElapsed64x64) .neg() .exp() ) .add( args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add( args.cConvergenceUUpperBound64x64.mul(convFHighU64x64) ) ); } /** * @notice calculate the exponential decay coefficient for a given interval * @param oldTimestamp timestamp of previous update * @param newTimestamp current timestamp * @return 64x64 fixed point representation of exponential decay coefficient */ function _decay(uint256 oldTimestamp, uint256 newTimestamp) internal pure returns (int128) { return ONE_64x64.sub( (-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp() ); } /** * @notice calculate Choudhury’s approximation of the Black-Scholes CDF * @param input64x64 64x64 fixed point representation of random variable * @return 64x64 fixed point representation of the approximated CDF of x */ function _N(int128 input64x64) internal pure returns (int128) { // squaring via mul is cheaper than via pow int128 inputSquared64x64 = input64x64.mul(input64x64); int128 value64x64 = (-inputSquared64x64 >> 1).exp().div( CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add( CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt()) ) ); return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64; } /** * @notice calculate the price of an option using the Black-Scholes model * @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance * @param strike64x64 64x64 fixed point representation of strike price * @param spot64x64 64x64 fixed point representation of spot price * @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years) * @param isCall whether to price "call" or "put" option * @return 64x64 fixed point representation of Black-Scholes option price */ function _blackScholesPrice( int128 varianceAnnualized64x64, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) internal pure returns (int128) { int128 cumulativeVariance64x64 = timeToMaturity64x64.mul( varianceAnnualized64x64 ); int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt(); int128 d1_64x64 = spot64x64 .div(strike64x64) .ln() .add(cumulativeVariance64x64 >> 1) .div(cumulativeVarianceSqrt64x64); int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64); if (isCall) { return spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64))); } else { return -spot64x64.mul(_N(-d1_64x64)).sub( strike64x64.mul(_N(-d2_64x64)) ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Contract ownership standard interface * @dev see https://eips.ethereum.org/EIPS/eip-173 */ interface IERC173 { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @notice get the ERC173 contract owner * @return conract owner */ function owner() external view returns (address); /** * @notice transfer contract ownership to new account * @param account address of new owner */ function transferOwnership(address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library OwnableStorage { struct Layout { address owner; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.Ownable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function setOwner(Layout storage l, address owner) internal { l.owner = owner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20Internal } from './IERC20Internal.sol'; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 is IERC20Internal { /** * @notice query the total minted token supply * @return token supply */ function totalSupply() external view returns (uint256); /** * @notice query the token balance of given account * @param account address to query * @return token balance */ function balanceOf(address account) external view returns (uint256); /** * @notice query the allowance granted from given holder to given spender * @param holder approver of allowance * @param spender recipient of allowance * @return token allowance */ function allowance(address holder, address spender) external view returns (uint256); /** * @notice grant approval to spender to spend tokens * @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729) * @param spender recipient of allowance * @param amount quantity of tokens approved for spending * @return success status (always true; otherwise function should revert) */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient on behalf of given holder * @param holder holder of tokens prior to transfer * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transferFrom( address holder, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from '../token/ERC20/IERC20.sol'; import { IERC20Metadata } from '../token/ERC20/metadata/IERC20Metadata.sol'; /** * @title WETH (Wrapped ETH) interface */ interface IWETH is IERC20, IERC20Metadata { /** * @notice convert ETH to WETH */ function deposit() external payable; /** * @notice convert WETH to ETH * @dev if caller is a contract, it should have a fallback or receive function * @param amount quantity of WETH to convert, denominated in wei */ function withdraw(uint256 amount) external; } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {FeeDiscountStorage} from "./FeeDiscountStorage.sol"; interface IFeeDiscount { event Staked( address indexed user, uint256 amount, uint256 stakePeriod, uint256 lockedUntil ); event Unstaked(address indexed user, uint256 amount); struct StakeLevel { uint256 amount; // Amount to stake uint256 discount; // Discount when amount is reached } /** * @notice Stake using IERC2612 permit * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) * @param deadline Deadline after which permit will fail * @param v V * @param r R * @param s S */ function stakeWithPermit( uint256 amount, uint256 period, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Lockup xPremia for protocol fee discounts * Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) */ function stake(uint256 amount, uint256 period) external; /** * @notice Unstake xPremia (If lockup period has ended) * @param amount The amount of xPremia to unstake */ function unstake(uint256 amount) external; ////////// // View // ////////// /** * Calculate the stake amount of a user, after applying the bonus from the lockup period chosen * @param user The user from which to query the stake amount * @return The user stake amount after applying the bonus */ function getStakeAmountWithBonus(address user) external view returns (uint256); /** * @notice Calculate the % of fee discount for user, based on his stake * @param user The _user for which the discount is for * @return Percentage of protocol fee discount (in basis point) * Ex : 1000 = 10% fee discount */ function getDiscount(address user) external view returns (uint256); /** * @notice Get stake levels * @return Stake levels * Ex : 2500 = -25% */ function getStakeLevels() external returns (StakeLevel[] memory); /** * @notice Get stake period multiplier * @param period The duration (in seconds) for which tokens are locked * @return The multiplier for this staking period * Ex : 20000 = x2 */ function getStakePeriodMultiplier(uint256 period) external returns (uint256); /** * @notice Get staking infos of a user * @param user The user address for which to get staking infos * @return The staking infos of the user */ function getUserInfo(address user) external view returns (FeeDiscountStorage.UserInfo memory); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; interface IPoolEvents { event Purchase( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 baseCost, uint256 feeCost, int128 spot64x64 ); event Sell( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 baseCost, uint256 feeCost, int128 spot64x64 ); event Exercise( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 exerciseValue, uint256 fee ); event Underwrite( address indexed underwriter, address indexed longReceiver, uint256 shortTokenId, uint256 intervalContractSize, uint256 intervalPremium, bool isManualUnderwrite ); event AssignExercise( address indexed underwriter, uint256 shortTokenId, uint256 freedAmount, uint256 intervalContractSize, uint256 fee ); event AssignSale( address indexed underwriter, uint256 shortTokenId, uint256 freedAmount, uint256 intervalContractSize ); event Deposit(address indexed user, bool isCallPool, uint256 amount); event Withdrawal( address indexed user, bool isCallPool, uint256 depositedAt, uint256 amount ); event FeeWithdrawal(bool indexed isCallPool, uint256 amount); event APYFeeReserved( address underwriter, uint256 shortTokenId, uint256 amount ); event APYFeePaid(address underwriter, uint256 shortTokenId, uint256 amount); event Annihilate(uint256 shortTokenId, uint256 amount); event UpdateCLevel( bool indexed isCall, int128 cLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64 ); event UpdateSteepness(int128 steepness64x64, bool isCallPool); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {PremiaMiningStorage} from "./PremiaMiningStorage.sol"; interface IPremiaMining { function addPremiaRewards(uint256 _amount) external; function premiaRewardsAvailable() external view returns (uint256); function getTotalAllocationPoints() external view returns (uint256); function getPoolInfo(address pool, bool isCallPool) external view returns (PremiaMiningStorage.PoolInfo memory); function getPremiaPerYear() external view returns (uint256); function addPool(address _pool, uint256 _allocPoints) external; function setPoolAllocPoints( address[] memory _pools, uint256[] memory _allocPoints ) external; function pendingPremia( address _pool, bool _isCallPool, address _user ) external view returns (uint256); function updatePool( address _pool, bool _isCallPool, uint256 _totalTVL ) external; function allocatePending( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; function claim( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {VolatilitySurfaceOracleStorage} from "./VolatilitySurfaceOracleStorage.sol"; interface IVolatilitySurfaceOracle { /** * @notice Pack IV model parameters into a single bytes32 * @dev This function is used to pack the parameters into a single variable, which is then used as input in `update` * @param params Parameters of IV model to pack * @return result The packed parameters of IV model */ function formatParams(int256[5] memory params) external pure returns (bytes32 result); /** * @notice Unpack IV model parameters from a bytes32 * @param input Packed IV model parameters to unpack * @return params The unpacked parameters of the IV model */ function parseParams(bytes32 input) external pure returns (int256[] memory params); /** * @notice Get the list of whitelisted relayers * @return The list of whitelisted relayers */ function getWhitelistedRelayers() external view returns (address[] memory); /** * @notice Get the IV model parameters of a token pair * @param base The base token of the pair * @param underlying The underlying token of the pair * @return The IV model parameters */ function getParams(address base, address underlying) external view returns (VolatilitySurfaceOracleStorage.Update memory); /** * @notice Get unpacked IV model parameters * @param base The base token of the pair * @param underlying The underlying token of the pair * @return The unpacked IV model parameters */ function getParamsUnpacked(address base, address underlying) external view returns (int256[] memory); /** * @notice Get time to maturity in years, as a 64x64 fixed point representation * @param maturity Maturity timestamp * @return Time to maturity (in years), as a 64x64 fixed point representation */ function getTimeToMaturity64x64(uint64 maturity) external view returns (int128); /** * @notice calculate the annualized volatility for given set of parameters * @param base The base token of the pair * @param underlying The underlying token of the pair * @param spot64x64 64x64 fixed point representation of spot price * @param strike64x64 64x64 fixed point representation of strike price * @param timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years) * @return 64x64 fixed point representation of annualized implied volatility, where 1 is defined as 100% */ function getAnnualizedVolatility64x64( address base, address underlying, int128 spot64x64, int128 strike64x64, int128 timeToMaturity64x64 ) external view returns (int128); /** * @notice calculate the price of an option using the Black-Scholes model * @param base The base token of the pair * @param underlying The underlying token of the pair * @param strike64x64 Strike, as a64x64 fixed point representation * @param spot64x64 Spot price, as a 64x64 fixed point representation * @param timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years) * @param isCall Whether it is for call or put * @return 64x64 fixed point representation of the Black Scholes price */ function getBlackScholesPrice64x64( address base, address underlying, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (int128); /** * @notice Get Black Scholes price as an uint256 with 18 decimals * @param base The base token of the pair * @param underlying The underlying token of the pair * @param strike64x64 Strike, as a64x64 fixed point representation * @param spot64x64 Spot price, as a 64x64 fixed point representation * @param timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years) * @param isCall Whether it is for call or put * @return Black scholes price, as an uint256 with 18 decimals */ function getBlackScholesPrice( address base, address underlying, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (uint256); /** * @notice Add relayers to the whitelist so that they can add oracle surfaces * @param accounts The addresses to add to the whitelist */ function addWhitelistedRelayers(address[] memory accounts) external; /** * @notice Remove relayers from the whitelist so that they cannot add oracle surfaces * @param accounts The addresses to remove from the whitelist */ function removeWhitelistedRelayers(address[] memory accounts) external; /** * @notice Update a list of IV model parameters * @param base List of base tokens * @param underlying List of underlying tokens * @param parameters List of IV model parameters */ function updateParams( address[] memory base, address[] memory underlying, bytes32[] memory parameters ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Partial ERC20 interface needed by internal functions */ interface IERC20Internal { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library FeeDiscountStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.staking.PremiaFeeDiscount"); struct UserInfo { uint256 balance; // Balance staked by user uint64 stakePeriod; // Stake period selected by user uint64 lockedUntil; // Timestamp at which the lock ends } struct Layout { // User data with xPREMIA balance staked and date at which lock ends mapping(address => UserInfo) userInfo; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library PremiaMiningStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.PremiaMining"); // Info of each pool. struct PoolInfo { uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block. uint256 lastRewardTimestamp; // Last timestamp that PREMIA distribution occurs uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below. } // Info of each user. struct UserInfo { uint256 reward; // Total allocated unclaimed reward uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PREMIA // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPremiaPerShare` (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. } struct Layout { // Total PREMIA left to distribute uint256 premiaAvailable; // Amount of premia distributed per year uint256 premiaPerYear; // pool -> isCallPool -> PoolInfo mapping(address => mapping(bool => PoolInfo)) poolInfo; // pool -> isCallPool -> user -> UserInfo mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 totalAllocPoint; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; library VolatilitySurfaceOracleStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.VolatilitySurfaceOracle"); uint256 internal constant PARAM_BITS = 51; uint256 internal constant PARAM_BITS_MINUS_ONE = 50; uint256 internal constant PARAM_AMOUNT = 5; // START_BIT = PARAM_BITS * (PARAM_AMOUNT - 1) uint256 internal constant START_BIT = 204; struct Update { uint256 updatedAt; bytes32 params; } struct Layout { // Base token -> Underlying token -> Update mapping(address => mapping(address => Update)) parameters; // Relayer addresses which can be trusted to provide accurate option trades EnumerableSet.AddressSet whitelistedRelayers; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function getParams( Layout storage l, address base, address underlying ) internal view returns (bytes32) { return l.parameters[base][underlying].params; } function parseParams(bytes32 input) internal pure returns (int256[] memory params) { params = new int256[](PARAM_AMOUNT); // Value to add to negative numbers to cast them to int256 int256 toAdd = (int256(-1) >> PARAM_BITS) << PARAM_BITS; assembly { let i := 0 // Value equal to -1 let mid := shl(PARAM_BITS_MINUS_ONE, 1) for { } lt(i, PARAM_AMOUNT) { } { let offset := sub(START_BIT, mul(PARAM_BITS, i)) let param := shr( offset, sub( input, shl( add(offset, PARAM_BITS), shr(add(offset, PARAM_BITS), input) ) ) ) // Check if value is a negative number and needs casting if or(eq(param, mid), gt(param, mid)) { param := add(param, toAdd) } // Store result in the params array mstore(add(params, add(0x20, mul(0x20, i))), param) i := add(i, 1) } } } function formatParams(int256[5] memory params) internal pure returns (bytes32 result) { int256 max = int256(1 << PARAM_BITS_MINUS_ONE); unchecked { for (uint256 i = 0; i < PARAM_AMOUNT; i++) { require(params[i] < max && params[i] > -max, "Out of bounds"); } } assembly { let i := 0 for { } lt(i, PARAM_AMOUNT) { } { let offset := sub(START_BIT, mul(PARAM_BITS, i)) let param := mload(add(params, mul(0x20, i))) result := add( result, shl( offset, sub(param, shl(PARAM_BITS, shr(PARAM_BITS, param))) ) ) i := add(i, 1) } } } }
query tokens held by given address account address to query return list of token ids/
function _tokensByAccount(address account) internal view virtual returns (uint256[] memory) { EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage .layout() .tokensByAccount[account]; uint256[] memory ids = new uint256[](tokens.length()); unchecked { for (uint256 i; i < tokens.length(); i++) { ids[i] = tokens.at(i); } } return ids; }
596,925
./full_match/1/0x25127685dC35d4dc96C7fEAC7370749d004C5040/sources/unibot_token.sol
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; }
17,004,661
/** *Submitted for verification at Etherscan.io on 2020-02-11 */ // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/apps-agent/contracts/standards/ERC1271.sol pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File: @aragon/apps-agent/contracts/SignatureValidator.sol pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes 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)) } } } // File: @aragon/apps-agent/contracts/standards/IERC165.sol pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { 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 ); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/apps-agent/contracts/Agent.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-165 conformance /** * @notice Tells whether this contract supports a given ERC-165 interface * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @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, ERROR_MUL_OVERFLOW); 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, ERROR_DIV_ZERO); // 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, ERROR_SUB_UNDERFLOW); 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, ERROR_ADD_OVERFLOW); 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, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/apps-voting/contracts/Voting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File: @aragon/ppf-contracts/contracts/IFeed.sol pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File: @aragon/apps-finance/contracts/Finance.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File: @aragon/apps-payroll/contracts/Payroll.sol pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File: @aragon/apps-token-manager/contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File: @aragon/apps-survey/contracts/Survey.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: @aragon/os/contracts/apm/Repo.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File: @aragon/os/contracts/apm/APMNamehash.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File: @aragon/os/contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: @aragon/os/contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: @aragon/os/contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: @aragon/os/contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File: @aragon/os/contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: @aragon/os/contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: @aragon/os/contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: @aragon/os/contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: @aragon/os/contracts/lib/ens/AbstractENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // 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); } // File: @aragon/os/contracts/lib/ens/ENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File: @aragon/os/contracts/lib/ens/PublicResolver.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File: @aragon/os/contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: @aragon/os/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: @aragon/os/contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: @aragon/os/contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File: @aragon/id/contracts/ens/IPublicResolver.sol pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File: @aragon/templates-shared/contracts/BaseTemplate.sol pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol pragma solidity 0.4.24; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol pragma solidity 0.4.24; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol pragma solidity 0.4.24; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; string public version = '0.3'; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply token total supply @param _connectorBalance total connector balance @param _connectorWeight connector weight, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in connector token @return purchase return amount */ function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _supply.mul(_depositAmount) / _connectorBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_connectorBalance); (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply token total supply @param _connectorBalance total connector @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000 @param _sellAmount sell amount, in the token itself @return sale return amount */ function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _connectorBalance; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _connectorBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight); uint256 temp1 = _connectorBalance.mul(result); uint256 temp2 = _connectorBalance << precision; return (temp1 - temp2) / result; } /** @dev given two connector balances/weights and a sell amount (in the first connector token), calculates the return for a conversion from the first connector token to the second connector token (in the second connector token) Formula: Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight)) @param _fromConnectorBalance input connector balance @param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000 @param _toConnectorBalance output connector balance @param _toConnectorWeight output connector weight, represented in ppm, 1-1000000 @param _amount input connector amount @return second connector amount */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { // validate input require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT); // special case for equal weights if (_fromConnectorWeight == _toConnectorWeight) return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromConnectorBalance.add(_amount); (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight); uint256 temp1 = _toConnectorBalance.mul(result); uint256 temp2 = _toConnectorBalance << precision; return (temp1 - temp2) / result; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' Detailed description: - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 - The natural logarithm of the input is calculated by summing up the intermediate results above - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalExp.py' Detailed description: - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible - The exponentiation of each binary exponent is given (pre-calculated) - The exponentiation of r is calculated via Taylor series for e^x, where x = r - The exponentiation of the input is calculated by multiplying the intermediate results above - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } } // File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol pragma solidity 0.4.24; contract IAragonFundraisingController { function openTrading() external; function updateTappedAmount(address _token) external; function collateralsToBeClaimed(address _collateral) public view returns (uint256); function balanceOf(address _who, address _token) public view returns (uint256); } // File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol pragma solidity 0.4.24; contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary (address indexed beneficiary); event UpdateFormula (address indexed formula); event UpdateFees (uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch ( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage) ; event CancelBatch (uint256 indexed id, address indexed collateral); event AddCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken (address indexed collateral); event UpdateCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open (); event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value); event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event UpdatePricing ( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded token] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING); controller = _controller; tokenManager = _tokenManager; token = ERC20(tokenManager.token()); formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) { Collateral storage collateral = collaterals[_collateral]; return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) { return _tokenManager.maxAccountTokens() == uint256(-1); } function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return ( _msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value ); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds tokenManager.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); tokenManager.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); tokenManager.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn); } function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } } // File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol pragma solidity 0.4.24; contract IPresale { function open() external; function close() external; function contribute(address _contributor, uint256 _value) external payable; function refund(address _contributor, uint256 _vestedPurchaseId) external; function contributionToTokens(uint256 _value) public view returns (uint256); function contributionToken() public view returns (address); } // File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol pragma solidity 0.4.24; contract ITap { function updateBeneficiary(address _beneficiary) external; function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external; function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external; function addTappedToken(address _token, uint256 _rate, uint256 _floor) external; function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external; function resetTappedToken(address _token) external; function updateTappedAmount(address _token) external; function withdraw(address _token) external; function getMaximumWithdrawal(address _token) public view returns (uint256); function rates(address _token) public view returns (uint256); } // File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol pragma solidity 0.4.24; contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE"); bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE"); bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE"); bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207; bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416; bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2; bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant TO_RESET_CAP = 10; string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS"; IPresale public presale; BatchedBancorMarketMaker public marketMaker; Agent public reserve; ITap public tap; address[] public toReset; /***** external functions *****/ /** * @notice Initialize Aragon Fundraising controller * @param _presale The address of the presale contract * @param _marketMaker The address of the market maker contract * @param _reserve The address of the reserve [pool] contract * @param _tap The address of the tap contract * @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open] */ function initialize( IPresale _presale, BatchedBancorMarketMaker _marketMaker, Agent _reserve, ITap _tap, address[] _toReset ) external onlyInit { require(isContract(_presale), ERROR_CONTRACT_IS_EOA); require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(isContract(_tap), ERROR_CONTRACT_IS_EOA); require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS); initialized(); presale = _presale; marketMaker = _marketMaker; reserve = _reserve; tap = _tap; for (uint256 i = 0; i < _toReset.length; i++) { require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS); toReset.push(_toReset[i]); } } /* generic settings related function */ /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { marketMaker.updateBeneficiary(_beneficiary); tap.updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { marketMaker.updateFees(_buyFeePct, _sellFeePct); } /* presale related functions */ /** * @notice Open presale */ function openPresale() external auth(OPEN_PRESALE_ROLE) { presale.open(); } /** * @notice Close presale and open trading */ function closePresale() external isInitialized { presale.close(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution token to be spent */ function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) { presale.contribute.value(msg.value)(msg.sender, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized { presale.refund(_contributor, _vestedPurchaseId); } /* market making related functions */ /** * @notice Open trading [enabling users to open buy and sell orders] */ function openTrading() external auth(OPEN_TRADING_ROLE) { for (uint256 i = 0; i < toReset.length; i++) { if (tap.rates(toReset[i]) != uint256(0)) { tap.resetTappedToken(toReset[i]); } } marketMaker.open(); } /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { marketMaker.openSellOrder(msg.sender, _collateral, _amount); } /** * @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimSellOrder(_seller, _batchId, _collateral); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage, uint256 _rate, uint256 _floor ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); if (_collateral != ETH) { reserve.addProtectedToken(_collateral); } if (_rate > 0) { tap.addTappedToken(_collateral, _rate, _floor); } } /** * @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past] * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function reAddCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { marketMaker.removeCollateralToken(_collateral); // the token should still be tapped to avoid being locked // the token should still be protected to avoid being spent } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* tap related functions */ /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) { tap.addTappedToken(_token, _rate, _floor); } /** * @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) { tap.updateTappedToken(_token, _rate, _floor); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { tap.updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary * @param _token The address of the token to be transfered from the reserve to the beneficiary */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { tap.withdraw(_token); } /***** public view functions *****/ function token() public view isInitialized returns (address) { return marketMaker.token(); } function contributionToken() public view isInitialized returns (address) { return presale.contributionToken(); } function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return tap.getMaximumWithdrawal(_token); } function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) { return marketMaker.collateralsToBeClaimed(_collateral); } function balanceOf(address _who, address _token) public view isInitialized returns (uint256) { uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who); if (_who == address(reserve)) { return balance.sub(tap.getMaximumWithdrawal(_token)); } else { return balance; } } /***** internal functions *****/ function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } } // File: @ablack/fundraising-presale/contracts/Presale.sol pragma solidity ^0.4.24; contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4 string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN"; string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL"; string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE"; string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD"; string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT"; string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE"; string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE"; string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE"; string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE"; string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED"; enum State { Pending, // presale is idle and pending to be started Funding, // presale has started and contributors can purchase tokens Refunding, // presale has not reached goal within period and contributors can claim refunds GoalReached, // presale has reached goal within period and trading is ready to be open Closed // presale has reached goal within period, has been closed and trading has been open } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; address public reserve; address public beneficiary; address public contributionToken; uint256 public goal; uint64 public period; uint256 public exchangeRate; uint64 public vestingCliffPeriod; uint64 public vestingCompletePeriod; uint256 public supplyOfferedPct; uint256 public fundingForBeneficiaryPct; uint64 public openDate; bool public isClosed; uint64 public vestingCliffDate; uint64 public vestingCompleteDate; uint256 public totalRaised; mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent) event SetOpenDate (uint64 date); event Close (); event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); /***** external function *****/ /** * @notice Initialize presale * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent] * @param _contributionToken The address of the token to be used to contribute * @param _goal The goal to be reached by the end of that presale [in contribution token wei] * @param _period The period within which to accept contribution for that presale * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM] * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM] * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM] * @param _openDate The date upon which that presale is to be open [ignored if 0] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, address _reserve, address _beneficiary, address _contributionToken, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY); require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN); require(_goal > 0, ERROR_INVALID_GOAL); require(_period > 0, ERROR_INVALID_TIME_PERIOD); require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE); require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD); require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD); require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT); require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT); initialized(); controller = _controller; tokenManager = _tokenManager; token = ERC20(_tokenManager.token()); reserve = _reserve; beneficiary = _beneficiary; contributionToken = _contributionToken; goal = _goal; period = _period; exchangeRate = _exchangeRate; vestingCliffPeriod = _vestingCliffPeriod; vestingCompletePeriod = _vestingCompletePeriod; supplyOfferedPct = _supplyOfferedPct; fundingForBeneficiaryPct = _fundingForBeneficiaryPct; if (_openDate != 0) { _setOpenDate(_openDate); } } /** * @notice Open presale [enabling users to contribute] */ function open() external auth(OPEN_ROLE) { require(state() == State.Pending, ERROR_INVALID_STATE); require(openDate == 0, ERROR_INVALID_STATE); _open(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _contributor The address of the contributor * @param _value The amount of contribution token to be spent */ function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) { require(state() == State.Funding, ERROR_INVALID_STATE); require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE); if (contributionToken == ETH) { require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE); } else { require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE); } _contribute(_contributor, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized { require(state() == State.Refunding, ERROR_INVALID_STATE); _refund(_contributor, _vestedPurchaseId); } /** * @notice Close presale and open trading */ function close() external nonReentrant isInitialized { require(state() == State.GoalReached, ERROR_INVALID_STATE); _close(); } /***** public view functions *****/ /** * @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution tokens to be used in that computation */ function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) { return _value.mul(exchangeRate).div(PPM); } function contributionToken() public view isInitialized returns (address) { return contributionToken; } /** * @notice Returns the current state of that presale */ function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; } else { return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; } else { return State.Refunding; } } /***** internal functions *****/ function _timeSinceOpen() internal view returns (uint64) { if (openDate == 0) { return 0; } else { return getTimestamp64().sub(openDate); } } function _setOpenDate(uint64 _date) internal { require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD); openDate = _date; _setVestingDatesWhenOpenDateIsKnown(); emit SetOpenDate(_date); } function _setVestingDatesWhenOpenDateIsKnown() internal { vestingCliffDate = openDate.add(vestingCliffPeriod); vestingCompleteDate = openDate.add(vestingCompletePeriod); } function _open() internal { _setOpenDate(getTimestamp64()); } function _contribute(address _contributor, uint256 _value) internal { uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value; if (contributionToken == ETH && _value > value) { msg.sender.transfer(_value.sub(value)); } // (contributor) ~~~> contribution tokens ~~~> (presale) if (contributionToken != ETH) { require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE); require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE); _transfer(contributionToken, _contributor, address(this), value); } // (mint ✨) ~~~> project tokens ~~~> (contributor) uint256 tokensToSell = contributionToTokens(value); tokenManager.issue(tokensToSell); uint256 vestedPurchaseId = tokenManager.assignVested( _contributor, tokensToSell, openDate, vestingCliffDate, vestingCompleteDate, true /* revokable */ ); totalRaised = totalRaised.add(value); // register contribution tokens spent in this purchase for a possible upcoming refund contributions[_contributor][vestedPurchaseId] = value; emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId); } function _refund(address _contributor, uint256 _vestedPurchaseId) internal { // recall how much contribution tokens are to be refund for this purchase uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId]; require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND); contributions[_contributor][_vestedPurchaseId] = 0; // (presale) ~~~> contribution tokens ~~~> (contributor) _transfer(contributionToken, address(this), _contributor, tokensToRefund); /** * NOTE * the following lines assume that _contributor has not transfered any of its vested tokens * for now TokenManager does not handle switching the transferrable status of its underlying token * there is thus no way to enforce non-transferrability during the presale phase only * this will be updated in a later version */ // (contributor) ~~~> project tokens ~~~> (token manager) (uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId); tokenManager.revokeVesting(_contributor, _vestedPurchaseId); // (token manager) ~~~> project tokens ~~~> (burn 💥) tokenManager.burn(address(tokenManager), tokensSold); emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId); } function _close() internal { isClosed = true; // (presale) ~~~> contribution tokens ~~~> (beneficiary) uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM); if (fundsForBeneficiary > 0) { _transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary); } // (presale) ~~~> contribution tokens ~~~> (reserve) uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this)); _transfer(contributionToken, address(this), reserve, tokensForReserve); // (mint ✨) ~~~> project tokens ~~~> (beneficiary) uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct); tokenManager.issue(tokensForBeneficiary); tokenManager.assignVested( beneficiary, tokensForBeneficiary, openDate, vestingCliffDate, vestingCompleteDate, false /* revokable */ ); // open trading controller.openTrading(); emit Close(); } function _transfer(address _token, address _from, address _to, uint256 _amount) internal { if (_token == ETH) { require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED); require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED); _to.transfer(_amount); } else { if (_from == address(this)) { require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } else { require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } } } } // File: @ablack/fundraising-tap/contracts/Tap.sol pragma solidity 0.4.24; contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE"); bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE"); bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE"); bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE"); bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30; bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc; bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd; bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288; bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT"; string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN"; string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE"; string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE"; string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED"; string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED"; string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO"; IAragonFundraisingController public controller; Vault public reserve; address public beneficiary; uint256 public batchBlocks; uint256 public maximumTapRateIncreasePct; uint256 public maximumTapFloorDecreasePct; mapping (address => uint256) public tappedAmounts; mapping (address => uint256) public rates; mapping (address => uint256) public floors; mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers] mapping (address => uint256) public lastTapUpdates; // timestamps event UpdateBeneficiary (address indexed beneficiary); event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct); event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct); event AddTappedToken (address indexed token, uint256 rate, uint256 floor); event RemoveTappedToken (address indexed token); event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor); event ResetTappedToken (address indexed token); event UpdateTappedAmount (address indexed token, uint256 tappedAmount); event Withdraw (address indexed token, uint256 amount); /***** external functions *****/ /** * @notice Initialize tap * @param _controller The address of the controller contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn] * @param _batchBlocks The number of blocks batches are to last * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE] * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _maximumTapRateIncreasePct, uint256 _maximumTapFloorDecreasePct ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS); require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); initialized(); controller = _controller; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; maximumTapRateIncreasePct = _maximumTapRateIncreasePct; maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { _updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) { require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN); require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); _addTappedToken(_token, _rate, _floor); } /** * @notice Remove tap for `_token.symbol(): string` * @param _token The address of the token to be un-tapped */ function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _removeTappedToken(_token); } /** * @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE); _updateTappedToken(_token, _rate, _floor); } /** * @notice Reset tap timestamps for `_token.symbol(): string` * @param _token The address of the token whose tap timestamps are to be reset */ function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _resetTappedToken(_token); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()` * @param _token The address of the token to be transfered */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); uint256 amount = _updateTappedAmount(_token); require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO); _withdraw(_token, amount); } /***** public view functions *****/ function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return _tappedAmount(_token); } function rates(address _token) public view isInitialized returns (uint256) { return rates[_token]; } /***** internal functions *****/ /* computation functions */ function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } function _tappedAmount(address _token) internal view returns (uint256) { uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]); uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve); uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]); uint256 tappedAmount = tappedAmounts[_token].add(flow); /** * whatever happens enough collateral should be * kept in the reserve pool to guarantee that * its balance is kept above the floor once * all pending sell orders are claimed */ /** * the reserve's balance is already below the balance to be kept * the tapped amount should be reset to zero */ if (balance <= toBeKept) { return 0; } /** * the reserve's balance minus the upcoming tap flow would be below the balance to be kept * the flow should be reduced to balance - toBeKept */ if (balance <= toBeKept.add(tappedAmount)) { return balance.sub(toBeKept); } /** * the reserve's balance minus the upcoming flow is above the balance to be kept * the flow can be added to the tapped amount */ return tappedAmount; } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) { return _maximumTapFloorDecreasePct <= PCT_BASE; } function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } function _tokenIsTapped(address _token) internal view returns (bool) { return rates[_token] != uint256(0); } function _tapRateIsValid(uint256 _rate) internal pure returns (bool) { return _rate != 0; } function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) { return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor); } function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) { uint256 rate = rates[_token]; if (_rate <= rate) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) { return true; } return false; } function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) { uint256 floor = floors[_token]; if (_floor >= floor) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (maximumTapFloorDecreasePct >= PCT_BASE) { return true; } if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) { return true; } return false; } /* state modifying functions */ function _updateTappedAmount(address _token) internal returns (uint256) { uint256 tappedAmount = _tappedAmount(_token); lastTappedAmountUpdates[_token] = _currentBatchId(); tappedAmounts[_token] = tappedAmount; emit UpdateTappedAmount(_token, tappedAmount); return tappedAmount; } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal { maximumTapRateIncreasePct = _maximumTapRateIncreasePct; emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal { maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * 1. if _token is tapped in the middle of a batch it will * reach the next batch faster than what it normally takes * to go through a batch [e.g. one block later] * 2. this will allow for a higher withdrawal than expected * a few blocks after _token is tapped * 3. this is not a problem because this extra amount is * static [at most rates[_token] * batchBlocks] and does * not increase in time */ rates[_token] = _rate; floors[_token] = _floor; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit AddTappedToken(_token, _rate, _floor); } function _removeTappedToken(address _token) internal { delete tappedAmounts[_token]; delete rates[_token]; delete floors[_token]; delete lastTappedAmountUpdates[_token]; delete lastTapUpdates[_token]; emit RemoveTappedToken(_token); } function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * withdraw before updating to keep the reserve * actual balance [balance - virtual withdrawal] * continuous in time [though a floor update can * still break this continuity] */ uint256 amount = _updateTappedAmount(_token); if (amount > 0) { _withdraw(_token, amount); } rates[_token] = _rate; floors[_token] = _floor; lastTapUpdates[_token] = getTimestamp(); emit UpdateTappedToken(_token, _rate, _floor); } function _resetTappedToken(address _token) internal { tappedAmounts[_token] = 0; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit ResetTappedToken(_token); } function _withdraw(address _token, uint256 _amount) internal { tappedAmounts[_token] = tappedAmounts[_token].sub(_amount); reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error emit Withdraw(_token, _amount); } } // File: contracts/AavegotchiTBCTemplate.sol pragma solidity 0.4.24; contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate { string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS"; string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE"; bool private constant BOARD_TRANSFERABLE = false; uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0); uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1); bool private constant SHARE_TRANSFERABLE = true; uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18); uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0); uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days); uint256 private constant BUY_FEE_PCT = 0; uint256 private constant SELL_FEE_PCT = 0; uint32 private constant DAI_RESERVE_RATIO = 333333; // 33% uint32 private constant ANT_RESERVE_RATIO = 10000; // 1% bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d; bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5; bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0; bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac; bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc; struct Cache { address dao; address boardTokenManager; address boardVoting; address vault; address finance; address shareVoting; address shareTokenManager; address reserve; address presale; address marketMaker; address tap; address controller; } address[] public collaterals; mapping (address => Cache) private cache; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID, address _dai, address _ant ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); require(isContract(_dai), ERROR_BAD_SETTINGS); require(isContract(_ant), ERROR_BAD_SETTINGS); require(_dai != _ant, ERROR_BAD_SETTINGS); collaterals.push(_dai); collaterals.push(_ant); } /***** external functions *****/ function prepareInstance( string _boardTokenName, string _boardTokenSymbol, address[] _boardMembers, uint64[3] _boardVotingSettings, uint64 _financePeriod ) external { require(_boardMembers.length > 0, ERROR_BAD_SETTINGS); require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS); // deploy DAO (Kernel dao, ACL acl) = _createDAO(); // deploy board token MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS); // install board apps TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod); // mint board tokens _mintTokens(acl, tm, _boardMembers, 1); // cache DAO _cacheDao(dao); } function installShareApps( string _shareTokenName, string _shareTokenSymbol, uint64[3] _shareVotingSettings ) external { require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS); _ensureBoardAppsCache(); Kernel dao = _daoCache(); // deploy share token MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS); // install share apps _installShareApps(dao, shareToken, _shareVotingSettings); // setup board apps permissions [now that share apps have been installed] _setupBoardPermissions(dao); } function installFundraisingApps( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) external { _ensureShareAppsCache(); Kernel dao = _daoCache(); // install fundraising apps _installFundraisingApps( dao, _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct ); // setup share apps permissions [now that fundraising apps have been installed] _setupSharePermissions(dao); // setup fundraising apps permissions _setupFundraisingPermissions(dao); } function finalizeInstance( string _id, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) external { require(bytes(_id).length > 0, ERROR_BAD_SETTINGS); require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS); require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS); require(_slippages.length == 2, ERROR_BAD_SETTINGS); _ensureFundraisingAppsCache(); Kernel dao = _daoCache(); ACL acl = ACL(dao.acl()); (, Voting shareVoting) = _shareAppsCache(); // setup collaterals _setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI); // setup EVM script registry permissions _createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting); // clear DAO permissions _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting); // register id _registerID(_id, address(dao)); // clear cache _clearCache(); } /***** internal apps installation functions *****/ function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod) internal returns (TokenManager) { TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _token, _votingSettings); Vault vault = _installVaultApp(_dao); Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod); _cacheBoardApps(tm, voting, vault, finance); return tm; } function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings) internal { TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings); _cacheShareApps(tm, voting); } function _installFundraisingApps( Kernel _dao, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) internal { _proxifyFundraisingApps(_dao); _initializePresale( _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); _initializeMarketMaker(_batchBlocks); _initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); _initializeController(); } function _proxifyFundraisingApps(Kernel _dao) internal { Agent reserve = _installNonDefaultAgentApp(_dao); Presale presale = Presale(_registerApp(_dao, PRESALE_ID)); BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID)); Tap tap = Tap(_registerApp(_dao, TAP_ID)); AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID)); _cacheFundraisingApps(reserve, presale, marketMaker, tap, controller); } /***** internal apps initialization functions *****/ function _initializePresale( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) internal { _presaleCache().initialize( _controllerCache(), _shareTMCache(), _reserveCache(), _vaultCache(), collaterals[0], _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); } function _initializeMarketMaker(uint256 _batchBlocks) internal { IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID)); (,, Vault beneficiary,) = _boardAppsCache(); (TokenManager shareTM,) = _shareAppsCache(); (Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache(); marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT); } function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal { (,, Vault beneficiary,) = _boardAppsCache(); (Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); } function _initializeController() internal { (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); address[] memory toReset = new address[](1); toReset[0] = collaterals[0]; controller.initialize(presale, marketMaker, reserve, tap, toReset); } /***** internal setup functions *****/ function _setupCollaterals( Kernel _dao, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) internal { ACL acl = ACL(_dao.acl()); (, Voting shareVoting) = _shareAppsCache(); (,,,, AragonFundraisingController controller) = _fundraisingAppsCache(); // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE()); // add DAI both as a protected collateral and a tapped token controller.addCollateralToken( collaterals[0], _virtualSupplies[0], _virtualBalances[0], DAI_RESERVE_RATIO, _slippages[0], _rateDAI, _floorDAI ); // add ANT as a protected collateral [but not as a tapped token] controller.addCollateralToken( collaterals[1], _virtualSupplies[1], _virtualBalances[1], ANT_RESERVE_RATIO, _slippages[1], 0, 0 ); // transfer ADD_COLLATERAL_TOKEN_ROLE _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); } /***** internal permissions functions *****/ function _setupBoardPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); // token manager _createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting); // voting _createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting); // vault _createVaultPermissions(acl, vault, finance, shareVoting); // finance _createFinancePermissions(acl, finance, boardVoting, shareVoting); _createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting); } function _setupSharePermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM,,,) = _boardAppsCache(); (TokenManager shareTM, Voting shareVoting) = _shareAppsCache(); (, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache(); // token manager address[] memory grantees = new address[](2); grantees[0] = address(marketMaker); grantees[1] = address(presale); acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting); _createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting); // voting _createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting); } function _setupFundraisingPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (, Voting boardVoting,,) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); // reserve address[] memory grantees = new address[](2); grantees[0] = address(tap); grantees[1] = address(marketMaker); acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting); acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting); _createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting); // presale acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting); acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting); // market maker acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting); // tap acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting); // controller // ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added] acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting); // acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting); acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting); } /***** internal cache functions *****/ function _cacheDao(Kernel _dao) internal { Cache storage c = cache[msg.sender]; c.dao = address(_dao); } function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal { Cache storage c = cache[msg.sender]; c.boardTokenManager = address(_boardTM); c.boardVoting = address(_boardVoting); c.vault = address(_vault); c.finance = address(_finance); } function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal { Cache storage c = cache[msg.sender]; c.shareTokenManager = address(_shareTM); c.shareVoting = address(_shareVoting); } function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal { Cache storage c = cache[msg.sender]; c.reserve = address(_reserve); c.presale = address(_presale); c.marketMaker = address(_marketMaker); c.tap = address(_tap); c.controller = address(_controller); } function _daoCache() internal view returns (Kernel dao) { Cache storage c = cache[msg.sender]; dao = Kernel(c.dao); } function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) { Cache storage c = cache[msg.sender]; boardTM = TokenManager(c.boardTokenManager); boardVoting = Voting(c.boardVoting); vault = Vault(c.vault); finance = Finance(c.finance); } function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); shareVoting = Voting(c.shareVoting); } function _fundraisingAppsCache() internal view returns ( Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller ) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); presale = Presale(c.presale); marketMaker = BatchedBancorMarketMaker(c.marketMaker); tap = Tap(c.tap); controller = AragonFundraisingController(c.controller); } function _clearCache() internal { Cache storage c = cache[msg.sender]; delete c.dao; delete c.boardTokenManager; delete c.boardVoting; delete c.vault; delete c.finance; delete c.shareVoting; delete c.shareTokenManager; delete c.reserve; delete c.presale; delete c.marketMaker; delete c.tap; delete c.controller; } /** * NOTE * the following functions are only needed for the presale * initialization function [which we can't compile otherwise * because of a `stack too deep` error] */ function _vaultCache() internal view returns (Vault vault) { Cache storage c = cache[msg.sender]; vault = Vault(c.vault); } function _shareTMCache() internal view returns (TokenManager shareTM) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); } function _reserveCache() internal view returns (Agent reserve) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); } function _presaleCache() internal view returns (Presale presale) { Cache storage c = cache[msg.sender]; presale = Presale(c.presale); } function _controllerCache() internal view returns (AragonFundraisingController controller) { Cache storage c = cache[msg.sender]; controller = AragonFundraisingController(c.controller); } /***** internal check functions *****/ function _ensureBoardAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.boardTokenManager != address(0) && c.boardVoting != address(0) && c.vault != address(0) && c.finance != address(0), ERROR_MISSING_CACHE ); } function _ensureShareAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.shareTokenManager != address(0) && c.shareVoting != address(0), ERROR_MISSING_CACHE ); } function _ensureFundraisingAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.reserve != address(0) && c.presale != address(0) && c.marketMaker != address(0) && c.tap != address(0) && c.controller != address(0), ERROR_MISSING_CACHE ); } /***** internal utils functions *****/ function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) { address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId)); emit InstalledApp(proxy, _appId); return proxy; } }
Returns the name associated with an ENS node, for reverse records. Defined in EIP181. node The ENS node to query. return The associated name./
function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; }
451,434
//SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import './MadMouseTroupe.sol'; import './MadMouseStaking.sol'; import './lib/Ownable.sol'; contract MadMouseTroupeMetadata is Ownable { using Strings for uint256; MadMouseTroupe public madmouseTroupe; MadMouseTroupeMetadata public metadataGenesis; string specialURI; string constant unrevealedURI = 'ipfs://QmW9NKUGYesTiYx5iSP1o82tn4Chq9i1yQV6DBnzznrHTH'; function setMadMouseAddress(MadMouseTroupe madmouseTroupe_, MadMouseTroupeMetadata metadataGenesis_) external onlyOwner { metadataGenesis = metadataGenesis_; madmouseTroupe = madmouseTroupe_; } function setSpecialURI(string calldata uri) external onlyOwner { specialURI = uri; } // will act as an ERC721 proxy function balanceOf(address user) external view returns (uint256) { return madmouseTroupe.numOwned(user); } // reuse metadata build from genesis collection function buildMouseMetadata(uint256 tokenId, uint256 level) external returns (string memory) { if (tokenId > 30) { (, bytes memory data) = address(metadataGenesis).delegatecall( abi.encodeWithSelector(this.buildMouseMetadata.selector, tokenId, level) ); return abi.decode(data, (string)); } return bytes(specialURI).length != 0 ? string.concat(specialURI, tokenId.toString()) : unrevealedURI; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.13; // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM`MMM NMM MMM MMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMhMMMMMMM MMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM MM-MMMMM MMMM MMMM lMMMDMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMM jMMMMl MM MMM M MMM M MMMM MMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMM MMMMMMMMM , ` M Y MM MMM BMMMMMM MMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMM MMMMMMMMMMMM IM MM l MMM X MM. MMMMMMMMMM MMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.nlMMMMMMMMMMMMMMMMM]._ MMMMMMMMMMMMMMMNMMMMMMMMMMMMMM // MMMMMMMMMMMMMM TMMMMMMMMMMMMMMMMMM +MMMMMMMMMMMM: rMMMMMMMMN MMMMMMMMMMMMMM // MMMMMMMMMMMM MMMMMMMMMMMMMMMM MMMMMM MMMMMMMM qMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMM^ MMMb .MMMMMMMMMMMMMMMMMMM // MMMMMMMMMM MMMMMMMMMMMMMMM MM MMMMMMM MMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM M gMMMMMMMMMMMMMMMMM // MMMMMMMMu MMMMMMMMMMMMMMM MMMMMMM .MMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMM :MMMMMMMMMMMMMMMM // MMMMMMM^ MMMMMMMMMMMMMMMl MMMMMMMM MMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMM // MMMMMMM MMMMMMMMMMMMMMMM MMMMMMMM MMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMM // MMMMMMr MMMMMMMMMMMMMMMM MMMMMMMM .MMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMM // MMMMMMM MMMMMMMMMMMMMMMMM DMMMMMMMMMM MMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMM|`MMMMMMMMMMMMMMMM q MMMMMMMMMMMMMMMMMMM MMMMMMM // MMMMMMMMMTMMMMMMMMMMMMMMM qMMMMMMMMMMMMMMMMMMgMMMMMMMMM // MMMMMMMMq MMMMMMMMMMMMMMMh jMMMMMMMMMMMMMMMMMMM nMMMMMMMM // MMMMMMMMMM MMMMMMMMMMMMMMMQ nc -MMMMMn MMMMMMMMMMMMMMMMMMMM MMMMMMMMMM // MMMMMMMMMM.MMMMMMMMMMMMMMMMMMl M1 `MMMMMMMMMMMMMMMMMMMMMMrMMMMMMMMMM // MMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMM :MMMMMMMMMM MMMMMMMMMMMM qMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMX MMMMMMMMMMMMMMM uMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMM DMMMMMMMMM IMMMMMMMMMMMMMMMMMMMMMMM M Y MMMMMMMN MMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMM MMMMMM `` M MM MMM , MMMM Mv MMM MMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMM MMh Ml . M MMMM I MMMT M :M ,MMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMM MMMMMMMMt MM MMMMB m ]MMM MMMM MMMMMM MMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMM MMMMM MMM TM MM 9U .MM _MMMMM MMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMM YMMMMMMMn MMMM +MMMMMMM1`MMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.`MMM MMM MMMMM`.MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MM M M M M M______ ____ ___ __ __ ____ ___ M M M M M M MM // MM M M M M M| || \ / \ | | || \ / _] M M M M M M MM // MM M M M M M | || D ) || | || o ) [_ M M M M M M MM // MM M M M M M M|_| |_|| /| O || | || _/ _] M M M M M MMM // MM M M M M M M | | | \| || : || | | [_ M M M M M M MM // MMM M M M M M | | | . \ || || | | | M M M M M MMM // MM M M M M M |__| |__|\_|\___/ \__,_||__| |_____|M M M M M M MM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM // MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM author: phaze MMM import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import './lib/Ownable.sol'; import {VRFBaseMainnet as VRFBase} from './lib/VRFBase.sol'; import './Gouda.sol'; import './MadMouseStaking.sol'; error PublicSaleNotActive(); error WhitelistNotActive(); error InvalidAmount(); error ExceedsLimit(); error SignatureExceedsLimit(); error IncorrectValue(); error InvalidSignature(); error ContractCallNotAllowed(); error InvalidString(); error MaxLevelReached(); error MaxNumberReached(); error MinHoldDurationRequired(); error IncorrectHash(); error CollectionAlreadyRevealed(); error CollectionNotRevealed(); error TokenDataAlreadySet(); error MintAndStakeMinHoldDurationNotReached(); interface IMadMouseMetadata { function buildMouseMetadata(uint256 tokenId, uint256 level) external view returns (string memory); } contract MadMouseTroupe is Ownable, MadMouseStaking, VRFBase { using ECDSA for bytes32; using UserDataOps for uint256; using TokenDataOps for uint256; using DNAOps for uint256; bool public publicSaleActive; uint256 constant MAX_SUPPLY = 5000; uint256 constant MAX_PER_WALLET = 50; uint256 constant PURCHASE_LIMIT = 3; uint256 constant whitelistPrice = 0.075 ether; address public metadata; address public multiSigTreasury = 0xFB79a928C5d6c5932Ba83Aa8C7145cBDCDb9fd2E; address signerAddress = 0x3ADE0c5e35cbF136245F4e4bBf4563BD151d39D1; uint256 public totalLevel2Reached; uint256 public totalLevel3Reached; uint256 constant LEVEL_2_COST = 120 * 1e18; uint256 constant LEVEL_3_COST = 350 * 1e18; uint256 constant MAX_NUM_LEVEL_2 = 3300; uint256 constant MAX_NUM_LEVEL_3 = 1200; uint256 constant NAME_CHANGE_COST = 25 * 1e18; uint256 constant BIO_CHANGE_COST = 15 * 1e18; uint256 constant MAX_LEN_NAME = 20; uint256 constant MAX_LEN_BIO = 35; uint256 constant MINT_AND_STAKE_MIN_HOLD_DURATION = 3 days; uint256 profileUpdateMinHoldDuration = 30 days; mapping(uint256 => string) public mouseName; mapping(uint256 => string) public mouseBio; string public description; string public imagesBaseURI; string constant unrevealedURI = 'ipfs://QmW9NKUGYesTiYx5iSP1o82tn4Chq9i1yQV6DBnzznrHTH'; bool private revealed; bytes32 immutable secretHash; constructor(bytes32 secretHash_) MadMouseStaking(MAX_SUPPLY, MAX_PER_WALLET) { secretHash = secretHash_; _mintAndStake(msg.sender, 30, false); } /* ------------- External ------------- */ function mint(uint256 amount, bool stake) external payable noContract { if (!publicSaleActive) revert PublicSaleNotActive(); if (PURCHASE_LIMIT < amount) revert ExceedsLimit(); uint256 price_ = price(); if (msg.value != price_ * amount) revert IncorrectValue(); if (price_ == 0) { // free mints will at first be restricted to purchase limit uint256 numMinted = _userData[msg.sender].numMinted(); if (numMinted + amount > PURCHASE_LIMIT) revert ExceedsLimit(); // free mints > 1 will be staked if (amount != 1) stake = true; } _mintAndStake(msg.sender, amount, stake); } function whitelistMint( uint256 amount, uint256 limit, bytes calldata signature, bool stake ) external payable noContract { if (publicSaleActive) revert WhitelistNotActive(); if (!validSignature(signature, limit)) revert InvalidSignature(); uint256 numMinted = _userData[msg.sender].numMinted(); if (numMinted + amount > limit) revert ExceedsLimit(); _mintAndStake(msg.sender, amount, stake); } function levelUp(uint256 tokenId) external payable { uint256 tokenData = _tokenDataOf(tokenId); address owner = tokenData.trueOwner(); if (owner != msg.sender) revert IncorrectOwner(); uint256 level = tokenData.level(); if (level > 2) revert MaxLevelReached(); if (level == 1) { if (totalLevel2Reached >= MAX_NUM_LEVEL_2) revert MaxNumberReached(); gouda.burnFrom(msg.sender, LEVEL_2_COST); ++totalLevel2Reached; } else { if (totalLevel3Reached >= MAX_NUM_LEVEL_3) revert MaxNumberReached(); gouda.burnFrom(msg.sender, LEVEL_3_COST); ++totalLevel3Reached; } uint256 newTokenData = tokenData.increaseLevel().resetOwnerCount(); if (tokenData.staked() && revealed) { uint256 userData = _claimReward(); (userData, newTokenData) = updateDataWhileStaked(userData, tokenId, tokenData, newTokenData); _userData[msg.sender] = userData; } _tokenData[tokenId] = newTokenData; } function setName(uint256 tokenId, string calldata name) external payable onlyLongtermHolder(tokenId) { if (!isValidString(name, MAX_LEN_NAME)) revert InvalidString(); gouda.burnFrom(msg.sender, NAME_CHANGE_COST); mouseName[tokenId] = name; } function setBio(uint256 tokenId, string calldata bio) external payable onlyLongtermHolder(tokenId) { if (!isValidString(bio, MAX_LEN_BIO)) revert InvalidString(); gouda.burnFrom(msg.sender, BIO_CHANGE_COST); mouseBio[tokenId] = bio; } // only to be used by owner in extreme cases when these reflect negatively on the collection // since they are automatically shown in the metadata (on OpenSea) function resetName(uint256 tokenId) external payable { address _owner = _tokenDataOf(tokenId).trueOwner(); if (_owner != msg.sender && owner() != msg.sender) revert IncorrectOwner(); delete mouseName[tokenId]; } function resetBio(uint256 tokenId) external payable { address _owner = _tokenDataOf(tokenId).trueOwner(); if (_owner != msg.sender && owner() != msg.sender) revert IncorrectOwner(); delete mouseBio[tokenId]; } /* ------------- View ------------- */ function price() public view returns (uint256) { return totalSupply < 3500 ? 0 ether : .02 ether; } function tokenURI(uint256 tokenId) public view override returns (string memory) { if (!_exists(tokenId)) revert NonexistentToken(); if (!revealed || address(metadata) == address(0)) return unrevealedURI; return IMadMouseMetadata(address(metadata)).buildMouseMetadata(tokenId, this.getLevel(tokenId)); } function previewTokenURI(uint256 tokenId, uint256 level) external view returns (string memory) { if (!_exists(tokenId)) revert NonexistentToken(); if (!revealed || address(metadata) == address(0)) return unrevealedURI; return IMadMouseMetadata(address(metadata)).buildMouseMetadata(tokenId, level); } function getDNA(uint256 tokenId) external view onceRevealed returns (uint256) { if (!_exists(tokenId)) revert NonexistentToken(); return computeDNA(tokenId); } function getLevel(uint256 tokenId) external view returns (uint256) { return _tokenDataOf(tokenId).level(); } /* ------------- Private ------------- */ function validSignature(bytes calldata signature, uint256 limit) private view returns (bool) { bytes32 msgHash = keccak256(abi.encode(address(this), msg.sender, limit)); return msgHash.toEthSignedMessageHash().recover(signature) == signerAddress; } // not guarded for reveal function computeDNA(uint256 tokenId) private view returns (uint256) { return uint256(keccak256(abi.encodePacked(randomSeed, tokenId))); } /* ------------- Owner ------------- */ function setPublicSaleActive(bool active) external payable onlyOwner { publicSaleActive = active; } function setProfileUpdateMinHoldDuration(uint256 duration) external payable onlyOwner { profileUpdateMinHoldDuration = duration; } function giveAway(address[] calldata to, uint256[] calldata amounts) external payable onlyOwner { for (uint256 i; i < to.length; ++i) _mintAndStake(to[i], amounts[i], false); } function setSignerAddress(address address_) external payable onlyOwner { signerAddress = address_; } function setMetadataAddress(address metadata_) external payable onlyOwner { metadata = metadata_; } function withdraw() external payable onlyOwner { uint256 balance = address(this).balance; multiSigTreasury.call{value: balance}(''); } function recoverToken(IERC20 token) external payable onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } function setDescription(string memory description_) external payable onlyOwner { description = description_; } // requires that the reveal is first done through chainlink vrf function setImagesBaseURI(string memory uri) external payable onlyOwner onceRevealed { imagesBaseURI = uri; } // extra security for reveal: // the owner sets a hash of a secret seed // once chainlink randomness fulfills, the secret is revealed and shifts the secret seed set by chainlink // Why? The final randomness should come from a trusted third party, // however devs need time to generate the collection from the metadata. // There is a time-frame in which an unfair advantage is gained after the seed is set and before the metadata is revealed. // This eliminates any possibility of the team generating an unfair seed and any unfair advantage by snipers. function reveal(string memory _imagesBaseURI, bytes32 secretSeed_) external payable onlyOwner whenRandomSeedSet { if (revealed) revert CollectionAlreadyRevealed(); if (secretHash != keccak256(abi.encode(secretSeed_))) revert IncorrectHash(); revealed = true; imagesBaseURI = _imagesBaseURI; _shiftRandomSeed(uint256(secretSeed_)); } /* ------------- Hooks ------------- */ // update role, level information when staking function _beforeStakeDataTransform( uint256 tokenId, uint256 userData, uint256 tokenData ) internal view override returns (uint256, uint256) { // assumption that mint&stake won't have revealed yet if (!tokenData.mintAndStake() && tokenData.role() == 0 && revealed) tokenData = tokenData.setRoleAndRarity(computeDNA(tokenId)); userData = userData.updateUserDataStake(tokenData); return (userData, tokenData); } function _beforeUnstakeDataTransform( uint256, uint256 userData, uint256 tokenData ) internal view override returns (uint256, uint256) { userData = userData.updateUserDataUnstake(tokenData); if (tokenData.mintAndStake() && block.timestamp - tokenData.lastTransfer() < MINT_AND_STAKE_MIN_HOLD_DURATION) revert MintAndStakeMinHoldDurationNotReached(); return (userData, tokenData); } function updateStakedTokenData(uint256[] calldata tokenIds) external payable onceRevealed { uint256 userData = _claimReward(); uint256 tokenId; uint256 tokenData; for (uint256 i; i < tokenIds.length; ++i) { tokenId = tokenIds[i]; tokenData = _tokenDataOf(tokenId); if (tokenData.trueOwner() != msg.sender) revert IncorrectOwner(); if (!tokenData.staked()) revert TokenIdUnstaked(); // only useful for staked ids if (tokenData.role() != 0) revert TokenDataAlreadySet(); (userData, tokenData) = updateDataWhileStaked(userData, tokenId, tokenData, tokenData); _tokenData[tokenId] = tokenData; } _userData[msg.sender] = userData; } // note: must be guarded by check for revealed function updateDataWhileStaked( uint256 userData, uint256 tokenId, uint256 oldTokenData, uint256 newTokenData ) private view returns (uint256, uint256) { uint256 userDataX; // add in the role and rarity data if not already uint256 tokenDataX = newTokenData.role() != 0 ? newTokenData : newTokenData.setRoleAndRarity(computeDNA(tokenId)); // update userData as if to unstake with old tokenData and stake with new tokenData userDataX = userData.updateUserDataUnstake(oldTokenData).updateUserDataStake(tokenDataX); return applySafeDataTransform(userData, newTokenData, userDataX, tokenDataX); } // simulates a token update and only returns ids != 0 if // the user gets a bonus increase upon updating staked data function shouldUpdateStakedIds(address user) external view returns (uint256[] memory) { if (!revealed) return new uint256[](0); uint256[] memory stakedIds = this.tokenIdsOf(user, 1); uint256 userData = _userData[user]; uint256 oldTotalBonus = totalBonus(user, userData); uint256 tokenData; for (uint256 i; i < stakedIds.length; ++i) { tokenData = _tokenDataOf(stakedIds[i]); if (tokenData.role() == 0) (userData, ) = updateDataWhileStaked(userData, stakedIds[i], tokenData, tokenData); else stakedIds[i] = 0; } uint256 newTotalBonus = totalBonus(user, userData); return (newTotalBonus > oldTotalBonus) ? stakedIds : new uint256[](0); } /* ------------- Modifier ------------- */ modifier onceRevealed() { if (!revealed) revert CollectionNotRevealed(); _; } modifier noContract() { if (tx.origin != msg.sender) revert ContractCallNotAllowed(); _; } modifier onlyLongtermHolder(uint256 tokenId) { uint256 tokenData = _tokenDataOf(tokenId); uint256 timeHeld = block.timestamp - tokenData.lastTransfer(); if (tokenData.trueOwner() != msg.sender) revert IncorrectOwner(); if (timeHeld < profileUpdateMinHoldDuration) revert MinHoldDurationRequired(); _; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './Gouda.sol'; import './lib/ERC721M.sol'; import './lib/Ownable.sol'; error InvalidBoostToken(); error TransferFailed(); error BoostInEffect(); error NotSpecialGuestOwner(); error SpecialGuestIndexMustDiffer(); abstract contract MadMouseStaking is ERC721M, Ownable { using UserDataOps for uint256; event BoostActivation(address token); Gouda public gouda; uint256 constant dailyReward = 0.3 * 1e18; uint256 constant ROLE_BONUS_3 = 2000; uint256 constant ROLE_BONUS_5 = 3500; uint256 constant TOKEN_BONUS = 1000; uint256 constant TIME_BONUS = 1000; uint256 constant RARITY_BONUS = 1000; uint256 constant OG_BONUS = 2000; uint256 constant SPECIAL_GUEST_BONUS = 1000; uint256 immutable OG_BONUS_END; uint256 immutable LAST_GOUDA_EMISSION_DATE; uint256 constant TOKEN_BOOST_DURATION = 9 days; uint256 constant TOKEN_BOOST_COOLDOWN = 9 days; uint256 constant TIME_BONUS_STAKE_DURATION = 30 days; mapping(IERC20 => uint256) tokenBoostCosts; mapping(uint256 => IERC721) specialGuests; mapping(IERC721 => bytes4) specialGuestsNumStakedSelector; address constant burnAddress = 0x000000000000000000000000000000000000dEaD; constructor(uint256 maxSupply_, uint256 maxPerWallet_) ERC721M('MadMouseCircus', 'MMC', 1, maxSupply_, maxPerWallet_) { OG_BONUS_END = block.timestamp + 60 days; LAST_GOUDA_EMISSION_DATE = block.timestamp + 5 * 365 days; } /* ------------- External ------------- */ function burnForBoost(IERC20 token) external payable { uint256 userData = _claimReward(); uint256 boostCost = tokenBoostCosts[token]; if (boostCost == 0) revert InvalidBoostToken(); bool success = token.transferFrom(msg.sender, burnAddress, boostCost); if (!success) revert TransferFailed(); uint256 boostStart = userData.boostStart(); if (boostStart + TOKEN_BOOST_DURATION + TOKEN_BOOST_COOLDOWN > block.timestamp) revert BoostInEffect(); _userData[msg.sender] = userData.setBoostStart(block.timestamp); emit BoostActivation(address(token)); } function claimSpecialGuest(uint256 collectionIndex) external payable { uint256 userData = _claimReward(); uint256 specialGuestIndexOld = userData.specialGuestIndex(); if (collectionIndex == specialGuestIndexOld) revert SpecialGuestIndexMustDiffer(); if (collectionIndex != 0 && !hasSpecialGuest(msg.sender, collectionIndex)) revert NotSpecialGuestOwner(); _userData[msg.sender] = userData.setSpecialGuestIndex(collectionIndex); } function clearSpecialGuestData() external payable { _userData[msg.sender] = _userData[msg.sender].setSpecialGuestIndex(0); } /* ------------- Internal ------------- */ function tokenBonus(uint256 userData) private view returns (uint256) { unchecked { uint256 lastClaimed = userData.lastClaimed(); uint256 boostEnd = userData.boostStart() + TOKEN_BOOST_DURATION; if (lastClaimed > boostEnd) return 0; if (block.timestamp <= boostEnd) return TOKEN_BONUS; // follows: lastClaimed <= boostEnd < block.timestamp // user is half-way through running out of boost, calculate exact fraction, // as if claim was initiated once at end of boost and once now // bonus * (time delta spent with boost bonus) / (complete duration) return (TOKEN_BONUS * (boostEnd - lastClaimed)) / (block.timestamp - lastClaimed); } } function roleBonus(uint256 userData) private pure returns (uint256) { uint256 numRoles = userData.uniqueRoleCount(); return numRoles < 3 ? 0 : numRoles < 5 ? ROLE_BONUS_3 : ROLE_BONUS_5; } function rarityBonus(uint256 userData) private pure returns (uint256) { unchecked { uint256 numStaked = userData.numStaked(); return numStaked == 0 ? 0 : (userData.rarityPoints() * RARITY_BONUS) / numStaked; } } function OGBonus(uint256 userData) private view returns (uint256) { unchecked { uint256 count = userData.OGCount(); uint256 lastClaimed = userData.lastClaimed(); if (count == 0 || lastClaimed > OG_BONUS_END) return 0; // follows: 0 < count <= numStaked uint256 bonus = (count * OG_BONUS) / userData.numStaked(); if (block.timestamp <= OG_BONUS_END) return bonus; // follows: lastClaimed <= OG_BONUS_END < block.timestamp return (bonus * (OG_BONUS_END - lastClaimed)) / (block.timestamp - lastClaimed); } } function timeBonus(uint256 userData) private view returns (uint256) { unchecked { uint256 stakeStart = userData.stakeStart(); uint256 stakeBonusStart = stakeStart + TIME_BONUS_STAKE_DURATION; if (block.timestamp < stakeBonusStart) return 0; uint256 lastClaimed = userData.lastClaimed(); if (lastClaimed >= stakeBonusStart) return TIME_BONUS; // follows: lastClaimed < stakeBonusStart <= block.timestamp return (TIME_BONUS * (block.timestamp - stakeBonusStart)) / (block.timestamp - lastClaimed); } } function hasSpecialGuest(address user, uint256 index) public view returns (bool) { if (index == 0) return false; // first 18 addresses are hardcoded to save gas if (index < 19) { address[19] memory guests = [ 0x0000000000000000000000000000000000000000, // 0: reserved 0x4BB33f6E69fd62cf3abbcC6F1F43b94A5D572C2B, // 1: Bears Deluxe 0xbEA8123277142dE42571f1fAc045225a1D347977, // 2: DystoPunks 0x12d2D1beD91c24f878F37E66bd829Ce7197e4d14, // 3: Galactic Apes 0x0c2E57EFddbA8c768147D1fdF9176a0A6EBd5d83, // 4: Kaiju Kingz 0x6E5a65B5f9Dd7b1b08Ff212E210DCd642DE0db8B, // 5: Octohedz 0x17eD38f5F519C6ED563BE6486e629041Bed3dfbC, // 6: PXQuest Adventurer 0xdd67892E722bE69909d7c285dB572852d5F8897C, // 7: Scholarz 0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e, // 8: Doodles 0x6F44Db5ed6b86d9cC6046D0C78B82caD9E600F6a, // 9: Digi Dragonz 0x219B8aB790dECC32444a6600971c7C3718252539, // 10: Sneaky Vampire Syndicate 0xC4a0b1E7AA137ADA8b2F911A501638088DFdD508, // 11: Uninterested Unicorns 0x9712228cEeDA1E2dDdE52Cd5100B88986d1Cb49c, // 12: Wulfz 0x56b391339615fd0e88E0D370f451fA91478Bb20F, // 13: Ethalien 0x648E8428e0104Ec7D08667866a3568a72Fe3898F, // 14: Dysto Apez 0xd2F668a8461D6761115dAF8Aeb3cDf5F40C532C6, // 15: Karafuru 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731, // 16: Anonymice 0xcB4307F1c3B5556256748DDF5B86E81258990B3C, // 17: The Other Side 0x5c211B8E4f93F00E2BD68e82F4E00FbB3302b35c // 18: Global Citizen Club ]; if (IERC721(guests[index]).balanceOf(user) != 0) return true; if (index == 10) return ISVSGraveyard(guests[index]).getBuriedCount(user) != 0; else if (index == 12) return AWOO(guests[index]).getStakedAmount(user) != 0; else if (index == 16) return CheethV2(guests[index]).stakedMiceQuantity(user) != 0; } else { IERC721 collection = specialGuests[index]; if (address(collection) != address(0)) { if (collection.balanceOf(user) != 0) return true; bytes4 selector = specialGuestsNumStakedSelector[collection]; if (selector != bytes4(0)) { (bool success, bytes memory data) = address(collection).staticcall( abi.encodeWithSelector(selector, user) ); return success && abi.decode(data, (uint256)) != 0; } } } return false; } function specialGuestBonus(address user, uint256 userData) private view returns (uint256) { uint256 index = userData.specialGuestIndex(); if (!hasSpecialGuest(user, index)) return 0; return SPECIAL_GUEST_BONUS; } function _pendingReward(address user, uint256 userData) internal view override returns (uint256) { uint256 lastClaimed = userData.lastClaimed(); if (lastClaimed == 0) return 0; uint256 timestamp = min(LAST_GOUDA_EMISSION_DATE, block.timestamp); unchecked { uint256 delta = timestamp < lastClaimed ? 0 : timestamp - lastClaimed; uint256 reward = (userData.baseReward() * delta * dailyReward) / (1 days); if (reward == 0) return 0; uint256 bonus = totalBonus(user, userData); // needs to be calculated per myriad for more accuracy return (reward * (10000 + bonus)) / 10000; } } function totalBonus(address user, uint256 userData) internal view returns (uint256) { unchecked { return roleBonus(userData) + specialGuestBonus(user, userData) + rarityBonus(userData) + OGBonus(userData) + timeBonus(userData) + tokenBonus(userData); } } function _payoutReward(address user, uint256 reward) internal override { if (reward != 0) gouda.mint(user, reward); } /* ------------- View ------------- */ // for convenience struct StakeInfo { uint256 numStaked; uint256 roleCount; uint256 roleBonus; uint256 specialGuestBonus; uint256 tokenBoost; uint256 stakeStart; uint256 timeBonus; uint256 rarityPoints; uint256 rarityBonus; uint256 OGCount; uint256 OGBonus; uint256 totalBonus; uint256 multiplierBase; uint256 dailyRewardBase; uint256 dailyReward; uint256 pendingReward; int256 tokenBoostDelta; uint256[3] levelBalances; } // calculates momentary totalBonus for display instead of effective bonus function getUserStakeInfo(address user) external view returns (StakeInfo memory info) { unchecked { uint256 userData = _userData[user]; info.numStaked = userData.numStaked(); info.roleCount = userData.uniqueRoleCount(); info.roleBonus = roleBonus(userData) / 100; info.specialGuestBonus = specialGuestBonus(user, userData) / 100; info.tokenBoost = (block.timestamp < userData.boostStart() + TOKEN_BOOST_DURATION) ? TOKEN_BONUS / 100 : 0; info.stakeStart = userData.stakeStart(); info.timeBonus = (info.stakeStart > 0 && block.timestamp > userData.stakeStart() + TIME_BONUS_STAKE_DURATION) ? TIME_BONUS / 100 : 0; info.OGCount = userData.OGCount(); info.OGBonus = (block.timestamp > OG_BONUS_END || userData.numStaked() == 0) ? 0 : (userData.OGCount() * OG_BONUS) / userData.numStaked() / 100; info.rarityPoints = userData.rarityPoints(); info.rarityBonus = rarityBonus(userData) / 100; info.totalBonus = info.roleBonus + info.specialGuestBonus + info.tokenBoost + info.timeBonus + info.rarityBonus + info.OGBonus; info.multiplierBase = userData.baseReward(); info.dailyRewardBase = info.multiplierBase * dailyReward; info.dailyReward = (info.dailyRewardBase * (100 + info.totalBonus)) / 100; info.pendingReward = _pendingReward(user, userData); info.tokenBoostDelta = int256(TOKEN_BOOST_DURATION) - int256(block.timestamp - userData.boostStart()); info.levelBalances = userData.levelBalances(); } } /* ------------- Owner ------------- */ function setGoudaToken(Gouda gouda_) external payable onlyOwner { gouda = gouda_; } function setSpecialGuests(IERC721[] calldata collections, uint256[] calldata indices) external payable onlyOwner { for (uint256 i; i < indices.length; ++i) { uint256 index = indices[i]; require(index != 0); specialGuests[index] = collections[i]; } } function setSpecialGuestStakingSelector(IERC721 collection, bytes4 selector) external payable onlyOwner { specialGuestsNumStakedSelector[collection] = selector; } function setBoostTokens(IERC20[] calldata _boostTokens, uint256[] calldata _boostCosts) external payable onlyOwner { for (uint256 i; i < _boostTokens.length; ++i) tokenBoostCosts[_boostTokens[i]] = _boostCosts[i]; } } // Special guest's staking interfaces interface ISVSGraveyard { function getBuriedCount(address burier) external view returns (uint256); } interface AWOO { function getStakedAmount(address staker) external view returns (uint256); } interface CheethV2 { function stakedMiceQuantity(address _address) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; error CallerIsNotTheOwner(); abstract contract Ownable { address _owner; constructor() { _owner = msg.sender; } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { if (msg.sender != _owner) revert CallerIsNotTheOwner(); _; } function transferOwnership(address newOwner) external onlyOwner { _owner = newOwner; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = 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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@chainlink/contracts/src/v0.8/VRFConsumerBase.sol'; import './Ownable.sol'; error RandomSeedNotSet(); error RandomSeedAlreadySet(); contract VRFBase is VRFConsumerBase, Ownable { bytes32 private immutable keyHash; uint256 private immutable fee; uint256 public randomSeed; constructor( bytes32 keyHash_, uint256 fee_, address vrfCoordinator_, address link_ ) VRFConsumerBase(vrfCoordinator_, link_) { keyHash = keyHash_; fee = fee_; } /* ------------- Owner ------------- */ function requestRandomSeed() external payable virtual onlyOwner whenRandomSeedUnset { requestRandomness(keyHash, fee); } // this function should not be needed and is just an emergency fail-safe if // for some reason chainlink is not able to fulfill the randomness callback function forceFulfillRandomness() external payable virtual onlyOwner whenRandomSeedUnset { randomSeed = uint256(blockhash(block.number - 1)); } /* ------------- Internal ------------- */ function fulfillRandomness(bytes32, uint256 randomNumber) internal virtual override { randomSeed = randomNumber; } function _shiftRandomSeed(uint256 randomNumber) internal { randomSeed = uint256(keccak256(abi.encode(randomSeed, randomNumber))); } /* ------------- View ------------- */ function randomSeedSet() public view returns (bool) { return randomSeed > 0; } /* ------------- Modifier ------------- */ modifier whenRandomSeedSet() { if (!randomSeedSet()) revert RandomSeedNotSet(); _; } modifier whenRandomSeedUnset() { if (randomSeedSet()) revert RandomSeedAlreadySet(); _; } } // get your shit together Chainlink... contract VRFBaseMainnet is VRFBase( 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445, 2 * 1e18, 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, 0x514910771AF9Ca656af840dff83E8264EcF986CA ) { } contract VRFBaseRinkeby is VRFBase( 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311, 0.1 * 1e18, 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B, 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 ) {} contract VRFBaseMumbai is VRFBase( 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4, 0.0001 * 1e18, 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, 0x326C977E6efc84E512bB9C30f76E30c160eD06FB ) {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/access/AccessControl.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; contract Gouda is ERC20, AccessControl { bytes32 constant MINT_AUTHORITY = keccak256('MINT_AUTHORITY'); bytes32 constant BURN_AUTHORITY = keccak256('BURN_AUTHORITY'); bytes32 constant TREASURY = keccak256('TREASURY'); address public multiSigTreasury = 0xFB79a928C5d6c5932Ba83Aa8C7145cBDCDb9fd2E; constructor(address madmouse) ERC20('Gouda', 'GOUDA') { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINT_AUTHORITY, madmouse); _setupRole(BURN_AUTHORITY, madmouse); _setupRole(TREASURY, multiSigTreasury); _mint(multiSigTreasury, 200_000 * 1e18); } /* ------------- Restricted ------------- */ function mint(address user, uint256 amount) external onlyRole(MINT_AUTHORITY) { _mint(user, amount); } /* ------------- ERC20Burnable ------------- */ function burnFrom(address account, uint256 amount) public { if (!hasRole(BURN_AUTHORITY, msg.sender)) _spendAllowance(account, msg.sender, amount); _burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import './ERC721MLibrary.sol'; error IncorrectOwner(); error NonexistentToken(); error QueryForZeroAddress(); error TokenIdUnstaked(); error ExceedsStakingLimit(); error MintToZeroAddress(); error MintZeroQuantity(); error MintMaxSupplyReached(); error MintMaxWalletReached(); error CallerNotOwnerNorApproved(); error ApprovalToCaller(); error ApproveToCurrentOwner(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); abstract contract ERC721M { using Address for address; using Strings for uint256; using UserDataOps for uint256; using TokenDataOps for uint256; event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); string public name; string public symbol; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; uint256 public totalSupply; uint256 immutable startingIndex; uint256 immutable collectionSize; uint256 immutable maxPerWallet; // note: hard limit of 255, otherwise overflows can happen uint256 constant stakingLimit = 100; mapping(uint256 => uint256) internal _tokenData; mapping(address => uint256) internal _userData; constructor( string memory name_, string memory symbol_, uint256 startingIndex_, uint256 collectionSize_, uint256 maxPerWallet_ ) { name = name_; symbol = symbol_; collectionSize = collectionSize_; maxPerWallet = maxPerWallet_; startingIndex = startingIndex_; } /* ------------- External ------------- */ function stake(uint256[] calldata tokenIds) external payable { uint256 userData = _claimReward(); for (uint256 i; i < tokenIds.length; ++i) userData = _stake(msg.sender, tokenIds[i], userData); _userData[msg.sender] = userData; } function unstake(uint256[] calldata tokenIds) external payable { uint256 userData = _claimReward(); for (uint256 i; i < tokenIds.length; ++i) userData = _unstake(msg.sender, tokenIds[i], userData); _userData[msg.sender] = userData; } function claimReward() external payable { _userData[msg.sender] = _claimReward(); } /* ------------- Private ------------- */ function _stake( address from, uint256 tokenId, uint256 userData ) private returns (uint256) { uint256 _numStaked = userData.numStaked(); uint256 tokenData = _tokenDataOf(tokenId); address owner = tokenData.owner(); if (_numStaked >= stakingLimit) revert ExceedsStakingLimit(); if (owner != from) revert IncorrectOwner(); delete getApproved[tokenId]; // hook, used for reading DNA, updating role balances, (uint256 userDataX, uint256 tokenDataX) = _beforeStakeDataTransform(tokenId, userData, tokenData); (userData, tokenData) = applySafeDataTransform(userData, tokenData, userDataX, tokenDataX); tokenData = tokenData.setstaked(); userData = userData.decreaseBalance(1).increaseNumStaked(1); if (_numStaked == 0) userData = userData.setStakeStart(block.timestamp); _tokenData[tokenId] = tokenData; emit Transfer(from, address(this), tokenId); return userData; } function _unstake( address to, uint256 tokenId, uint256 userData ) private returns (uint256) { uint256 tokenData = _tokenDataOf(tokenId); address owner = tokenData.trueOwner(); bool isStaked = tokenData.staked(); if (owner != to) revert IncorrectOwner(); if (!isStaked) revert TokenIdUnstaked(); (uint256 userDataX, uint256 tokenDataX) = _beforeUnstakeDataTransform(tokenId, userData, tokenData); (userData, tokenData) = applySafeDataTransform(userData, tokenData, userDataX, tokenDataX); // if mintAndStake flag is set, we need to make sure that next tokenData is set // because tokenData in this case is implicit and needs to carry over if (tokenData.mintAndStake()) { unchecked { tokenData = _ensureTokenDataSet(tokenId + 1, tokenData).unsetMintAndStake(); } } tokenData = tokenData.unsetstaked(); userData = userData.increaseBalance(1).decreaseNumStaked(1).setStakeStart(block.timestamp); _tokenData[tokenId] = tokenData; emit Transfer(address(this), to, tokenId); return userData; } /* ------------- Internal ------------- */ function _mintAndStake( address to, uint256 quantity, bool stake_ ) internal { unchecked { uint256 totalSupply_ = totalSupply; uint256 startTokenId = startingIndex + totalSupply_; uint256 userData = _userData[to]; uint256 numMinted_ = userData.numMinted(); if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); if (totalSupply_ + quantity > collectionSize) revert MintMaxSupplyReached(); if (numMinted_ + quantity > maxPerWallet && address(this).code.length != 0) revert MintMaxWalletReached(); // don't update for airdrops if (to == msg.sender) userData = userData.increaseNumMinted(quantity); uint256 tokenData = TokenDataOps.newTokenData(to, block.timestamp, stake_); // don't have to care about next token data if only minting one // could optimize to implicitly flag last token id of batch if (quantity == 1) tokenData = tokenData.flagNextTokenDataSet(); if (stake_) { uint256 _numStaked = userData.numStaked(); userData = claimReward(userData); userData = userData.increaseNumStaked(quantity); if (_numStaked + quantity > stakingLimit) revert ExceedsStakingLimit(); if (_numStaked == 0) userData = userData.setStakeStart(block.timestamp); uint256 tokenId; for (uint256 i; i < quantity; ++i) { tokenId = startTokenId + i; (userData, tokenData) = _beforeStakeDataTransform(tokenId, userData, tokenData); emit Transfer(address(0), to, tokenId); emit Transfer(to, address(this), tokenId); } } else { userData = userData.increaseBalance(quantity); for (uint256 i; i < quantity; ++i) emit Transfer(address(0), to, startTokenId + i); } _userData[to] = userData; _tokenData[startTokenId] = tokenData; totalSupply += quantity; } } function _claimReward() internal returns (uint256) { uint256 userData = _userData[msg.sender]; return claimReward(userData); } function claimReward(uint256 userData) private returns (uint256) { uint256 reward = _pendingReward(msg.sender, userData); userData = userData.setLastClaimed(block.timestamp); _payoutReward(msg.sender, reward); return userData; } function _tokenDataOf(uint256 tokenId) public view returns (uint256) { if (!_exists(tokenId)) revert NonexistentToken(); for (uint256 curr = tokenId; ; curr--) { uint256 tokenData = _tokenData[curr]; if (tokenData != 0) return (curr == tokenId) ? tokenData : tokenData.copy(); } // unreachable return 0; } function _exists(uint256 tokenId) internal view returns (bool) { return startingIndex <= tokenId && tokenId < startingIndex + totalSupply; } function transferFrom( address from, address to, uint256 tokenId ) public { // make sure no one is misled by token transfer events if (to == address(this)) { uint256 userData = _claimReward(); _userData[msg.sender] = _stake(msg.sender, tokenId, userData); } else { uint256 tokenData = _tokenDataOf(tokenId); address owner = tokenData.owner(); bool isApprovedOrOwner = (msg.sender == owner || isApprovedForAll[owner][msg.sender] || getApproved[tokenId] == msg.sender); if (!isApprovedOrOwner) revert CallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); if (owner != from) revert TransferFromIncorrectOwner(); delete getApproved[tokenId]; unchecked { _tokenData[tokenId] = _ensureTokenDataSet(tokenId + 1, tokenData) .setOwner(to) .setLastTransfer(block.timestamp) .incrementOwnerCount(); } _userData[from] = _userData[from].decreaseBalance(1); _userData[to] = _userData[to].increaseBalance(1); emit Transfer(from, to, tokenId); } } function _ensureTokenDataSet(uint256 tokenId, uint256 tokenData) private returns (uint256) { if (!tokenData.nextTokenDataSet() && _tokenData[tokenId] == 0 && _exists(tokenId)) _tokenData[tokenId] = tokenData.copy(); // make sure to not pass any token specific data in return tokenData.flagNextTokenDataSet(); } /* ------------- Virtual (hooks) ------------- */ function _beforeStakeDataTransform( uint256, // tokenId uint256 userData, uint256 tokenData ) internal view virtual returns (uint256, uint256) { return (userData, tokenData); } function _beforeUnstakeDataTransform( uint256, // tokenId uint256 userData, uint256 tokenData ) internal view virtual returns (uint256, uint256) { return (userData, tokenData); } function _pendingReward(address, uint256 userData) internal view virtual returns (uint256); function _payoutReward(address user, uint256 reward) internal virtual; /* ------------- View ------------- */ function ownerOf(uint256 tokenId) external view returns (address) { return _tokenDataOf(tokenId).owner(); } function trueOwnerOf(uint256 tokenId) external view returns (address) { return _tokenDataOf(tokenId).trueOwner(); } function balanceOf(address owner) external view returns (uint256) { if (owner == address(0)) revert QueryForZeroAddress(); return _userData[owner].balance(); } function numStaked(address user) external view returns (uint256) { return _userData[user].numStaked(); } function numOwned(address user) external view returns (uint256) { uint256 userData = _userData[user]; return userData.balance() + userData.numStaked(); } function numMinted(address user) external view returns (uint256) { return _userData[user].numMinted(); } function pendingReward(address user) external view returns (uint256) { return _pendingReward(user, _userData[user]); } // O(N) read-only functions function tokenIdsOf(address user, uint256 type_) external view returns (uint256[] memory) { unchecked { uint256 numTotal = type_ == 0 ? this.balanceOf(user) : type_ == 1 ? this.numStaked(user) : this.numOwned(user); uint256[] memory ids = new uint256[](numTotal); if (numTotal == 0) return ids; uint256 count; for (uint256 i = startingIndex; i < totalSupply + startingIndex; ++i) { uint256 tokenData = _tokenDataOf(i); if (user == tokenData.trueOwner()) { bool staked = tokenData.staked(); if ((type_ == 0 && !staked) || (type_ == 1 && staked) || type_ == 2) { ids[count++] = i; if (numTotal == count) return ids; } } } return ids; } } function totalNumStaked() external view returns (uint256) { unchecked { uint256 count; for (uint256 i = startingIndex; i < startingIndex + totalSupply; ++i) { if (_tokenDataOf(i).staked()) ++count; } return count; } } /* ------------- ERC721 ------------- */ function tokenURI(uint256 id) public view virtual returns (string memory); function supportsInterface(bytes4 interfaceId) external view 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 } function approve(address spender, uint256 tokenId) external { address owner = _tokenDataOf(tokenId).owner(); if (msg.sender != owner && !isApprovedForAll[owner][msg.sender]) revert CallerNotOwnerNorApproved(); getApproved[tokenId] = spender; emit Approval(owner, spender, tokenId); } function setApprovalForAll(address operator, bool approved) external { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function safeTransferFrom( address from, address to, uint256 tokenId ) external { safeTransferFrom(from, to, tokenId, ''); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public { transferFrom(from, to, tokenId); if ( to.code.length != 0 && IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) != IERC721Receiver(to).onERC721Received.selector ) revert TransferToNonERC721ReceiverImplementer(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // # ERC721M.sol // // _tokenData layout: // 0x________/cccccbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa // a [ 0] (uint160): address #owner (owner of token id) // b [160] (uint40): timestamp #lastTransfer (timestamp since the last transfer) // c [200] (uint20): #ownerCount (number of total owners of token) // f [220] (uint1): #staked flag (flag whether id has been staked) Note: this carries over when calling 'ownerOf' // f [221] (uint1): #mintAndStake flag (flag whether to carry over stake flag when calling tokenDataOf; used for mintAndStake and boost) // e [222] (uint1): #nextTokenDataSet flag (flag whether the data of next token id has already been set) // _ [224] (uint32): arbitrary data uint256 constant RESTRICTED_TOKEN_DATA = 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // # MadMouse.sol // // _tokenData (metadata) layout: // 0xefg00000________________________________________________________ // e [252] (uint4): #level (mouse level) [0...2] (must be 0-based) // f [248] (uint4): #role (mouse role) [1...5] (must start at 1) // g [244] (uint4): #rarity (mouse rarity) [0...3] struct TokenData { address owner; uint256 lastTransfer; uint256 ownerCount; bool staked; bool mintAndStake; bool nextTokenDataSet; uint256 level; uint256 role; uint256 rarity; } // # ERC721M.sol // // _userData layout: // 0x________________________________ddccccccccccbbbbbbbbbbaaaaaaaaaa // a [ 0] (uint32): #balance (owner ERC721 balance) // b [ 40] (uint40): timestamp #stakeStart (timestamp when stake started) // c [ 80] (uint40): timestamp #lastClaimed (timestamp when user last claimed rewards) // d [120] (uint8): #numStaked (balance count of all staked tokens) // _ [128] (uint128): arbitrary data uint256 constant RESTRICTED_USER_DATA = 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // # MadMouseStaking.sol // // _userData (boost) layout: // 0xttttttttt/o/rriiffgghhaabbccddee________________________________ // a-e [128] (5x uint8): #roleBalances (balance of all staked roles) // f-h [168] (3x uint8): #levelBalances (balance of all staked levels) // i [192] (uint8): #specialGuestIndex (signals whether the user claims to hold a token of a certain collection) // r [200] (uint10): #rarityPoints (counter of rare traits; 1 is rare, 2 is super-rare, 3 is ultra-rare) // o [210] (uint8): #OGCount (counter of rare traits; 1 is rare, 2 is super-rare, 3 is ultra-rare) // t [218] (uint38): timestamp #boostStart (timestamp of when the boost by burning tokens of affiliate collections started) struct UserData { uint256 balance; uint256 stakeStart; uint256 lastClaimed; uint256 numStaked; uint256[5] roleBalances; uint256 uniqueRoleCount; // inferred uint256[3] levelBalances; uint256 specialGuestIndex; uint256 rarityPoints; uint256 OGCount; uint256 boostStart; } function applySafeDataTransform( uint256 userData, uint256 tokenData, uint256 userDataTransformed, uint256 tokenDataTransformed ) pure returns (uint256, uint256) { // mask transformed data in order to leave base data untouched in any case userData = (userData & RESTRICTED_USER_DATA) | (userDataTransformed & ~RESTRICTED_USER_DATA); tokenData = (tokenData & RESTRICTED_TOKEN_DATA) | (tokenDataTransformed & ~RESTRICTED_TOKEN_DATA); return (userData, tokenData); } // @note: many of these are unchecked, because safemath wouldn't be able to guard // overflows while updating bitmaps unless custom checks were to be implemented library UserDataOps { function getUserData(uint256 userData) internal pure returns (UserData memory) { return UserData({ balance: UserDataOps.balance(userData), stakeStart: UserDataOps.stakeStart(userData), lastClaimed: UserDataOps.lastClaimed(userData), numStaked: UserDataOps.numStaked(userData), roleBalances: UserDataOps.roleBalances(userData), uniqueRoleCount: UserDataOps.uniqueRoleCount(userData), levelBalances: UserDataOps.levelBalances(userData), specialGuestIndex: UserDataOps.specialGuestIndex(userData), rarityPoints: UserDataOps.rarityPoints(userData), OGCount: UserDataOps.OGCount(userData), boostStart: UserDataOps.boostStart(userData) }); } function balance(uint256 userData) internal pure returns (uint256) { return userData & 0xFFFFF; } function increaseBalance(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData + amount; } } function decreaseBalance(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData - amount; } } function numMinted(uint256 userData) internal pure returns (uint256) { return (userData >> 20) & 0xFFFFF; } function increaseNumMinted(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData + (amount << 20); } } function stakeStart(uint256 userData) internal pure returns (uint256) { return (userData >> 40) & 0xFFFFFFFFFF; } function setStakeStart(uint256 userData, uint256 timestamp) internal pure returns (uint256) { return (userData & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000FFFFFFFFFF) | (timestamp << 40); } function lastClaimed(uint256 userData) internal pure returns (uint256) { return (userData >> 80) & 0xFFFFFFFFFF; } function setLastClaimed(uint256 userData, uint256 timestamp) internal pure returns (uint256) { return (userData & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000FFFFFFFFFFFFFFFFFFFF) | (timestamp << 80); } function numStaked(uint256 userData) internal pure returns (uint256) { return (userData >> 120) & 0xFF; } function increaseNumStaked(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData + (amount << 120); } } function decreaseNumStaked(uint256 userData, uint256 amount) internal pure returns (uint256) { unchecked { return userData - (amount << 120); } } function roleBalances(uint256 userData) internal pure returns (uint256[5] memory balances) { balances = [ (userData >> (128 + 0)) & 0xFF, (userData >> (128 + 8)) & 0xFF, (userData >> (128 + 16)) & 0xFF, (userData >> (128 + 24)) & 0xFF, (userData >> (128 + 32)) & 0xFF ]; } // trait counts are set through hook in madmouse contract (MadMouse::_beforeStakeDataTransform) function uniqueRoleCount(uint256 userData) internal pure returns (uint256) { unchecked { return (toUInt256((userData >> (128)) & 0xFF > 0) + toUInt256((userData >> (128 + 8)) & 0xFF > 0) + toUInt256((userData >> (128 + 16)) & 0xFF > 0) + toUInt256((userData >> (128 + 24)) & 0xFF > 0) + toUInt256((userData >> (128 + 32)) & 0xFF > 0)); } } function levelBalances(uint256 userData) internal pure returns (uint256[3] memory balances) { unchecked { balances = [ (userData >> (168 + 0)) & 0xFF, (userData >> (168 + 8)) & 0xFF, (userData >> (168 + 16)) & 0xFF ]; } } // depends on the levels of the staked tokens (also set in hook MadMouse::_beforeStakeDataTransform) // counts the base reward, depending on the levels of staked ids function baseReward(uint256 userData) internal pure returns (uint256) { unchecked { return (((userData >> (168)) & 0xFF) + (((userData >> (168 + 8)) & 0xFF) << 1) + (((userData >> (168 + 16)) & 0xFF) << 2)); } } function rarityPoints(uint256 userData) internal pure returns (uint256) { return (userData >> 200) & 0x3FF; } function specialGuestIndex(uint256 userData) internal pure returns (uint256) { return (userData >> 192) & 0xFF; } function setSpecialGuestIndex(uint256 userData, uint256 index) internal pure returns (uint256) { return (userData & ~uint256(0xFF << 192)) | (index << 192); } function boostStart(uint256 userData) internal pure returns (uint256) { return (userData >> 218) & 0xFFFFFFFFFF; } function setBoostStart(uint256 userData, uint256 timestamp) internal pure returns (uint256) { return (userData & ~(uint256(0xFFFFFFFFFF) << 218)) | (timestamp << 218); } function OGCount(uint256 userData) internal pure returns (uint256) { return (userData >> 210) & 0xFF; } // (should start at 128, 168; but role/level start at 1...) function updateUserDataStake(uint256 userData, uint256 tokenData) internal pure returns (uint256) { unchecked { uint256 role = TokenDataOps.role(tokenData); if (role > 0) { userData += uint256(1) << (120 + (role << 3)); // roleBalances userData += TokenDataOps.rarity(tokenData) << 200; // rarityPoints } if (TokenDataOps.mintAndStake(tokenData)) userData += uint256(1) << 210; // OGCount userData += uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)); // levelBalances return userData; } } function updateUserDataUnstake(uint256 userData, uint256 tokenData) internal pure returns (uint256) { unchecked { uint256 role = TokenDataOps.role(tokenData); if (role > 0) { userData -= uint256(1) << (120 + (role << 3)); // roleBalances userData -= TokenDataOps.rarity(tokenData) << 200; // rarityPoints } if (TokenDataOps.mintAndStake(tokenData)) userData -= uint256(1) << 210; // OG-count userData -= uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)); // levelBalances return userData; } } function increaseLevelBalances(uint256 userData, uint256 tokenData) internal pure returns (uint256) { unchecked { return userData + (uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3))); } } function decreaseLevelBalances(uint256 userData, uint256 tokenData) internal pure returns (uint256) { unchecked { return userData - (uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3))); } } } library TokenDataOps { function getTokenData(uint256 tokenData) internal view returns (TokenData memory) { return TokenData({ owner: TokenDataOps.owner(tokenData), lastTransfer: TokenDataOps.lastTransfer(tokenData), ownerCount: TokenDataOps.ownerCount(tokenData), staked: TokenDataOps.staked(tokenData), mintAndStake: TokenDataOps.mintAndStake(tokenData), nextTokenDataSet: TokenDataOps.nextTokenDataSet(tokenData), level: TokenDataOps.level(tokenData), role: TokenDataOps.role(tokenData), rarity: TokenDataOps.rarity(tokenData) }); } function newTokenData( address owner_, uint256 lastTransfer_, bool stake_ ) internal pure returns (uint256) { uint256 tokenData = (uint256(uint160(owner_)) | (lastTransfer_ << 160) | (uint256(1) << 200)); return stake_ ? setstaked(setMintAndStake(tokenData)) : tokenData; } function copy(uint256 tokenData) internal pure returns (uint256) { // tokenData minus the token specific flags (4/2bits), i.e. only owner, lastTransfer, ownerCount // stake flag (& mintAndStake flag) carries over if mintAndStake was called return tokenData & (RESTRICTED_TOKEN_DATA >> (mintAndStake(tokenData) ? 2 : 4)); } function owner(uint256 tokenData) internal view returns (address) { if (staked(tokenData)) return address(this); return trueOwner(tokenData); } function setOwner(uint256 tokenData, address owner_) internal pure returns (uint256) { return (tokenData & 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) | uint160(owner_); } function staked(uint256 tokenData) internal pure returns (bool) { return ((tokenData >> 220) & uint256(1)) > 0; // Note: this can carry over when calling 'ownerOf' } function setstaked(uint256 tokenData) internal pure returns (uint256) { return tokenData | (uint256(1) << 220); } function unsetstaked(uint256 tokenData) internal pure returns (uint256) { return tokenData & ~(uint256(1) << 220); } function mintAndStake(uint256 tokenData) internal pure returns (bool) { return ((tokenData >> 221) & uint256(1)) > 0; } function setMintAndStake(uint256 tokenData) internal pure returns (uint256) { return tokenData | (uint256(1) << 221); } function unsetMintAndStake(uint256 tokenData) internal pure returns (uint256) { return tokenData & ~(uint256(1) << 221); } function nextTokenDataSet(uint256 tokenData) internal pure returns (bool) { return ((tokenData >> 222) & uint256(1)) > 0; } function flagNextTokenDataSet(uint256 tokenData) internal pure returns (uint256) { return tokenData | (uint256(1) << 222); // nextTokenDatatSet flag (don't repeat the read/write) } function trueOwner(uint256 tokenData) internal pure returns (address) { return address(uint160(tokenData)); } function ownerCount(uint256 tokenData) internal pure returns (uint256) { return (tokenData >> 200) & 0xFFFFF; } function incrementOwnerCount(uint256 tokenData) internal pure returns (uint256) { uint256 newOwnerCount = min(ownerCount(tokenData) + 1, 0xFFFFF); return (tokenData & ~(uint256(0xFFFFF) << 200)) | (newOwnerCount << 200); } function resetOwnerCount(uint256 tokenData) internal pure returns (uint256) { uint256 count = min(ownerCount(tokenData), 2); // keep minter status return (tokenData & ~(uint256(0xFFFFF) << 200)) | (count << 200); } function lastTransfer(uint256 tokenData) internal pure returns (uint256) { return (tokenData >> 160) & 0xFFFFFFFFFF; } function setLastTransfer(uint256 tokenData, uint256 timestamp) internal pure returns (uint256) { return (tokenData & 0xFFFFFFFFFFFFFF0000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | (timestamp << 160); } // MadMouse function level(uint256 tokenData) internal pure returns (uint256) { unchecked { return 1 + (tokenData >> 252); } } function increaseLevel(uint256 tokenData) internal pure returns (uint256) { unchecked { return tokenData + (uint256(1) << 252); } } function role(uint256 tokenData) internal pure returns (uint256) { return (tokenData >> 248) & 0xF; } function rarity(uint256 tokenData) internal pure returns (uint256) { return (tokenData >> 244) & 0xF; } // these slots should be are already 0 function setRoleAndRarity(uint256 tokenData, uint256 dna) internal pure returns (uint256) { return ((tokenData & ~(uint256(0xFF) << 244)) | (DNAOps.toRole(dna) << 248) | (DNAOps.toRarity(dna) << 244)); } } library DNAOps { function toRole(uint256 dna) internal pure returns (uint256) { unchecked { return 1 + ((dna & 0xFF) % 5); } } function toRarity(uint256 dna) internal pure returns (uint256) { uint256 dnaFur = (dna >> 8) & 0xFF; if (dnaFur > 108) return 0; if (dnaFur > 73) return 1; if (dnaFur > 17) return 2; return 3; } } /* ------------- Helpers ------------- */ // more efficient https://github.com/ethereum/solidity/issues/659 function toUInt256(bool x) pure returns (uint256 r) { assembly { r := x } } function min(uint256 a, uint256 b) pure returns (uint256) { return a < b ? a : b; } function isValidString(string calldata str, uint256 maxLen) pure returns (bool) { unchecked { bytes memory b = bytes(str); if (b.length < 1 || b.length > maxLen || b[0] == 0x20 || b[b.length - 1] == 0x20) return false; bytes1 lastChar = b[0]; bytes1 char; for (uint256 i; i < b.length; ++i) { char = b[i]; if ( (char > 0x60 && char < 0x7B) || //a-z (char > 0x40 && char < 0x5B) || //A-Z (char == 0x20) || //space (char > 0x2F && char < 0x3A) //9-0 ) { lastChar = char; } else { return false; } } return true; } }
hook, used for reading DNA, updating role balances,
function _stake( address from, uint256 tokenId, uint256 userData ) private returns (uint256) { uint256 _numStaked = userData.numStaked(); uint256 tokenData = _tokenDataOf(tokenId); address owner = tokenData.owner(); if (_numStaked >= stakingLimit) revert ExceedsStakingLimit(); if (owner != from) revert IncorrectOwner(); delete getApproved[tokenId]; (uint256 userDataX, uint256 tokenDataX) = _beforeStakeDataTransform(tokenId, userData, tokenData); (userData, tokenData) = applySafeDataTransform(userData, tokenData, userDataX, tokenDataX); tokenData = tokenData.setstaked(); userData = userData.decreaseBalance(1).increaseNumStaked(1); if (_numStaked == 0) userData = userData.setStakeStart(block.timestamp); _tokenData[tokenId] = tokenData; emit Transfer(from, address(this), tokenId); return userData; }
393,191
pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) { require(_totalSupply.add(_amount) <= minting_capped_amount); _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { 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, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 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); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // 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) function increaseApproval(address spender, uint256 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; } // 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) function decreaseApproval(address spender, uint256 subtractedValue ) public returns (bool){ uint256 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; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) { require(_totalSupply.add(_amount) <= minting_capped_amount); _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { 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, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 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); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // 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) function increaseApproval(address spender, uint256 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; } // 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) function decreaseApproval(address spender, uint256 subtractedValue ) public returns (bool){ uint256 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; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getBountyAmount() public view returns(uint256); } contract EmalBounty is Ownable { using SafeMath for uint256; // The token being sold EmalToken public token; // Bounty contract state Data structures enum State { Active, Closed } // contains current state of bounty contract State public state; // Bounty limit in EMAL tokens uint256 public bountyLimit; // Count of total number of EML tokens that have been currently allocated to bounty users uint256 public totalTokensAllocated = 0; // Count of allocated tokens (not issued only allocated) for each bounty user mapping(address => uint256) public allocatedTokens; // Count of allocated tokens issued to each bounty user. mapping(address => uint256) public amountOfAllocatedTokensGivenOut; /** @dev Event fired when tokens are allocated to a bounty user account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** * @dev Event fired when EML tokens are sent to a bounty user * @param beneficiary Address where the allocated tokens were sent * @param tokenCount The amount of tokens that were sent */ event IssuedAllocatedTokens(address indexed beneficiary, uint256 tokenCount); /** @param _token Address of the token that will be rewarded for the investors */ constructor(address _token) public { require(_token != address(0)); owner = msg.sender; token = EmalToken(_token); state = State.Active; bountyLimit = token.getBountyAmount(); } /* Do not accept ETH */ function() external payable { revert(); } function closeBounty() public onlyOwner returns(bool){ require( state!=State.Closed ); state = State.Closed; return true; } /** @dev Public function to check if bounty isActive or not * @return True if Bounty event has ended */ function isBountyActive() public view returns(bool) { if (state==State.Active && totalTokensAllocated<bountyLimit){ return true; } else { return false; } } /** @dev Allocates tokens to a bounty user * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensAllocated.add(tokens) > bountyLimit) { tokens = bountyLimit.sub(totalTokensAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool isActive = state==State.Active; bool positiveAllocation = tokenCount>0; bool bountyLimitNotReached = totalTokensAllocated<bountyLimit; return isActive && positiveAllocation && bountyLimitNotReached; } /** @dev Remove tokens from a bounty user's allocation. * @dev Used in game based bounty allocation, automatically called from the Sails app * @param beneficiary The address of the bounty user * @param tokenCount The number of tokens to be deallocated to this address */ function deductAllocatedTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(tokenCount>0 && tokenCount<=allocatedTokens[beneficiary]); allocatedTokens[beneficiary] = allocatedTokens[beneficiary].sub(tokenCount); totalTokensAllocated = totalTokensAllocated.sub(tokenCount); emit TokensDeallocated(beneficiary, tokenCount); return true; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor or the bounty user */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } /** @dev Bounty users will be issued EML Tokens by the sails api, * @dev after the Bounty has ended to their address * @param beneficiary address of the bounty user */ function issueTokensToAllocatedUsers(address beneficiary) public onlyOwner returns(bool success) { require(beneficiary!=address(0)); require(allocatedTokens[beneficiary]>0); uint256 tokensToSend = allocatedTokens[beneficiary]; allocatedTokens[beneficiary] = 0; amountOfAllocatedTokensGivenOut[beneficiary] = amountOfAllocatedTokensGivenOut[beneficiary].add(tokensToSend); assert(token.transferFrom(owner, beneficiary, tokensToSend)); emit IssuedAllocatedTokens(beneficiary, tokensToSend); return true; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getCrowdsaleAmount() public view returns(uint256); function setStartTimeForTokenTransfers(uint256 _startTime) external; } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalCrowdsale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Switched to true once token contract is notified of when to enable token transfers bool private isStartTimeSetForTokenTransfers = false; // Hard cap in EMAL tokens uint256 public hardCap; // Soft cap in EMAL tokens uint256 constant public soft_cap = 50000000 * (10 ** 18); // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Crowdsale uint256 public totalEtherRaisedByCrowdsale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Crowdsale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** * @dev Event for refund logging * @param receiver The address that received the refund * @param amount The amount that is being refunded (in wei) */ event Refund(address indexed receiver, uint256 amount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 25; uint256 bonusPercent2 = 15; uint256 bonusPercent3 = 0; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** * @dev public function that is used to determine the current rate for token / ETH conversion * @dev there exists a case where rate cant be set to 0, which is fine. * @return The current token rate */ function getRate() public view returns(uint256) { require( priceOfEMLTokenInUSDPenny !=0 ); require( priceOfEthInUSD !=0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { if (now <= (startTime + 1 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } if (now > (startTime + 1 days) && now <= (startTime + 2 days)) { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent2.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent3.add(100)).div(100); } } return rate; } /** @dev Initialise the Crowdsale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getCrowdsaleAmount(); } /** @dev Fallback function that can be used to buy EML tokens. Or in * case of the owner, return ether to allow refunds in case crowdsale * ended or paused and didnt reach soft_cap. */ function() external payable { if (msg.sender == multisigWallet) { require( (!isCrowdsaleActive()) && totalTokensSoldandAllocated<soft_cap); } else { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { revert(); } } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByCrowdsale = totalEtherRaisedByCrowdsale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Update token contract. _postValidationUpdateTokenContract(); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } function _postValidationUpdateTokenContract() internal { /** @dev If hard cap is reachde allow token transfers after two weeks * @dev Allow users to transfer tokens only after hardCap is reached * @dev Notiy token contract about startTime to start transfers */ if (totalTokensSoldandAllocated == hardCap) { token.setStartTimeForTokenTransfers(now + 2 weeks); } /** @dev If its the first token sold or allocated then set s, allow after 2 weeks * @dev Allow users to transfer tokens only after ICO crowdsale ends. * @dev Notify token contract about sale end time */ if (!isStartTimeSetForTokenTransfers) { isStartTimeSetForTokenTransfers = true; token.setStartTimeForTokenTransfers(endTime + 2 weeks); } } /** @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Crowdsale isActive or not * @return True if Crowdsale event has ended */ function isCrowdsaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev Returns ether to token holders in case soft cap is not reached. */ function claimRefund() public whenNotPaused onlyOwner { require(now>endTime); require(totalTokensSoldandAllocated<soft_cap); uint256 amount = etherInvestments[msg.sender]; if (address(this).balance >= amount) { etherInvestments[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); emit Refund(msg.sender, amount); } } } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); /* Update token contract. */ _postValidationUpdateTokenContract(); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract EmalToken { // add function prototypes of only those used here function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function getPresaleAmount() public view returns(uint256); } contract EmalWhitelist { // add function prototypes of only those used here function isWhitelisted(address investorAddr) public view returns(bool whitelisted); } contract EmalPresale is Ownable, Pausable { using SafeMath for uint256; // Start and end timestamps uint256 public startTime; uint256 public endTime; // The token being sold EmalToken public token; // Whitelist contract used to store whitelisted addresses EmalWhitelist public list; // Address where funds are collected address public multisigWallet; // Hard cap in EMAL tokens uint256 public hardCap; // Amount of tokens that were sold to ether investors plus tokens allocated to investors for fiat and btc investments. uint256 public totalTokensSoldandAllocated = 0; // Investor contributions made in ether mapping(address => uint256) public etherInvestments; // Tokens given to investors who sent ether investments mapping(address => uint256) public tokensSoldForEther; // Total ether raised by the Presale uint256 public totalEtherRaisedByPresale = 0; // Total number of tokens sold to investors who made payments in ether uint256 public totalTokensSoldByEtherInvestments = 0; // Count of allocated tokens for each investor or bounty user mapping(address => uint256) public allocatedTokens; // Count of total number of EML tokens that have been currently allocated to Presale investors uint256 public totalTokensAllocated = 0; /** @dev Event for EML token purchase using ether * @param investorAddr Address that paid and got the tokens * @param paidAmount The amount that was paid (in wei) * @param tokenCount The amount of tokens that were bought */ event TokenPurchasedUsingEther(address indexed investorAddr, uint256 paidAmount, uint256 tokenCount); /** @dev Event fired when EML tokens are allocated to an investor account * @param beneficiary Address that is allocated tokens * @param tokenCount The amount of tokens that were allocated */ event TokensAllocated(address indexed beneficiary, uint256 tokenCount); event TokensDeallocated(address indexed beneficiary, uint256 tokenCount); /** @dev variables and functions which determine conversion rate from ETH to EML * based on bonuses and current timestamp. */ uint256 priceOfEthInUSD = 450; uint256 bonusPercent1 = 35; uint256 priceOfEMLTokenInUSDPenny = 60; uint256 overridenBonusValue = 0; function setExchangeRate(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != priceOfEthInUSD); priceOfEthInUSD = overridenValue; return true; } function getExchangeRate() public view returns(uint256){ return priceOfEthInUSD; } function setOverrideBonus(uint256 overridenValue) public onlyOwner returns(bool) { require( overridenValue > 0 ); require( overridenValue != overridenBonusValue); overridenBonusValue = overridenValue; return true; } /** @dev public function that is used to determine the current rate for ETH to EML conversion * @return The current token rate */ function getRate() public view returns(uint256) { require(priceOfEMLTokenInUSDPenny > 0 ); require(priceOfEthInUSD > 0 ); uint256 rate; if(overridenBonusValue > 0){ rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(overridenBonusValue.add(100)).div(100); } else { rate = priceOfEthInUSD.mul(100).div(priceOfEMLTokenInUSDPenny).mul(bonusPercent1.add(100)).div(100); } return rate; } /** @dev Initialise the Presale contract. * (can be removed for testing) _startTime Unix timestamp for the start of the token sale * (can be removed for testing) _endTime Unix timestamp for the end of the token sale * @param _multisigWallet Ethereum address to which the invested funds are forwarded * @param _token Address of the token that will be rewarded for the investors * @param _list contains a list of investors who completed KYC procedures. */ constructor(uint256 _startTime, uint256 _endTime, address _multisigWallet, address _token, address _list) public { require(_startTime >= now); require(_endTime >= _startTime); require(_multisigWallet != address(0)); require(_token != address(0)); require(_list != address(0)); startTime = _startTime; endTime = _endTime; multisigWallet = _multisigWallet; owner = msg.sender; token = EmalToken(_token); list = EmalWhitelist(_list); hardCap = token.getPresaleAmount(); } /** @dev Fallback function that can be used to buy tokens. */ function() external payable { if (list.isWhitelisted(msg.sender)) { buyTokensUsingEther(msg.sender); } else { /* Do not accept ETH */ revert(); } } /** @dev Function for buying EML tokens using ether * @param _investorAddr The address that should receive bought tokens */ function buyTokensUsingEther(address _investorAddr) internal whenNotPaused { require(_investorAddr != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnToSender = 0; // final rate after including rate value and bonus amount. uint256 finalConversionRate = getRate(); // Calculate EML token amount to be transferred uint256 tokens = weiAmount.mul(finalConversionRate); // Distribute only the remaining tokens if final contribution exceeds hard cap if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); weiAmount = tokens.div(finalConversionRate); returnToSender = msg.value.sub(weiAmount); } // update state and balances etherInvestments[_investorAddr] = etherInvestments[_investorAddr].add(weiAmount); tokensSoldForEther[_investorAddr] = tokensSoldForEther[_investorAddr].add(tokens); totalTokensSoldByEtherInvestments = totalTokensSoldByEtherInvestments.add(tokens); totalEtherRaisedByPresale = totalEtherRaisedByPresale.add(weiAmount); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, _investorAddr, tokens)); emit TokenPurchasedUsingEther(_investorAddr, weiAmount, tokens); // Forward funds multisigWallet.transfer(weiAmount); // Return funds that are over hard cap if (returnToSender > 0) { msg.sender.transfer(returnToSender); } } /** * @dev Internal function that is used to check if the incoming purchase should be accepted. * @return True if the transaction can buy tokens */ function validPurchase() internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool minimumPurchase = msg.value >= 1*(10**18); bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && hardCapNotReached && minimumPurchase; } /** @dev Public function to check if Presale isActive or not * @return True if Presale event has ended */ function isPresaleActive() public view returns(bool) { if (!paused && now>startTime && now<endTime && totalTokensSoldandAllocated<=hardCap){ return true; } else { return false; } } /** @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOfEtherInvestor(address _owner) external view returns(uint256 balance) { require(_owner != address(0)); return etherInvestments[_owner]; } function getTokensSoldToEtherInvestor(address _owner) public view returns(uint256 balance) { require(_owner != address(0)); return tokensSoldForEther[_owner]; } /** @dev BELOW ARE FUNCTIONS THAT HANDLE INVESTMENTS IN FIAT AND BTC. * functions are automatically called by ICO Sails.js app. */ /** @dev Allocates EML tokens to an investor address called automatically * after receiving fiat or btc investments from KYC whitelisted investors. * @param beneficiary The address of the investor * @param tokenCount The number of tokens to be allocated to this address */ function allocateTokens(address beneficiary, uint256 tokenCount) public onlyOwner returns(bool success) { require(beneficiary != address(0)); require(validAllocation(tokenCount)); uint256 tokens = tokenCount; /* Allocate only the remaining tokens if final contribution exceeds hard cap */ if (totalTokensSoldandAllocated.add(tokens) > hardCap) { tokens = hardCap.sub(totalTokensSoldandAllocated); } /* Update state and balances */ allocatedTokens[beneficiary] = allocatedTokens[beneficiary].add(tokens); totalTokensSoldandAllocated = totalTokensSoldandAllocated.add(tokens); totalTokensAllocated = totalTokensAllocated.add(tokens); // assert implies it should never fail assert(token.transferFrom(owner, beneficiary, tokens)); emit TokensAllocated(beneficiary, tokens); return true; } function validAllocation( uint256 tokenCount ) internal view returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool positiveAllocation = tokenCount > 0; bool hardCapNotReached = totalTokensSoldandAllocated < hardCap; return withinPeriod && positiveAllocation && hardCapNotReached; } /** @dev Getter function to check the amount of allocated tokens * @param beneficiary address of the investor */ function getAllocatedTokens(address beneficiary) public view returns(uint256 tokenCount) { require(beneficiary != address(0)); return allocatedTokens[beneficiary]; } function getSoldandAllocatedTokens(address _addr) public view returns (uint256) { require(_addr != address(0)); uint256 totalTokenCount = getAllocatedTokens(_addr).add(getTokensSoldToEtherInvestor(_addr)); return totalTokenCount; } } pragma solidity 0.4.24; import "./SafeMath.sol"; import './StandardToken.sol'; import './Ownable.sol'; contract EmalToken is StandardToken, Ownable { using SafeMath for uint256; string public constant symbol = "EML"; string public constant name = "e-Mal Token"; uint8 public constant decimals = 18; // Total Number of tokens ever goint to be minted. 1 BILLION EML tokens. uint256 private constant minting_capped_amount = 1000000000 * 10 ** uint256(decimals); // 24% of initial supply uint256 constant presale_amount = 120000000 * 10 ** uint256(decimals); // 60% of inital supply uint256 constant crowdsale_amount = 300000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant vesting_amount = 40000000 * 10 ** uint256(decimals); // 8% of inital supply. uint256 constant bounty_amount = 40000000 * 10 ** uint256(decimals); uint256 private initialSupply = minting_capped_amount; address public presaleAddress; address public crowdsaleAddress; address public vestingAddress; address public bountyAddress; /** @dev Defines the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ uint256 public startTimeForTransfers; /** @dev to cap the total number of tokens that will ever be newly minted * owner has to stop the minting by setting this variable to true. */ bool public mintingFinished = false; /** @dev Miniting Essentials functions as per OpenZeppelin standards */ modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** @dev to prevent malicious use of EML tokens and to comply with Anti * Money laundering regulations EML tokens can be frozen. */ mapping (address => bool) public frozenAccount; /** @dev This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); event Mint(address indexed to, uint256 amount); event MintFinished(); event Burn(address indexed burner, uint256 value); constructor() public { startTimeForTransfers = now - 210 days; _totalSupply = initialSupply; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, balances[owner]); } /* Do not accept ETH */ function() public payable { revert(); } /** @dev Basic setters and getters to allocate tokens for vesting factory, presale * crowdsale and bounty this is done so that no need of actually transferring EML * tokens to sale contracts and hence preventing EML tokens from the risk of being * locked out in future inside the subcontracts. */ function setPresaleAddress(address _presaleAddress) external onlyOwner { presaleAddress = _presaleAddress; assert(approve(presaleAddress, presale_amount)); } function setCrowdsaleAddress(address _crowdsaleAddress) external onlyOwner { crowdsaleAddress = _crowdsaleAddress; assert(approve(crowdsaleAddress, crowdsale_amount)); } function setVestingAddress(address _vestingAddress) external onlyOwner { vestingAddress = _vestingAddress; assert(approve(vestingAddress, vesting_amount)); } function setBountyAddress(address _bountyAddress) external onlyOwner { bountyAddress = _bountyAddress; assert(approve(bountyAddress, bounty_amount)); } function getPresaleAmount() internal pure returns(uint256) { return presale_amount; } function getCrowdsaleAmount() internal pure returns(uint256) { return crowdsale_amount; } function getVestingAmount() internal pure returns(uint256) { return vesting_amount; } function getBountyAmount() internal pure returns(uint256) { return bounty_amount; } /** @dev Sets the start time after which transferring of EML tokens * will be allowed done so as to prevent early buyers from clearing out * of their EML balance during the presale and publicsale. */ function setStartTimeForTokenTransfers(uint256 _startTimeForTransfers) external { require(msg.sender == crowdsaleAddress); if (_startTimeForTransfers < startTimeForTransfers) { startTimeForTransfers = _startTimeForTransfers; } } /** @dev Transfer possible only after ICO ends and Frozen accounts * wont be able to transfer funds to other any other account and viz. * @notice added safeTransfer functionality */ function transfer(address _to, uint256 _value) public returns(bool) { require(now >= startTimeForTransfers); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(super.transfer(_to, _value)); return true; } /** @dev Only owner's tokens can be transferred before Crowdsale ends. * beacuse the inital supply of EML is allocated to owners acc and later * distributed to various subcontracts. * @notice added safeTransferFrom functionality */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!frozenAccount[msg.sender]); if (now < startTimeForTransfers) { require(_from == owner); } require(super.transferFrom(_from, _to, _value)); return true; } /** @notice added safeApprove functionality */ function approve(address spender, uint256 tokens) public returns (bool){ require(super.approve(spender, tokens)); return true; } /** @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyOwner { require(frozenAccount[target] != freeze); frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) { require(_totalSupply.add(_amount) <= minting_capped_amount); _totalSupply = _totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } pragma solidity 0.4.24; import './Ownable.sol'; /** @notice This contract provides support for whitelisting addresses. * only whitelisted addresses are allowed to send ether and buy tokens * during preSale and Pulic crowdsale. * @dev after deploying contract, deploy Presale / Crowdsale contract using * EmalWhitelist address. To allow claim refund functionality and allow wallet * owner efatoora to send ether to Crowdsale contract for refunds add wallet * address to whitelist. */ contract EmalWhitelist is Ownable { mapping(address => bool) whitelist; event AddToWhitelist(address investorAddr); event RemoveFromWhitelist(address investorAddr); /** @dev Throws if operator is not whitelisted. */ modifier onlyIfWhitelisted(address investorAddr) { require(whitelist[investorAddr]); _; } constructor() public { owner = msg.sender; } /** @dev Returns if an address is whitelisted or not */ function isWhitelisted(address investorAddr) public view returns(bool whitelisted) { return whitelist[investorAddr]; } /** * @dev Adds an investor to whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function addToWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = true; return true; } /** * @dev Removes an investor's address from whitelist * @param investorAddr The address to user to be added to the whitelist, signifies that the user completed KYC requirements. */ function removeFromWhitelist(address investorAddr) public onlyOwner returns(bool success) { require(investorAddr!= address(0)); whitelist[investorAddr] = false; return true; } } pragma solidity 0.4.24; contract ERC20Token { 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, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 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); } pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity 0.4.24; import "./Ownable.sol"; /* Pausable contract */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity 0.4.24; import './ERC20Token.sol'; import './SafeMath.sol'; contract StandardToken is ERC20Token { using SafeMath for uint256; // Global variable to store total number of tokens passed from EmalToken.sol uint256 _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address tokenOwner) public view returns (uint256){ return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public returns (bool){ require(to != address(0)); require(tokens > 0 && tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // Transfer tokens from one address to another function transferFrom(address from, address to, uint256 tokens) public returns (bool success){ require(to != address(0)); require(tokens > 0 && tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from, to, tokens); return true; } // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. function approve(address spender, uint256 tokens) public returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // Function to check the amount of tokens that an owner allowed to a spender. function allowance(address tokenOwner, address spender) public view returns (uint256 remaining){ return allowed[tokenOwner][spender]; } // 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) function increaseApproval(address spender, uint256 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; } // 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) function decreaseApproval(address spender, uint256 subtractedValue ) public returns (bool){ uint256 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; } } pragma solidity 0.4.24; import "./EmalToken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; /** @title StandardTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner. */ contract StandardTokenVesting is Ownable { using SafeMath for uint256; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; owner = msg.sender; cliff = _start.add(_cliff); start = _start; } /** @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; } /** @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(EmalToken token) public onlyOwner returns(bool) { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); return true; } /** @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(EmalToken token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** @dev Calculates the amount that has already vested. * @param token Emal token which is being vested */ function vestedAmount(EmalToken token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } }
Transfers vested tokens to beneficiary. token ERC20 token which is being vested/
function release(EmalToken token) public returns (bool){ uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); return true; }
7,279,337
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul interface DharmaTradeReserveV5Interface { event ROLEMODIFIED441(Role indexed role, address account); //inject NONSTANDARD NAMING event ROLEPAUSED231(Role indexed role); //inject NONSTANDARD NAMING event ROLEUNPAUSED960(Role indexed role); //inject NONSTANDARD NAMING event ETHERRECEIVED44(address sender, uint256 amount); //inject NONSTANDARD NAMING enum Role { // # DEPOSIT_MANAGER, // 0 ADJUSTER, // 1 WITHDRAWAL_MANAGER, // 2 RESERVE_TRADER, // 3 PAUSER // 4 } struct RoleStatus { address account; bool paused; } function TRADEDAIFORETHER831( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEETHERFORDAI150( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought); function TRADEDAIFORTOKEN796( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADETOKENFORDAI354( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought); function TRADEDAIFORETHERUSINGRESERVES632( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI477( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function TRADEDAIFORTOKENUSINGRESERVES160( //inject NONSTANDARD NAMING address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI443( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function FINALIZEETHERDEPOSIT112( //inject NONSTANDARD NAMING address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external; function FINALIZEDAIDEPOSIT982( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external; function FINALIZEDHARMADAIDEPOSIT983( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external; function MINT439(uint256 daiAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING function REDEEM267(uint256 dDaiAmount) external returns (uint256 daiReceived); //inject NONSTANDARD NAMING function TRADEDDAIFORUSDC791( //inject NONSTANDARD NAMING uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function TRADEUSDCFORDDAI490( //inject NONSTANDARD NAMING uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function WITHDRAWUSDC225(address recipient, uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDAI871(address recipient, uint256 daiAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDHARMADAI182(address recipient, uint256 dDaiAmount) external; //inject NONSTANDARD NAMING function WITHDRAWUSDCTOPRIMARYRECIPIENT429(uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDAITOPRIMARYRECIPIENT980(uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWETHER987( //inject NONSTANDARD NAMING address payable recipient, uint256 etherAmount ) external; function WITHDRAW561( //inject NONSTANDARD NAMING ERC20Interface token, address recipient, uint256 amount ) external returns (bool success); function CALLANY447( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); function SETDAILIMIT819(uint256 daiAmount) external; //inject NONSTANDARD NAMING function SETETHERLIMIT192(uint256 daiAmount) external; //inject NONSTANDARD NAMING function SETPRIMARYUSDCRECIPIENT853(address recipient) external; //inject NONSTANDARD NAMING function SETPRIMARYDAIRECIPIENT291(address recipient) external; //inject NONSTANDARD NAMING function SETROLE200(Role role, address account) external; //inject NONSTANDARD NAMING function REMOVEROLE179(Role role) external; //inject NONSTANDARD NAMING function PAUSE944(Role role) external; //inject NONSTANDARD NAMING function UNPAUSE758(Role role) external; //inject NONSTANDARD NAMING function ISPAUSED720(Role role) external view returns (bool paused); //inject NONSTANDARD NAMING function ISROLE342(Role role) external view returns (bool hasRole); //inject NONSTANDARD NAMING function ISDHARMASMARTWALLET39( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet); function GETDEPOSITMANAGER376() external view returns (address depositManager); //inject NONSTANDARD NAMING function GETADJUSTER193() external view returns (address adjuster); //inject NONSTANDARD NAMING function GETRESERVETRADER467() external view returns (address reserveTrader); //inject NONSTANDARD NAMING function GETWITHDRAWALMANAGER690() external view returns (address withdrawalManager); //inject NONSTANDARD NAMING function GETPAUSER338() external view returns (address pauser); //inject NONSTANDARD NAMING function GETRESERVES367() external view returns ( //inject NONSTANDARD NAMING uint256 dai, uint256 dDai, uint256 dDaiUnderlying ); function GETDAILIMIT285() external view returns ( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 dDaiAmount ); function GETETHERLIMIT400() external view returns (uint256 etherAmount); //inject NONSTANDARD NAMING function GETPRIMARYUSDCRECIPIENT588() external view returns ( //inject NONSTANDARD NAMING address recipient ); function GETPRIMARYDAIRECIPIENT262() external view returns ( //inject NONSTANDARD NAMING address recipient ); function GETIMPLEMENTATION10() external view returns (address implementation); //inject NONSTANDARD NAMING function GETVERSION332() external view returns (uint256 version); //inject NONSTANDARD NAMING } interface ERC20Interface { function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE776(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE300(address, address) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER681(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM400(address, address, uint256) external returns (bool); //inject NONSTANDARD NAMING } interface DTokenInterface { function MINT439(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING function REDEEM267(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING function REDEEMUNDERLYING590(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFUNDERLYING496(address) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER681(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function APPROVE776(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function EXCHANGERATECURRENT187() external view returns (uint256); //inject NONSTANDARD NAMING } interface TradeHelperInterface { function TRADEUSDCFORDDAI490(uint256 amountUSDC, uint256 quotedDaiEquivalentAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING function TRADEDDAIFORUSDC791(uint256 amountDai, uint256 quotedUSDCAmount) external returns (uint256 usdcReceived); //inject NONSTANDARD NAMING function GETEXPECTEDDAI516(uint256 usdc) external view returns (uint256 dai); //inject NONSTANDARD NAMING function GETEXPECTEDUSDC789(uint256 dai) external view returns (uint256 usdc); //inject NONSTANDARD NAMING } interface UniswapV1Interface { function ETHTOTOKENSWAPINPUT868( //inject NONSTANDARD NAMING uint256 minTokens, uint256 deadline ) external payable returns (uint256 tokensBought); function TOKENTOETHTRANSFEROUTPUT757( //inject NONSTANDARD NAMING uint256 ethBought, uint256 maxTokens, uint256 deadline, address recipient ) external returns (uint256 tokensSold); } interface UniswapV2Interface { function SWAPTOKENSFOREXACTTOKENS12( //inject NONSTANDARD NAMING uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPEXACTTOKENSFORTOKENS249( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } interface EtherReceiverInterface { function SETTLEETHER953() external; //inject NONSTANDARD NAMING } library SafeMath { function ADD482(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function MUL891(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV332(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, "SafeMath: division by zero"); return a / b; } } contract TwoStepOwnable { event OWNERSHIPTRANSFERRED446( //inject NONSTANDARD NAMING address indexed previousOwner, address indexed newOwner ); address private _owner; address private _newPotentialOwner; function TRANSFEROWNERSHIP849(address newOwner) external ONLYOWNER739 { //inject NONSTANDARD NAMING require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } function CANCELOWNERSHIPTRANSFER3() external ONLYOWNER739 { //inject NONSTANDARD NAMING delete _newPotentialOwner; } function ACCEPTOWNERSHIP151() external { //inject NONSTANDARD NAMING require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OWNERSHIPTRANSFERRED446(_owner, msg.sender); _owner = msg.sender; } function OWNER633() external view returns (address) { //inject NONSTANDARD NAMING return _owner; } function ISOWNER526() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } modifier ONLYOWNER739() { //inject NONSTANDARD NAMING require(ISOWNER526(), "TwoStepOwnable: caller is not the owner."); _; } } contract DharmaTradeReserveV5ImplementationStaging is DharmaTradeReserveV5Interface, TwoStepOwnable { using SafeMath for uint256; // Maintain a role status mapping with assigned accounts and paused states. mapping(uint256 => RoleStatus) private _roles; // Maintain a "primary recipient" the withdrawal manager can transfer Dai to. address private _primaryDaiRecipient; // Maintain a "primary recipient" the withdrawal manager can transfer USDC to. address private _primaryUSDCRecipient; // Maintain a maximum allowable transfer size (in Dai) for the deposit manager. uint256 private _daiLimit; // Maintain a maximum allowable transfer size (in Ether) for the deposit manager. uint256 private _etherLimit; bool private _originatesFromReserveTrader; // unused, don't change storage layout uint256 private constant _version870 = 5; //inject NONSTANDARD NAMING // This contract interacts with USDC, Dai, and Dharma Dai. ERC20Interface internal constant _usdc497 = ERC20Interface( //inject NONSTANDARD NAMING 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); ERC20Interface internal constant _dai122 = ERC20Interface( //inject NONSTANDARD NAMING 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); DTokenInterface internal constant _ddai891 = DTokenInterface( //inject NONSTANDARD NAMING 0x00000000001876eB1444c986fD502e618c587430 ); TradeHelperInterface internal constant _trade_helper741 = TradeHelperInterface( //inject NONSTANDARD NAMING 0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d ); UniswapV1Interface internal constant _uniswap_dai582 = UniswapV1Interface( //inject NONSTANDARD NAMING 0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667 ); UniswapV2Interface internal constant _uniswap_router975 = UniswapV2Interface( //inject NONSTANDARD NAMING 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); EtherReceiverInterface internal constant _eth_receiver919 = EtherReceiverInterface( //inject NONSTANDARD NAMING 0xaf84687D21736F5E06f738c6F065e88890465E7c ); // The "Create2 Header" is used to compute smart wallet deployment addresses. bytes21 internal constant _create2_header355 = bytes21( //inject NONSTANDARD NAMING 0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory ); // The "Wallet creation code" header & footer are also used to derive wallets. bytes internal constant _wallet_creation_code_header592 = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; //inject NONSTANDARD NAMING bytes28 internal constant _wallet_creation_code_footer939 = bytes28( //inject NONSTANDARD NAMING 0x00000000000000000000000000000000000000000000000000000000 ); // Include a payable fallback so that the contract can receive Ether payments. function () external payable { emit ETHERRECEIVED44(msg.sender, msg.value); } function INITIALIZE936() external { //inject NONSTANDARD NAMING // Approve Uniswap router to transfer Dai on behalf of this contract. if (_dai122.ALLOWANCE300(address(this), address(_uniswap_router975)) != uint256(-1)) { bool ok = _dai122.APPROVE776(address(_uniswap_router975), uint256(-1)); require(ok, "Dai approval for Uniswap router failed."); } } function TRADEDAIFORETHER831( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. bool ok = (_dai122.TRANSFERFROM400(msg.sender, address(this), daiAmount)); require(ok, "Dai transfer in failed."); // Trade the Dai for the quoted Ether amount on Uniswap and send to caller. totalDaiSold = _uniswap_dai582.TOKENTOETHTRANSFEROUTPUT757( quotedEtherAmount, daiAmount, deadline, msg.sender ); } function TRADEDAIFORTOKEN796( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. bool ok = (_dai122.TRANSFERFROM400(msg.sender, address(this), daiAmount)); require(ok, "Dai transfer in failed."); // Establish a direct path (for now) between Dai and the target token. address[] memory path = new address[](2); path[0] = address(_dai122); path[1] = token; // Trade the Dai for the quoted token amount on Uniswap and send to caller. uint256[] memory amounts = new uint256[](2); amounts = _uniswap_router975.SWAPTOKENSFOREXACTTOKENS12( quotedTokenAmount, daiAmount, path, msg.sender, deadline ); totalDaiSold = amounts[0]; } function TRADEDAIFORETHERUSINGRESERVES632( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. uint256 daiBalance = _dai122.BALANCEOF395(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _ddai891.REDEEMUNDERLYING590(additionalDaiRequired); } // Trade the Dai for the quoted Ether amount on Uniswap. totalDaiSold = _uniswap_dai582.TOKENTOETHTRANSFEROUTPUT757( quotedEtherAmount, daiAmountFromReserves, deadline, address(_eth_receiver919) ); // Move the Ether from the receiver to this contract (gas workaround). _eth_receiver919.SETTLEETHER953(); } function TRADEETHERFORDAI150( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought) { // Trade the Ether for the quoted Dai amount on Uniswap. totalDaiBought = _uniswap_dai582.ETHTOTOKENSWAPINPUT868.value(msg.value)( quotedDaiAmount, deadline ); // Transfer the Dai to the caller and revert on failure. bool ok = (_dai122.TRANSFER681(msg.sender, quotedDaiAmount)); require(ok, "Dai transfer out failed."); } function TRADETOKENFORDAI354( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought) { // Transfer the token from the caller and revert on failure. bool ok = (token.TRANSFERFROM400(msg.sender, address(this), tokenAmount)); require(ok, "Token transfer in failed."); // Approve Uniswap router to transfer tokens on behalf of this contract. if (token.ALLOWANCE300(address(this), address(_uniswap_router975)) != uint256(-1)) { ok = token.APPROVE776(address(_uniswap_router975), uint256(-1)); require(ok, "Token approval for Uniswap router failed."); } // Establish a direct path (for now) between the target token and Dai. address[] memory path = new address[](2); path[0] = address(token); path[1] = address(_dai122); // Trade the Dai for the quoted token amount on Uniswap and send to caller. uint256[] memory amounts = new uint256[](2); amounts = _uniswap_router975.SWAPEXACTTOKENSFORTOKENS249( tokenAmount, quotedDaiAmount, path, msg.sender, deadline ); totalDaiBought = amounts[1]; // Transfer the Dai to the caller and revert on failure. ok = (_dai122.TRANSFER681(msg.sender, quotedDaiAmount)); require(ok, "Dai transfer out failed."); } function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI477( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade the Ether for the quoted Dai amount on Uniswap. totalDaiBought = _uniswap_dai582.ETHTOTOKENSWAPINPUT868.value( etherAmountFromReserves )( quotedDaiAmount, deadline ); // Mint dDai using the received Dai. totalDDaiMinted = _ddai891.MINT439(totalDaiBought); } function TRADEDAIFORTOKENUSINGRESERVES160( //inject NONSTANDARD NAMING address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. uint256 daiBalance = _dai122.BALANCEOF395(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _ddai891.REDEEMUNDERLYING590(additionalDaiRequired); } // Establish a direct path (for now) between Dai and the target token. address[] memory path = new address[](2); path[0] = address(_dai122); path[1] = token; // Trade the Dai for the quoted token amount on Uniswap. uint256[] memory amounts = new uint256[](2); amounts = _uniswap_router975.SWAPTOKENSFOREXACTTOKENS12( quotedTokenAmount, daiAmountFromReserves, path, address(this), deadline ); totalDaiSold = amounts[0]; } function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI443( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external ONLYOWNEROR153(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Approve Uniswap router to transfer tokens on behalf of this contract. if (token.ALLOWANCE300(address(this), address(_uniswap_router975)) != uint256(-1)) { bool ok = token.APPROVE776(address(_uniswap_router975), uint256(-1)); require(ok, "Token approval for Uniswap router failed."); } // Establish a direct path (for now) between the target token and Dai. address[] memory path = new address[](2); path[0] = address(token); path[1] = address(_dai122); // Trade the Dai for the quoted token amount on Uniswap. uint256[] memory amounts = new uint256[](2); amounts = _uniswap_router975.SWAPEXACTTOKENSFORTOKENS249( tokenAmountFromReserves, quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[1]; // Mint dDai using the received Dai. totalDDaiMinted = _ddai891.MINT439(totalDaiBought); } function FINALIZEDAIDEPOSIT982( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external ONLYOWNEROR153(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. require( _ISSMARTWALLET802(smartWallet, initialUserSigningKey), "Could not resolve smart wallet using provided signing key." ); // Ensure that the amount to transfer is lower than the limit. require(daiAmount < _daiLimit, "Transfer size exceeds the limit."); // Transfer the Dai to the specified smart wallet. require(_dai122.TRANSFER681(smartWallet, daiAmount), "Dai transfer failed."); } function FINALIZEDHARMADAIDEPOSIT983( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external ONLYOWNEROR153(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. require( _ISSMARTWALLET802(smartWallet, initialUserSigningKey), "Could not resolve smart wallet using provided signing key." ); // Get the current dDai exchange rate. uint256 exchangeRate = _ddai891.EXCHANGERATECURRENT187(); // Ensure that an exchange rate was actually returned. require(exchangeRate != 0, "Could not retrieve dDai exchange rate."); // Get the equivalent Dai amount of the transfer. uint256 daiEquivalent = (dDaiAmount.MUL891(exchangeRate)) / 1e18; // Ensure that the amount to transfer is lower than the limit. require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit."); // Transfer the dDai to the specified smart wallet. require(_ddai891.TRANSFER681(smartWallet, dDaiAmount), "dDai transfer failed."); } function FINALIZEETHERDEPOSIT112( //inject NONSTANDARD NAMING address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external ONLYOWNEROR153(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. require( _ISSMARTWALLET802(smartWallet, initialUserSigningKey), "Could not resolve smart wallet using provided signing key." ); // Ensure that the amount to transfer is lower than the limit. require(etherAmount < _etherLimit, "Transfer size exceeds the limit."); // Transfer the Ether to the specified smart wallet. bool ok; (ok, ) = smartWallet.call.value(etherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function MINT439( //inject NONSTANDARD NAMING uint256 daiAmount ) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 dDaiMinted) { // Use the specified amount of Dai to mint dDai. dDaiMinted = _ddai891.MINT439(daiAmount); } function REDEEM267( //inject NONSTANDARD NAMING uint256 dDaiAmount ) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 daiReceived) { // Redeem the specified amount of dDai for Dai. daiReceived = _ddai891.REDEEM267(dDaiAmount); } function TRADEUSDCFORDDAI490( //inject NONSTANDARD NAMING uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 dDaiMinted) { dDaiMinted = _trade_helper741.TRADEUSDCFORDDAI490( usdcAmount, quotedDaiEquivalentAmount ); } function TRADEDDAIFORUSDC791( //inject NONSTANDARD NAMING uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external ONLYOWNEROR153(Role.ADJUSTER) returns (uint256 usdcReceived) { usdcReceived = _trade_helper741.TRADEDDAIFORUSDC791( daiEquivalentAmount, quotedUSDCAmount ); } function WITHDRAWUSDCTOPRIMARYRECIPIENT429( //inject NONSTANDARD NAMING uint256 usdcAmount ) external ONLYOWNEROR153(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryUSDCRecipient; require( primaryRecipient != address(0), "No USDC primary recipient currently set." ); // Transfer the supplied USDC amount to the primary recipient. bool ok = _usdc497.TRANSFER681(primaryRecipient, usdcAmount); require(ok, "USDC transfer failed."); } function WITHDRAWDAITOPRIMARYRECIPIENT980( //inject NONSTANDARD NAMING uint256 daiAmount ) external ONLYOWNEROR153(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryDaiRecipient; require( primaryRecipient != address(0), "No Dai primary recipient currently set." ); // Transfer the supplied Dai amount to the primary recipient. bool ok = _dai122.TRANSFER681(primaryRecipient, daiAmount); require(ok, "Dai transfer failed."); } function WITHDRAWUSDC225( //inject NONSTANDARD NAMING address recipient, uint256 usdcAmount ) external ONLYOWNER739 { // Transfer the USDC to the specified recipient. require(_usdc497.TRANSFER681(recipient, usdcAmount), "USDC transfer failed."); } function WITHDRAWDAI871( //inject NONSTANDARD NAMING address recipient, uint256 daiAmount ) external ONLYOWNER739 { // Transfer the Dai to the specified recipient. require(_dai122.TRANSFER681(recipient, daiAmount), "Dai transfer failed."); } function WITHDRAWDHARMADAI182( //inject NONSTANDARD NAMING address recipient, uint256 dDaiAmount ) external ONLYOWNER739 { // Transfer the dDai to the specified recipient. require(_ddai891.TRANSFER681(recipient, dDaiAmount), "dDai transfer failed."); } function WITHDRAWETHER987( //inject NONSTANDARD NAMING address payable recipient, uint256 etherAmount ) external ONLYOWNER739 { bool ok; // Transfer the Ether to the specified recipient. (ok, ) = recipient.call.value(etherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function WITHDRAW561( //inject NONSTANDARD NAMING ERC20Interface token, address recipient, uint256 amount ) external ONLYOWNER739 returns (bool success) { // Transfer the token to the specified recipient. success = token.TRANSFER681(recipient, amount); } function CALLANY447( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external ONLYOWNER739 returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified data. (ok, returnData) = target.call.value(amount)(data); } function SETDAILIMIT819(uint256 daiAmount) external ONLYOWNER739 { //inject NONSTANDARD NAMING // Set the new limit. _daiLimit = daiAmount; } function SETETHERLIMIT192(uint256 etherAmount) external ONLYOWNER739 { //inject NONSTANDARD NAMING // Set the new limit. _etherLimit = etherAmount; } function SETPRIMARYUSDCRECIPIENT853(address recipient) external ONLYOWNER739 { //inject NONSTANDARD NAMING // Set the new primary recipient. _primaryUSDCRecipient = recipient; } function SETPRIMARYDAIRECIPIENT291(address recipient) external ONLYOWNER739 { //inject NONSTANDARD NAMING // Set the new primary recipient. _primaryDaiRecipient = recipient; } function PAUSE944(Role role) external ONLYOWNEROR153(Role.PAUSER) { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(!storedRoleStatus.paused, "Role in question is already paused."); storedRoleStatus.paused = true; emit ROLEPAUSED231(role); } function UNPAUSE758(Role role) external ONLYOWNER739 { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(storedRoleStatus.paused, "Role in question is already unpaused."); storedRoleStatus.paused = false; emit ROLEUNPAUSED960(role); } function SETROLE200(Role role, address account) external ONLYOWNER739 { //inject NONSTANDARD NAMING require(account != address(0), "Must supply an account."); _SETROLE808(role, account); } function REMOVEROLE179(Role role) external ONLYOWNER739 { //inject NONSTANDARD NAMING _SETROLE808(role, address(0)); } function ISPAUSED720(Role role) external view returns (bool paused) { //inject NONSTANDARD NAMING paused = _ISPAUSED545(role); } function ISROLE342(Role role) external view returns (bool hasRole) { //inject NONSTANDARD NAMING hasRole = _ISROLE373(role); } function ISDHARMASMARTWALLET39( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet) { dharmaSmartWallet = _ISSMARTWALLET802(smartWallet, initialUserSigningKey); } function GETDEPOSITMANAGER376() external view returns (address depositManager) { //inject NONSTANDARD NAMING depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account; } function GETADJUSTER193() external view returns (address adjuster) { //inject NONSTANDARD NAMING adjuster = _roles[uint256(Role.ADJUSTER)].account; } function GETRESERVETRADER467() external view returns (address reserveTrader) { //inject NONSTANDARD NAMING reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account; } function GETWITHDRAWALMANAGER690() external view returns (address withdrawalManager) { //inject NONSTANDARD NAMING withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account; } function GETPAUSER338() external view returns (address pauser) { //inject NONSTANDARD NAMING pauser = _roles[uint256(Role.PAUSER)].account; } function GETRESERVES367() external view returns ( //inject NONSTANDARD NAMING uint256 dai, uint256 dDai, uint256 dDaiUnderlying ) { dai = _dai122.BALANCEOF395(address(this)); dDai = _ddai891.BALANCEOF395(address(this)); dDaiUnderlying = _ddai891.BALANCEOFUNDERLYING496(address(this)); } function GETDAILIMIT285() external view returns ( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 dDaiAmount ) { daiAmount = _daiLimit; dDaiAmount = (daiAmount.MUL891(1e18)).DIV332(_ddai891.EXCHANGERATECURRENT187()); } function GETETHERLIMIT400() external view returns (uint256 etherAmount) { //inject NONSTANDARD NAMING etherAmount = _etherLimit; } function GETPRIMARYUSDCRECIPIENT588() external view returns ( //inject NONSTANDARD NAMING address recipient ) { recipient = _primaryUSDCRecipient; } function GETPRIMARYDAIRECIPIENT262() external view returns ( //inject NONSTANDARD NAMING address recipient ) { recipient = _primaryDaiRecipient; } function GETIMPLEMENTATION10() external view returns ( //inject NONSTANDARD NAMING address implementation ) { (bool ok, bytes memory returnData) = address( 0x481B1a16E6675D33f8BBb3a6A58F5a9678649718 ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } function GETVERSION332() external view returns (uint256 version) { //inject NONSTANDARD NAMING version = _version870; } function _SETROLE808(Role role, address account) internal { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; if (account != storedRoleStatus.account) { storedRoleStatus.account = account; emit ROLEMODIFIED441(role, account); } } function _ISROLE373(Role role) internal view returns (bool hasRole) { //inject NONSTANDARD NAMING hasRole = msg.sender == _roles[uint256(role)].account; } function _ISPAUSED545(Role role) internal view returns (bool paused) { //inject NONSTANDARD NAMING paused = _roles[uint256(role)].paused; } function _ISSMARTWALLET802( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) internal pure returns (bool) { // Derive the keccak256 hash of the smart wallet initialization code. bytes32 initCodeHash = keccak256( abi.encodePacked( _wallet_creation_code_header592, initialUserSigningKey, _wallet_creation_code_footer939 ) ); // Attempt to derive a smart wallet address that matches the one provided. address target; for (uint256 nonce = 0; nonce < 10; nonce++) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using all inputs. abi.encodePacked( // pack all inputs to the hash together. _create2_header355, // pass in control character + factory address. nonce, // pass in current nonce as the salt. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); // Exit early if the provided smart wallet matches derived target address. if (target == smartWallet) { return true; } // Otherwise, increment the nonce and derive a new salt. nonce++; } // Explicity recognize no target was found matching provided smart wallet. return false; } modifier ONLYOWNEROR153(Role role) { //inject NONSTANDARD NAMING if (!ISOWNER526()) { require(_ISROLE373(role), "Caller does not have a required role."); require(!_ISPAUSED545(role), "Role in question is currently paused."); } _; } }
inject NONSTANDARD NAMING
function SETPRIMARYUSDCRECIPIENT853(address recipient) external ONLYOWNER739 {
6,408,765
./partial_match/4/0x614bA1c3F900a8E1F3Ded518D3F28B2F1551c6ea/sources/LvChefV3.sol
Safe lv1 transfer function, just in case if rounding error causes pool to not have enough lv1s.
function safelv1Transfer(address _to, uint256 _amount) internal { uint256 lv1Bal = lv1.balanceOf(address(this)); if (_amount > lv1Bal) { lv1.transfer(_to, lv1Bal); lv1.transfer(_to, _amount); } }
8,669,812
pragma solidity 0.4.25; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @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,"Math error"); 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,"Math error"); // 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,"Math error"); 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,"Math error"); 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,"Math error"); return a % b; } } /** * @title Standard ERC20 token * @dev Implementation of the basic standard token. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal balances_; mapping (address => mapping (address => uint256)) private allowed_; uint256 private totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances_[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed_[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances_[msg.sender],"Invalid value"); require(_to != address(0),"Invalid address"); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed_[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances_[_from],"Value is more than balance"); require(_value <= allowed_[_from][msg.sender],"Value is more than alloved"); require(_to != address(0),"Invalid address"); 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 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, uint256 _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, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed_[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed_[msg.sender][_spender] = 0; } else { allowed_[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]); return true; } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param _account The account that will receive the created tokens. * @param _amount The amount that will be created. */ function _mint(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); totalSupply_ = totalSupply_.add(_amount); balances_[_account] = balances_[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param _account The account whose tokens will be burnt. * @param _amount The amount that will be burnt. */ function _burn(address _account, uint256 _amount) internal { require(_account != 0,"Invalid address"); require(_amount <= balances_[_account],"Amount is more than balance"); totalSupply_ = totalSupply_.sub(_amount); balances_[_account] = balances_[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } } /** * @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( IERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value),"Transfer error"); } function safeTransferFrom( IERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value),"Tranfer error"); } function safeApprove( IERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value),"Approve error"); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable { event Paused(); event Unpaused(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused,"Contract is paused, sorry"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused, "Contract is running now"); _; } } /** * @title Pausable token * @dev ERC20 modified with pausable transfers. **/ contract ERC20Pausable is ERC20, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Contract ATHLETICO token * @dev ERC20 compatible token contract */ contract ATHLETICOToken is ERC20Pausable { string public constant name = "ATHLETICO TOKEN"; string public constant symbol = "ATH"; uint32 public constant decimals = 18; uint256 public INITIAL_SUPPLY = 1000000000 * 1 ether; // 1 000 000 000 address public CrowdsaleAddress; bool public ICOover; mapping (address => bool) public kyc; mapping (address => uint256) public sponsors; event LogSponsor( address indexed from, uint256 value ); constructor(address _CrowdsaleAddress) public { CrowdsaleAddress = _CrowdsaleAddress; _mint(_CrowdsaleAddress, INITIAL_SUPPLY); } modifier onlyOwner() { require(msg.sender == CrowdsaleAddress,"Only CrowdSale contract can run this"); _; } modifier validDestination( address to ) { require(to != address(0),"Empty address"); require(to != address(this),"RESTO Token address"); _; } modifier isICOover { if (msg.sender != CrowdsaleAddress){ require(ICOover == true,"Transfer of tokens is prohibited until the end of the ICO"); } _; } /** * @dev Override for testing address destination */ function transfer(address _to, uint256 _value) public validDestination(_to) isICOover returns (bool) { return super.transfer(_to, _value); } /** * @dev Override for testing address destination */ function transferFrom(address _from, address _to, uint256 _value) public validDestination(_to) isICOover returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Function to mint tokens * can run only from crowdsale contract * @param to The address that will receive the minted tokens. * @param _value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 _value) public onlyOwner { _mint(to, _value); } /** * @dev Function to burn tokens * Anyone can burn their tokens and in this way help the project. * Information about sponsors is public. * On the project website you can get a sponsor certificate. */ function burn(uint256 _value) public { _burn(msg.sender, _value); sponsors[msg.sender] = sponsors[msg.sender].add(_value); emit LogSponsor(msg.sender, _value); } /** * @dev function set kyc bool to true * can run only from crowdsale contract * @param _investor The investor who passed the procedure KYC */ function kycPass(address _investor) public onlyOwner { kyc[_investor] = true; } /** * @dev function set kyc bool to false * can run only from crowdsale contract * @param _investor The investor who not passed the procedure KYC (change after passing kyc - something wrong) */ function kycNotPass(address _investor) public onlyOwner { kyc[_investor] = false; } /** * @dev function set ICOOver bool to true * can run only from crowdsale contract */ function setICOover() public onlyOwner { ICOover = true; } /** * @dev function transfer tokens from special address to users * can run only from crowdsale contract */ function transferTokensFromSpecialAddress(address _from, address _to, uint256 _value) public onlyOwner whenNotPaused returns (bool){ require (balances_[_from] >= _value,"Decrease value"); balances_[_from] = balances_[_from].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev called from crowdsale contract to pause, triggers stopped state * can run only from crowdsale contract */ function pause() public onlyOwner whenNotPaused { paused = true; emit Paused(); } /** * @dev called from crowdsale contract to unpause, returns to normal state * can run only from crowdsale contract */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpaused(); } } /** * @title Ownable * @dev The Ownable contract has an owner and DAOContract addresses, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public DAOContract; address private candidate; constructor() public { owner = msg.sender; DAOContract = msg.sender; } modifier onlyOwner() { require(msg.sender == owner,"Access denied"); _; } modifier onlyDAO() { require(msg.sender == DAOContract,"Access denied"); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0),"Invalid address"); candidate = _newOwner; } function setDAOContract(address _newDAOContract) public onlyOwner { require(_newDAOContract != address(0),"Invalid address"); DAOContract = _newDAOContract; } function confirmOwnership() public { require(candidate == msg.sender,"Only from candidate"); owner = candidate; delete candidate; } } contract TeamAddress { } contract BountyAddress { } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale */ contract Crowdsale is Ownable { using SafeMath for uint256; using SafeERC20 for ATHLETICOToken; event LogStateSwitch(State newState); event LogRefunding(address indexed to, uint256 amount); mapping(address => uint) public crowdsaleBalances; uint256 public softCap = 250 * 1 ether; address internal myAddress = this; ATHLETICOToken public token = new ATHLETICOToken(myAddress); uint64 public crowdSaleStartTime; uint64 public crowdSaleEndTime = 1559347200; // 01.06.2019 0:00:00 uint256 internal minValue = 0.005 ether; //Addresses for store tokens TeamAddress public teamAddress = new TeamAddress(); BountyAddress public bountyAddress = new BountyAddress(); // How many token units a buyer gets per wei. uint256 public rate; // Amount of wei raised uint256 public weiRaised; event LogWithdraw( address indexed from, address indexed to, uint256 amount ); event LogTokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); // Create state of contract enum State { Init, CrowdSale, Refunding, WorkTime } State public currentState = State.Init; modifier onlyInState(State state){ require(state==currentState); _; } constructor() public { uint256 totalTokens = token.INITIAL_SUPPLY(); /** * @dev Inicial distributing tokens to special adresses * TeamAddress - 10% * BountyAddress - 5% */ _deliverTokens(teamAddress, totalTokens.div(10)); _deliverTokens(bountyAddress, totalTokens.div(20)); rate = 20000; setState(State.CrowdSale); crowdSaleStartTime = uint64(now); } /** * @dev public function finishing crowdsale if enddate is coming or softcap is passed */ function finishCrowdSale() public onlyInState(State.CrowdSale) { require(now >= crowdSaleEndTime || myAddress.balance >= softCap, "Too early"); if(myAddress.balance >= softCap) { setState(State.WorkTime); token.setICOover(); } else { setState(State.Refunding); } } /** * @dev fallback function */ function () external payable { buyTokens(msg.sender); } /** * @dev token purchase * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); crowdsaleBalances[_beneficiary] = crowdsaleBalances[_beneficiary].add(weiAmount); emit LogTokensPurchased( msg.sender, _beneficiary, weiAmount, tokens ); } function setState(State _state) internal { currentState = _state; emit LogStateSwitch(_state); } /** * @dev called by the owner to pause, triggers stopped state */ function pauseCrowdsale() public onlyOwner { token.pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpauseCrowdsale() public onlyOwner { token.unpause(); } /** * @dev called by the DAO to set new rate */ function setRate(uint256 _newRate) public onlyDAO { rate = _newRate; } /** * @dev function set kyc bool to true * @param _investor The investor who passed the procedure KYC */ function setKYCpassed(address _investor) public onlyDAO returns(bool){ token.kycPass(_investor); return true; } /** * @dev function set kyc bool to false * @param _investor The investor who not passed the procedure KYC after passing */ function setKYCNotPassed(address _investor) public onlyDAO returns(bool){ token.kycNotPass(_investor); return true; } /** * @dev the function tranfer tokens from TeamAddress */ function transferTokensFromTeamAddress(address _investor, uint256 _value) public onlyDAO returns(bool){ token.transferTokensFromSpecialAddress(address(teamAddress), _investor, _value); return true; } /** * @dev the function tranfer tokens from BountyAddress */ function transferTokensFromBountyAddress(address _investor, uint256 _value) public onlyDAO returns(bool){ token.transferTokensFromSpecialAddress(address(bountyAddress), _investor, _value); return true; } /** * @dev Validation of an incoming purchase. internal function. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view{ require(_beneficiary != address(0),"Invalid address"); require(_weiAmount >= minValue,"Min amount is 0.005 ether"); require(currentState != State.Refunding, "Only for CrowdSale and Work stage."); } /** * @dev internal function * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Function transfer token to new investors * Access restricted DAO */ function transferTokens(address _newInvestor, uint256 _tokenAmount) public onlyDAO { _deliverTokens(_newInvestor, _tokenAmount); } /** * @dev Function mint tokens to winners or prize funds contracts * Access restricted DAO */ function mintTokensToWinners(address _address, uint256 _tokenAmount) public onlyDAO { require(currentState == State.WorkTime, "CrowdSale is not finished yet. Access denied."); token.mint(_address, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev this function is ether converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 bonus = 0; uint256 resultAmount = _weiAmount; /** * ICO bonus UnisTimeStamp * Start date End date * StartTime -01.01.2019 - 100% 1543622400 1546300800 * 01.01.2019-01.02.2019 - 50% 1546300800 1548979200 * 01.02.2019-01.03.2019 - 25% 1548979200 1551398400 */ if (now >= crowdSaleStartTime && now < 1546300800) { bonus = 100; } if (now >= 1546300800 && now < 1548979200) { bonus = 50; } if (now >= 1548979200 && now < 1551398400) { bonus = 25; } if (bonus > 0) { resultAmount += _weiAmount.mul(bonus).div(100); } return resultAmount.mul(rate); } /** * @dev function returns funds to investors in case of project failure. */ function refund() public payable{ require(currentState == State.Refunding, "Only for Refunding stage."); // refund ether to investors uint value = crowdsaleBalances[msg.sender]; crowdsaleBalances[msg.sender] = 0; msg.sender.transfer(value); emit LogRefunding(msg.sender, value); } /** * @dev function of withdrawal of funds for the development of the project if successful */ function withdrawFunds (address _to, uint256 _value) public onlyDAO { require(currentState == State.WorkTime, "CrowdSale is not finished yet. Access denied."); require (myAddress.balance >= _value,"Value is more than balance"); require(_to != address(0),"Invalid address"); _to.transfer(_value); emit LogWithdraw(msg.sender, _to, _value); } }
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,"Math error"); uint256 c = _a - _b; return c; }
7,275,045
./partial_match/1/0x44383018ecf3DBED34eE621439a5Ff6002e8209b/sources/contracts/libraries/GovernanceUtilV1.sol
The date and time prior to which a governance administrator may still initiate a "emergency resolution." Warning: this function does not validate the cover and product key supplied. s Specify store instance coverKey Enter cover key productKey Enter product key/
function getResolutionDeadlineInternal( IStore s, bytes32 coverKey, bytes32 productKey ) external view returns (uint256) { return s.getUintByKeys(ProtoUtilV1.NS_RESOLUTION_DEADLINE, coverKey, productKey); }
10,998,113