file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/80001/0x24f51617c1ad2120CCd1c238AED2f770A772630E/sources/src/AllowListDrop.sol
,-. `-' /|\ | ,----------. / \ |ERC721Drop| Caller `----+-----' | adminMintAirdrop() | | ----------------------------------> | | | | _________________________________________________________________ ! ALT / caller is not admin or minter role? | ! !_____/ | | ! ! | revert Access_MissingRoleOrAdmin()| ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | _________________________________________________________________ ! ALT / drop has no tokens left for recipients to mint? ! !_____/ | | ! ! | revert Mint_SoldOut() | ! ! | <---------------------------------- ! !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | | | _____________________________________ | ! LOOP / for all recipients ! | !______/ | ! | ! |----. ! | ! | | mint tokens ! | ! |<---' ! | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! | | | return last minted token ID | | <---------------------------------- Caller ,----+-----. ,-. |ERC721Drop| `-' `----------' /|\ | / \ This mints multiple editions to the given list of addresses. recipients list of addresses to send the newly minted editions to
function adminMintAirdrop(address[] calldata recipients) external override onlyRoleOrAdmin(MINTER_ROLE) canMintTokens(recipients.length) returns (uint256) { uint256 atId = _currentIndex; uint256 startAt = atId; unchecked { for ( uint256 endAt = atId + recipients.length; atId < endAt; atId++ ) { _mintNFTs(recipients[atId - startAt], 1); } } return _lastMintedTokenId(); }
851,109
pragma solidity >=0.8.0 <0.9.0; // SPDX-License-Identifier: MIT import "./interfaces.sol"; contract Verification { uint8 public constant STATUS_WAITING = 0; uint8 public constant STATUS_VERIFYING = 1; uint8 public constant REWARD_SECTOR = 0; uint8 public constant REWARD_SEED = 1; uint8 public constant REWARD_VERIFY = 2; ITurboFil public turboFil; ISector public sector; bytes28 public seed; address payable public seedSubmitter; uint256 public sectorReward; uint256 public seedReward; uint256 public verifyReward; uint256 public verifyThreshold; uint8 public status; bytes28 _proof; uint256 _submitProofDDL; uint256 _verifyProofDDL; mapping(address=>bool) public hasVerified; address[] trueVerifiers; address[] falseVerifiers; modifier onlyStatus(uint8 status_) { require(status == status_, "Verification: not at required status"); _; } event ProofSubmitted(bytes28 indexed sector_afid, bytes28 indexed seed, bytes28 proof); event ProofVerified(bytes28 indexed sector_afid, bytes28 indexed seed, bytes28 proof, bool indexed result); event Reward(uint8 indexed reward_type, address indexed to, uint256 amount); event VerifyFinish(bool indexed result); /// @dev created by TurboFil constructor( address payable sector_, bytes28 seed_, address payable seedSubmitter_, uint256 submitProofTimeout_, uint256 verifyProofTimeout_, uint256 verifyThreshold_, uint256 sectorReward_, uint256 seedReward_, uint256 verifyReward_ ) payable { require(msg.value >= sectorReward_ + seedReward_ + verifyReward_ * verifyThreshold_, "Verification: not enough funds for rewards"); turboFil = ITurboFil(msg.sender); sector = ISector(sector_); seed = seed_; seedSubmitter = seedSubmitter_; sectorReward = sectorReward_; seedReward = seedReward_; verifyReward = verifyReward_; _submitProofDDL = block.number + submitProofTimeout_; _verifyProofDDL = _submitProofDDL + verifyProofTimeout_; verifyThreshold = verifyThreshold_; } /// @notice Submit proof of the sector for verification /// @notice This function must be called by sector owner /// @param proof_ the afid of the proof function submitProof(bytes28 proof_) onlyStatus(STATUS_WAITING) external { require(sector.owner() == msg.sender, "Verification: caller is not sector owner"); require(block.number <= _submitProofDDL, "Verification: submit proof too late"); _proof = proof_; status = STATUS_VERIFYING; emit ProofSubmitted(sector.afid(), seed, proof_); } /// @notice Submit the verification result of the proof. /// @notice This function must be called by users who has VERIFY_ROLE in TurboFil contract. /// @param result_ whether the proof is valid or not function verifyProof(bool result_) onlyStatus(STATUS_VERIFYING) external { require(turboFil.hasVerifyRole(msg.sender), "Verification: does not have privilege to verify proof"); require(block.number <= _verifyProofDDL, "Verification: verify proof too late"); require(!hasVerified[msg.sender], "Verification: caller has already verified"); if (result_) { trueVerifiers.push(msg.sender); } else { falseVerifiers.push(msg.sender); } hasVerified[msg.sender] = true; emit ProofVerified(sector.afid(), seed, proof(), result_); if (trueVerifiers.length >= verifyThreshold) { emit VerifyFinish(true); _reward(); } else if (falseVerifiers.length >= verifyThreshold) { emit VerifyFinish(false); _punish(); } } function _reward() internal { sector.verificationResult{value: sectorReward}(seed, true); emit Reward(REWARD_SECTOR, address(sector), sectorReward); bool success = seedSubmitter.send(seedReward); if (success) emit Reward(REWARD_SEED, seedSubmitter, seedReward); for (uint256 i = 0; i < trueVerifiers.length; i++){ bool success = payable(trueVerifiers[i]).send(verifyReward); if (success) emit Reward(REWARD_VERIFY, trueVerifiers[i], verifyReward); } if (address(this).balance > 0) { payable(address(turboFil)).transfer(address(this).balance); } } function _punish() internal { sector.verificationResult(seed, false); seedSubmitter.transfer(seedReward); for (uint256 i = 0; i < falseVerifiers.length; i++){ payable(falseVerifiers[i]).send(verifyReward); } if (address(this).balance > 0) { payable(address(turboFil)).transfer(address(this).balance); } } /// @notice collect TFC that is not given as reward. function collectFunds() public { require(!fail() && !pass() && (expireSubmitProofDDL() || expireVerifyProofDDL()), "Verification: not allowed to collect funds"); if (address(this).balance > 0) payable(address(turboFil)).transfer(address(this).balance); } /* View functions */ function proof() onlyStatus(STATUS_VERIFYING) view public returns (bytes28) { return _proof; } function submitProofDDL() onlyStatus(STATUS_WAITING) view public returns (uint256) { return _submitProofDDL; } function verifyProofDDL() onlyStatus(STATUS_VERIFYING) view public returns (uint256) { return _verifyProofDDL; } function expireSubmitProofDDL() view public returns (bool) { return block.number > submitProofDDL(); } function expireVerifyProofDDL() view public returns (bool) { return block.number > verifyProofDDL(); } function fail() view public returns (bool) { return falseVerifiers.length >= verifyThreshold; } function pass() view public returns (bool) { return trueVerifiers.length >= verifyThreshold; } // @notice Sector owner fails to submit proof within timeout. function abandoned() view public returns (bool) { if (status == STATUS_WAITING && expireSubmitProofDDL()) { return true; }else { return false; } } // @notice Sector owner succeeds to submit proof but there are not enough verifiers within timeout. function deadend() view public returns (bool) { if (status == STATUS_VERIFYING && expireVerifyProofDDL()){ return false; }else { return true; } } }
Submit proof of the sector for verification This function must be called by sector owner proof_ the afid of the proof
function submitProof(bytes28 proof_) onlyStatus(STATUS_WAITING) external { require(sector.owner() == msg.sender, "Verification: caller is not sector owner"); require(block.number <= _submitProofDDL, "Verification: submit proof too late"); _proof = proof_; status = STATUS_VERIFYING; emit ProofSubmitted(sector.afid(), seed, proof_); }
6,344,519
./partial_match/42/0x925b6Dea592f731A9183cAe3a29568e2dD98cBE5/sources/TimeBasedSwitch.sol
inheritdoc ITimeBasedSwitch
function terminateSwitchEarly() public payable override onlyValid(msg.sender) nonReentrant { uint remains = users[msg.sender].amount; users[msg.sender].amount = 0; users[msg.sender].isValid = false; (bool success, ) = msg.sender.call.value(remains)(""); require(success, 'transfer failed'); for(uint i = 0; i < users[msg.sender].tokensLocked.length; i++) { address tokenToWithdraw = users[msg.sender].tokensLocked[i]; withdrawToken(tokenToWithdraw, users[msg.sender].tokens[tokenToWithdraw], msg.sender); } uint collectiblesLength = users[msg.sender].collectiblesLocked.length; for(uint i = 0; i < collectiblesLength; i++) { NFT storage currentCollectible = users[msg.sender].collectiblesLocked[i]; withdrawCollectible(currentCollectible.tokenAddress, currentCollectible.id, msg.sender); } delete users[msg.sender]; emit SwitchTerminated(msg.sender); }
9,074,591
./full_match/1/0x41f6b87E6a34D17871b23C5226057eEA96Ad3aa2/sources/contracts/RewardToolsDCLBordersContract.sol
Set the minimum number of days that a border can be removed for
function setMinDaysToRemove(uint256 minDays) public onlyOwner { settings.minDaysToRemove = minDays; }
3,126,438
pragma solidity 0.5.10; import "../interfaces/IBlockRewardAuRa.sol"; import "../interfaces/IERC677.sol"; import "../interfaces/IGovernance.sol"; import "../interfaces/IStakingAuRa.sol"; import "../interfaces/IValidatorSetAuRa.sol"; import "../upgradeability/UpgradeableOwned.sol"; import "../libs/SafeMath.sol"; /// @dev Implements staking and withdrawal logic. contract StakingAuRaBase is UpgradeableOwned, IStakingAuRa { using SafeMath for uint256; // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables, do not change their order, // and do not change their types! uint256[] internal _pools; uint256[] internal _poolsInactive; uint256[] internal _poolsToBeElected; uint256[] internal _poolsToBeRemoved; uint256[] internal _poolsLikelihood; uint256 internal _poolsLikelihoodSum; mapping(uint256 => address[]) internal _poolDelegators; mapping(uint256 => address[]) internal _poolDelegatorsInactive; mapping(address => uint256[]) internal _delegatorPools; mapping(address => mapping(uint256 => uint256)) internal _delegatorPoolsIndexes; mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal _stakeAmountByEpoch; mapping(uint256 => uint256) internal _stakeInitial; // Reserved storage slots to allow for layout changes in the future. uint256[24] private ______gapForInternal; /// @dev The limit of the minimum candidate stake (CANDIDATE_MIN_STAKE). uint256 public candidateMinStake; /// @dev The limit of the minimum delegator stake (DELEGATOR_MIN_STAKE). uint256 public delegatorMinStake; /// @dev The snapshot of tokens amount staked into the specified pool by the specified delegator /// before the specified staking epoch. Used by the `claimReward` function. /// The first parameter is the pool id, the second one is delegator's address, /// the third one is staking epoch number. mapping(uint256 => mapping(address => mapping(uint256 => uint256))) public delegatorStakeSnapshot; /// @dev The current amount of staking tokens/coins ordered for withdrawal from the specified /// pool by the specified staker. Used by the `orderWithdraw`, `claimOrderedWithdraw` and other functions. /// The first parameter is the pool id, the second one is the staker address. /// The second parameter should be a zero address if the staker is the pool itself. mapping(uint256 => mapping(address => uint256)) public orderedWithdrawAmount; /// @dev The current total amount of staking tokens/coins ordered for withdrawal from /// the specified pool by all of its stakers. Pool id is accepted as a parameter. mapping(uint256 => uint256) public orderedWithdrawAmountTotal; /// @dev The number of the staking epoch during which the specified staker ordered /// the latest withdraw from the specified pool. Used by the `claimOrderedWithdraw` function /// to allow the ordered amount to be claimed only in future staking epochs. The first parameter /// is the pool id, the second one is the staker address. /// The second parameter should be a zero address if the staker is the pool itself. mapping(uint256 => mapping(address => uint256)) public orderWithdrawEpoch; /// @dev The delegator's index in the array returned by the `poolDelegators` getter. /// Used by the `_removePoolDelegator` internal function. The first parameter is a pool id. /// The second parameter is delegator's address. /// If the value is zero, it may mean the array doesn't contain the delegator. /// Check if the delegator is in the array using the `poolDelegators` getter. mapping(uint256 => mapping(address => uint256)) public poolDelegatorIndex; /// @dev The delegator's index in the `poolDelegatorsInactive` array. /// Used by the `_removePoolDelegatorInactive` internal function. /// A delegator is considered inactive if they have withdrawn their stake from /// the specified pool but haven't yet claimed an ordered amount. /// The first parameter is a pool id. The second parameter is delegator's address. mapping(uint256 => mapping(address => uint256)) public poolDelegatorInactiveIndex; /// @dev The pool's index in the array returned by the `getPoolsInactive` getter. /// Used by the `_removePoolInactive` internal function. The pool id is accepted as a parameter. mapping(uint256 => uint256) public poolInactiveIndex; /// @dev The pool's index in the array returned by the `getPools` getter. /// Used by the `_removePool` internal function. A pool id is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `isPoolActive` getter. mapping(uint256 => uint256) public poolIndex; /// @dev The pool's index in the array returned by the `getPoolsToBeElected` getter. /// Used by the `_deletePoolToBeElected` and `_isPoolToBeElected` internal functions. /// The pool id is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `getPoolsToBeElected` getter. mapping(uint256 => uint256) public poolToBeElectedIndex; /// @dev The pool's index in the array returned by the `getPoolsToBeRemoved` getter. /// Used by the `_deletePoolToBeRemoved` internal function. /// The pool id is accepted as a parameter. /// If the value is zero, it may mean the array doesn't contain the address. /// Check the address is in the array using the `getPoolsToBeRemoved` getter. mapping(uint256 => uint256) public poolToBeRemovedIndex; /// @dev A boolean flag indicating whether the reward was already taken /// from the specified pool by the specified staker for the specified staking epoch. /// The first parameter is the pool id, the second one is staker's address, /// the third one is staking epoch number. /// The second parameter should be a zero address if the staker is the pool itself. mapping(uint256 => mapping(address => mapping(uint256 => bool))) public rewardWasTaken; /// @dev The amount of tokens currently staked into the specified pool by the specified /// staker. Doesn't include the amount ordered for withdrawal. /// The first parameter is the pool id, the second one is the staker address. /// The second parameter should be a zero address if the staker is the pool itself. mapping(uint256 => mapping(address => uint256)) public stakeAmount; /// @dev The number of staking epoch before which the specified delegator placed their first /// stake into the specified pool. If this is equal to zero, it means the delegator never /// staked into the specified pool. The first parameter is the pool id, /// the second one is delegator's address. mapping(uint256 => mapping(address => uint256)) public stakeFirstEpoch; /// @dev The number of staking epoch before which the specified delegator withdrew their stake /// from the specified pool. If this is equal to zero and `stakeFirstEpoch` is not zero, that means /// the delegator still has some stake in the specified pool. The first parameter is the pool id, /// the second one is delegator's address. mapping(uint256 => mapping(address => uint256)) public stakeLastEpoch; /// @dev The duration period (in blocks) at the end of staking epoch during which /// participants are not allowed to stake/withdraw/order/claim their staking tokens/coins. uint256 public stakeWithdrawDisallowPeriod; /// @dev The serial number of the current staking epoch. uint256 public stakingEpoch; /// @dev The duration of a staking epoch in blocks. uint256 public stakingEpochDuration; /// @dev The number of the first block of the current staking epoch. uint256 public stakingEpochStartBlock; /// @dev Returns the total amount of staking tokens/coins currently staked into the specified pool. /// Doesn't include the amount ordered for withdrawal. /// The pool id is accepted as a parameter. mapping(uint256 => uint256) public stakeAmountTotal; /// @dev The address of the `ValidatorSetAuRa` contract. IValidatorSetAuRa public validatorSetContract; /// @dev The block number of the last change in this contract. /// Can be used by Staking DApp. uint256 public lastChangeBlock; /// @dev The address of the `Governance` contract. IGovernance public governanceContract; // Reserved storage slots to allow for layout changes in the future. uint256[23] private ______gapForPublic; // ============================================== Constants ======================================================= /// @dev The max number of candidates (including validators). This limit was determined through stress testing. uint256 public constant MAX_CANDIDATES = 3000; // ================================================ Events ======================================================== /// @dev Emitted by the `_addPool` internal function to signal that /// a new pool is created. /// @param poolStakingAddress The staking address of newly added pool. /// @param poolMiningAddress The mining address of newly added pool. /// @param poolId The id of newly added pool. event AddedPool(address indexed poolStakingAddress, address indexed poolMiningAddress, uint256 poolId); /// @dev Emitted by the `claimOrderedWithdraw` function to signal the staker withdrew the specified /// amount of requested tokens/coins from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`. /// @param staker The address of the staker that withdrew the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the claim was made. /// @param amount The withdrawal amount. /// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`. event ClaimedOrderedWithdrawal( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount, uint256 fromPoolId ); /// @dev Emitted by the `moveStake` function to signal the staker moved the specified /// amount of stake from one pool to another during the specified staking epoch. /// @param fromPoolStakingAddress A staking address of the pool from which the `staker` moved the stake. /// @param toPoolStakingAddress A staking address of the destination pool where the `staker` moved the stake. /// @param staker The address of the staker who moved the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the `amount` was moved. /// @param amount The stake amount which was moved. /// @param fromPoolId An id of the pool from which the `staker` moved the stake. /// @param toPoolId An id of the destination pool where the `staker` moved the stake. event MovedStake( address fromPoolStakingAddress, address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount, uint256 fromPoolId, uint256 toPoolId ); /// @dev Emitted by the `orderWithdraw` function to signal the staker ordered the withdrawal of the /// specified amount of their stake from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress A staking address of the pool from which the `staker` /// ordered a withdrawal of the `amount`. /// @param staker The address of the staker that ordered the withdrawal of the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the order was made. /// @param amount The ordered withdrawal amount. Can be either positive or negative. /// See the `orderWithdraw` function. /// @param fromPoolId An id of the pool from which the `staker` ordered a withdrawal of the `amount`. event OrderedWithdrawal( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, int256 amount, uint256 fromPoolId ); /// @dev Emitted by the `stake` function to signal the staker placed a stake of the specified /// amount for the specified pool during the specified staking epoch. /// @param toPoolStakingAddress A staking address of the pool into which the `staker` placed the stake. /// @param staker The address of the staker that placed the stake. /// @param stakingEpoch The serial number of the staking epoch during which the stake was made. /// @param amount The stake amount. /// @param toPoolId An id of the pool into which the `staker` placed the stake. event PlacedStake( address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount, uint256 toPoolId ); /// @dev Emitted by the `withdraw` function to signal the staker withdrew the specified /// amount of a stake from the specified pool during the specified staking epoch. /// @param fromPoolStakingAddress A staking address of the pool from which the `staker` withdrew the `amount`. /// @param staker The address of staker that withdrew the `amount`. /// @param stakingEpoch The serial number of the staking epoch during which the withdrawal was made. /// @param amount The withdrawal amount. /// @param fromPoolId An id of the pool from which the `staker` withdrew the `amount`. event WithdrewStake( address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount, uint256 fromPoolId ); // ============================================== Modifiers ======================================================= /// @dev Ensures the transaction gas price is not zero. modifier gasPriceIsValid() { require(tx.gasprice != 0); _; } /// @dev Ensures the caller is the BlockRewardAuRa contract address. modifier onlyBlockRewardContract() { require(msg.sender == validatorSetContract.blockRewardContract()); _; } /// @dev Ensures the `initialize` function was called before. modifier onlyInitialized { require(isInitialized()); _; } /// @dev Ensures the caller is the ValidatorSetAuRa contract address. modifier onlyValidatorSetContract() { require(msg.sender == address(validatorSetContract)); _; } // =============================================== Setters ======================================================== /// @dev Fallback function. Prevents direct sending native coins to this contract. function () payable external { revert(); } /// @dev Adds a new candidate's pool to the list of active pools (see the `getPools` getter), /// moves the specified amount of staking tokens/coins from the candidate's staking address /// to the candidate's pool, and returns a unique id of the newly added pool. /// A participant calls this function using their staking address when /// they want to create a pool. This is a wrapper for the `stake` function. /// @param _amount The amount of tokens to be staked. Ignored when staking in native coins /// because `msg.value` is used in that case. /// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address /// (msg.sender). This address cannot be equal to `msg.sender`. /// @param _name A name of the pool as UTF-8 string (max length is 256 bytes). /// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes). function addPool( uint256 _amount, address _miningAddress, string calldata _name, string calldata _description ) external payable returns(uint256) { return _addPool(_amount, msg.sender, _miningAddress, false, _name, _description); } /// @dev Adds the `unremovable validator` to either the `poolsToBeElected` or the `poolsToBeRemoved` array /// depending on their own stake in their own pool when they become removable. This allows the /// `ValidatorSetAuRa.newValidatorSet` function to recognize the unremovable validator as a regular removable pool. /// Called by the `ValidatorSet.clearUnremovableValidator` function. /// @param _unremovablePoolId The pool id of the unremovable validator. function clearUnremovableValidator(uint256 _unremovablePoolId) external onlyValidatorSetContract { require(_unremovablePoolId != 0); if (stakeAmount[_unremovablePoolId][address(0)] != 0) { _addPoolToBeElected(_unremovablePoolId); _setLikelihood(_unremovablePoolId); } else { _addPoolToBeRemoved(_unremovablePoolId); } } /// @dev Increments the serial number of the current staking epoch. /// Called by the `ValidatorSetAuRa.newValidatorSet` at the last block of the finished staking epoch. function incrementStakingEpoch() external onlyValidatorSetContract { stakingEpoch++; } /// @dev Initializes the network parameters. /// Can only be called by the constructor of the `InitializerAuRa` contract or owner. /// @param _validatorSetContract The address of the `ValidatorSetAuRa` contract. /// @param _governanceContract The address of the `Governance` contract. /// @param _initialIds The array of initial validators' pool ids. /// @param _delegatorMinStake The minimum allowed amount of delegator stake in Wei. /// @param _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei. /// @param _stakingEpochDuration The duration of a staking epoch in blocks /// (e.g., 120954 = 1 week for 5-seconds blocks in AuRa). /// @param _stakingEpochStartBlock The number of the first block of initial staking epoch /// (must be zero if the network is starting from genesis block). /// @param _stakeWithdrawDisallowPeriod The duration period (in blocks) at the end of a staking epoch /// during which participants cannot stake/withdraw/order/claim their staking tokens/coins /// (e.g., 4320 = 6 hours for 5-seconds blocks in AuRa). function initialize( address _validatorSetContract, address _governanceContract, uint256[] calldata _initialIds, uint256 _delegatorMinStake, uint256 _candidateMinStake, uint256 _stakingEpochDuration, uint256 _stakingEpochStartBlock, uint256 _stakeWithdrawDisallowPeriod ) external { require(_validatorSetContract != address(0)); require(_initialIds.length > 0); require(_delegatorMinStake != 0); require(_candidateMinStake != 0); require(_stakingEpochDuration != 0); require(_stakingEpochDuration > _stakeWithdrawDisallowPeriod); require(_stakeWithdrawDisallowPeriod != 0); require(_getCurrentBlockNumber() == 0 || msg.sender == _admin()); require(!isInitialized()); // initialization can only be done once validatorSetContract = IValidatorSetAuRa(_validatorSetContract); governanceContract = IGovernance(_governanceContract); uint256 unremovablePoolId = validatorSetContract.unremovableValidator(); for (uint256 i = 0; i < _initialIds.length; i++) { require(_initialIds[i] != 0); _addPoolActive(_initialIds[i], false); if (_initialIds[i] != unremovablePoolId) { _addPoolToBeRemoved(_initialIds[i]); } } delegatorMinStake = _delegatorMinStake; candidateMinStake = _candidateMinStake; stakingEpochDuration = _stakingEpochDuration; stakingEpochStartBlock = _stakingEpochStartBlock; stakeWithdrawDisallowPeriod = _stakeWithdrawDisallowPeriod; lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Makes initial validator stakes. Can only be called by the owner /// before the network starts (after `initialize` is called but before `stakingEpochStartBlock`), /// or after the network starts from genesis (`stakingEpochStartBlock` == 0). /// Cannot be called more than once and cannot be called when starting from genesis. /// Requires `StakingAuRa` contract balance to be equal to the `_totalAmount`. /// @param _totalAmount The initial validator total stake amount (for all initial validators). function initialValidatorStake(uint256 _totalAmount) external onlyOwner { uint256 currentBlock = _getCurrentBlockNumber(); require(stakingEpoch == 0); require(currentBlock < stakingEpochStartBlock || stakingEpochStartBlock == 0); require(_thisBalance() == _totalAmount); require(_totalAmount % _pools.length == 0); uint256 stakingAmount = _totalAmount.div(_pools.length); uint256 stakingEpochStartBlock_ = stakingEpochStartBlock; // Temporarily set `stakingEpochStartBlock` to the current block number // to avoid revert in the `_stake` function stakingEpochStartBlock = currentBlock; for (uint256 i = 0; i < _pools.length; i++) { uint256 poolId = _pools[i]; address stakingAddress = validatorSetContract.stakingAddressById(poolId); require(stakeAmount[poolId][address(0)] == 0); _stake(stakingAddress, stakingAddress, stakingAmount); _stakeInitial[poolId] = stakingAmount; } // Restore `stakingEpochStartBlock` value stakingEpochStartBlock = stakingEpochStartBlock_; } /// @dev Removes a specified pool from the `pools` array (a list of active pools which can be retrieved by the /// `getPools` getter). Called by the `ValidatorSetAuRa._removeMaliciousValidator` internal function /// when a pool must be removed by the algorithm. /// @param _poolId The id of the pool to be removed. function removePool(uint256 _poolId) external onlyValidatorSetContract { _removePool(_poolId); } /// @dev Removes pools which are in the `_poolsToBeRemoved` internal array from the `pools` array. /// Called by the `ValidatorSetAuRa.newValidatorSet` function when pools must be removed by the algorithm. function removePools() external onlyValidatorSetContract { uint256[] memory poolsToRemove = _poolsToBeRemoved; for (uint256 i = 0; i < poolsToRemove.length; i++) { _removePool(poolsToRemove[i]); } } /// @dev Removes the candidate's or validator's pool from the `pools` array (a list of active pools which /// can be retrieved by the `getPools` getter). When a candidate or validator wants to remove their pool, /// they should call this function from their staking address. A validator cannot remove their pool while /// they are an `unremovable validator`. function removeMyPool() external gasPriceIsValid onlyInitialized { uint256 poolId = validatorSetContract.idByStakingAddress(msg.sender); require(poolId != 0); // initial validator cannot remove their pool during the initial staking epoch require(stakingEpoch > 0 || !validatorSetContract.isValidatorById(poolId)); require(poolId != validatorSetContract.unremovableValidator()); _removePool(poolId); } /// @dev Sets the number of the first block in the upcoming staking epoch. /// Called by the `ValidatorSetAuRa.newValidatorSet` function at the last block of a staking epoch. /// @param _blockNumber The number of the very first block in the upcoming staking epoch. function setStakingEpochStartBlock(uint256 _blockNumber) external onlyValidatorSetContract { stakingEpochStartBlock = _blockNumber; } /// @dev Moves staking tokens/coins from one pool to another. A staker calls this function when they want /// to move their tokens/coins from one pool to another without withdrawing their tokens/coins. /// @param _fromPoolStakingAddress The staking address of the source pool. /// @param _toPoolStakingAddress The staking address of the target pool. /// @param _amount The amount of staking tokens/coins to be moved. The amount cannot exceed the value returned /// by the `maxWithdrawAllowed` getter. function moveStake( address _fromPoolStakingAddress, address _toPoolStakingAddress, uint256 _amount ) external { require(_fromPoolStakingAddress != _toPoolStakingAddress); uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress); uint256 toPoolId = validatorSetContract.idByStakingAddress(_toPoolStakingAddress); address staker = msg.sender; _withdraw(_fromPoolStakingAddress, staker, _amount); _stake(_toPoolStakingAddress, staker, _amount); emit MovedStake( _fromPoolStakingAddress, _toPoolStakingAddress, staker, stakingEpoch, _amount, fromPoolId, toPoolId ); } /// @dev Moves the specified amount of staking tokens/coins from the staker's address to the staking address of /// the specified pool. Actually, the amount is stored in a balance of this StakingAuRa contract. /// A staker calls this function when they want to make a stake into a pool. /// @param _toPoolStakingAddress The staking address of the pool where the tokens should be staked. /// @param _amount The amount of tokens to be staked. Ignored when staking in native coins /// because `msg.value` is used instead. function stake(address _toPoolStakingAddress, uint256 _amount) external payable { _stake(_toPoolStakingAddress, _amount); } /// @dev Moves the specified amount of staking tokens/coins from the staking address of /// the specified pool to the staker's address. A staker calls this function when they want to withdraw /// their tokens/coins. /// @param _fromPoolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn. /// @param _amount The amount of tokens/coins to be withdrawn. The amount cannot exceed the value returned /// by the `maxWithdrawAllowed` getter. function withdraw(address _fromPoolStakingAddress, uint256 _amount) external { address payable staker = msg.sender; uint256 fromPoolId = validatorSetContract.idByStakingAddress(_fromPoolStakingAddress); _withdraw(_fromPoolStakingAddress, staker, _amount); _sendWithdrawnStakeAmount(staker, _amount); emit WithdrewStake(_fromPoolStakingAddress, staker, stakingEpoch, _amount, fromPoolId); } /// @dev Orders tokens/coins withdrawal from the staking address of the specified pool to the /// staker's address. The requested tokens/coins can be claimed after the current staking epoch is complete using /// the `claimOrderedWithdraw` function. /// @param _poolStakingAddress The staking address of the pool from which the amount will be withdrawn. /// @param _amount The amount to be withdrawn. A positive value means the staker wants to either set or /// increase their withdrawal amount. A negative value means the staker wants to decrease a /// withdrawal amount that was previously set. The amount cannot exceed the value returned by the /// `maxWithdrawOrderAllowed` getter. function orderWithdraw(address _poolStakingAddress, int256 _amount) external gasPriceIsValid onlyInitialized { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); require(_poolStakingAddress != address(0)); require(_amount != 0); require(poolId != 0); address staker = msg.sender; address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0); require(_isWithdrawAllowed(poolId, delegatorOrZero != address(0))); uint256 newOrderedAmount = orderedWithdrawAmount[poolId][delegatorOrZero]; uint256 newOrderedAmountTotal = orderedWithdrawAmountTotal[poolId]; uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero]; uint256 newStakeAmountTotal = stakeAmountTotal[poolId]; if (_amount > 0) { uint256 amount = uint256(_amount); // How much can `staker` order for withdrawal from `_poolStakingAddress` at the moment? require(amount <= maxWithdrawOrderAllowed(_poolStakingAddress, staker)); newOrderedAmount = newOrderedAmount.add(amount); newOrderedAmountTotal = newOrderedAmountTotal.add(amount); newStakeAmount = newStakeAmount.sub(amount); newStakeAmountTotal = newStakeAmountTotal.sub(amount); orderWithdrawEpoch[poolId][delegatorOrZero] = stakingEpoch; } else { uint256 amount = uint256(-_amount); newOrderedAmount = newOrderedAmount.sub(amount); newOrderedAmountTotal = newOrderedAmountTotal.sub(amount); newStakeAmount = newStakeAmount.add(amount); newStakeAmountTotal = newStakeAmountTotal.add(amount); } orderedWithdrawAmount[poolId][delegatorOrZero] = newOrderedAmount; orderedWithdrawAmountTotal[poolId] = newOrderedAmountTotal; stakeAmount[poolId][delegatorOrZero] = newStakeAmount; stakeAmountTotal[poolId] = newStakeAmountTotal; if (staker == _poolStakingAddress) { // Initial validator cannot withdraw their initial stake require(newStakeAmount >= _stakeInitial[poolId]); // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and `candidateMinStake` require(newStakeAmount == 0 || newStakeAmount >= candidateMinStake); uint256 unremovablePoolId = validatorSetContract.unremovableValidator(); if (_amount > 0) { // if the validator orders the `_amount` for withdrawal if (newStakeAmount == 0 && poolId != unremovablePoolId) { // If the removable validator orders their entire stake, // mark their pool as `to be removed` _addPoolToBeRemoved(poolId); } } else { // If the validator wants to reduce withdrawal value, // add their pool as `active` if it hasn't already done _addPoolActive(poolId, poolId != unremovablePoolId); } } else { // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and `delegatorMinStake` require(newStakeAmount == 0 || newStakeAmount >= delegatorMinStake); if (_amount > 0) { // if the delegator orders the `_amount` for withdrawal if (newStakeAmount == 0) { // If the delegator orders their entire stake, // remove the delegator from delegator list of the pool _removePoolDelegator(poolId, staker); } } else { // If the delegator wants to reduce withdrawal value, // add them to delegator list of the pool if it hasn't already done _addPoolDelegator(poolId, staker); } // Remember stake movement to use it later in the `claimReward` function _snapshotDelegatorStake(poolId, staker); } _setLikelihood(poolId); emit OrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, _amount, poolId); } /// @dev Withdraws the staking tokens/coins from the specified pool ordered during the previous staking epochs with /// the `orderWithdraw` function. The ordered amount can be retrieved by the `orderedWithdrawAmount` getter. /// @param _poolStakingAddress The staking address of the pool from which the ordered tokens/coins are withdrawn. function claimOrderedWithdraw(address _poolStakingAddress) external { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); require(poolId != 0); address payable staker = msg.sender; address delegatorOrZero = (staker != _poolStakingAddress) ? staker : address(0); require(stakingEpoch > orderWithdrawEpoch[poolId][delegatorOrZero]); require(!_isPoolBanned(poolId, delegatorOrZero != address(0))); uint256 claimAmount = orderedWithdrawAmount[poolId][delegatorOrZero]; require(claimAmount != 0); orderedWithdrawAmount[poolId][delegatorOrZero] = 0; orderedWithdrawAmountTotal[poolId] = orderedWithdrawAmountTotal[poolId].sub(claimAmount); if (stakeAmount[poolId][delegatorOrZero] == 0) { _withdrawCheckPool(poolId, _poolStakingAddress, staker); } _sendWithdrawnStakeAmount(staker, claimAmount); emit ClaimedOrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, claimAmount, poolId); } /// @dev Sets (updates) the limit of the minimum candidate stake (CANDIDATE_MIN_STAKE). /// Can only be called by the `owner`. /// @param _minStake The value of a new limit in Wei. function setCandidateMinStake(uint256 _minStake) external onlyOwner onlyInitialized { candidateMinStake = _minStake; } /// @dev Sets (updates) the limit of the minimum delegator stake (DELEGATOR_MIN_STAKE). /// Can only be called by the `owner`. /// @param _minStake The value of a new limit in Wei. function setDelegatorMinStake(uint256 _minStake) external onlyOwner onlyInitialized { delegatorMinStake = _minStake; } // =============================================== Getters ======================================================== /// @dev Returns an array of the current active pools (the pool ids of candidates and validators). /// The size of the array cannot exceed MAX_CANDIDATES. A pool can be added to this array with the `_addPoolActive` /// internal function which is called by the `stake` or `orderWithdraw` function. A pool is considered active /// if its address has at least the minimum stake and this stake is not ordered to be withdrawn. function getPools() external view returns(uint256[] memory) { return _pools; } /// @dev Returns an array of the current inactive pools (the pool ids of former candidates). /// A pool can be added to this array with the `_addPoolInactive` internal function which is called /// by `_removePool`. A pool is considered inactive if it is banned for some reason, if its address /// has zero stake, or if its entire stake is ordered to be withdrawn. function getPoolsInactive() external view returns(uint256[] memory) { return _poolsInactive; } /// @dev Returns the array of stake amounts for each corresponding /// address in the `poolsToBeElected` array (see the `getPoolsToBeElected` getter) and a sum of these amounts. /// Used by the `ValidatorSetAuRa.newValidatorSet` function when randomly selecting new validators at the last /// block of a staking epoch. An array value is updated every time any staked amount is changed in this pool /// (see the `_setLikelihood` internal function). /// @return `uint256[] likelihoods` - The array of the coefficients. The array length is always equal to the length /// of the `poolsToBeElected` array. /// `uint256 sum` - The total sum of the amounts. function getPoolsLikelihood() external view returns(uint256[] memory likelihoods, uint256 sum) { return (_poolsLikelihood, _poolsLikelihoodSum); } /// @dev Returns the list of pools (their ids) which will participate in a new validator set /// selection process in the `ValidatorSetAuRa.newValidatorSet` function. This is an array of pools /// which will be considered as candidates when forming a new validator set (at the last block of a staking epoch). /// This array is kept updated by the `_addPoolToBeElected` and `_deletePoolToBeElected` internal functions. function getPoolsToBeElected() external view returns(uint256[] memory) { return _poolsToBeElected; } /// @dev Returns the list of pools (their ids) which will be removed by the /// `ValidatorSetAuRa.newValidatorSet` function from the active `pools` array (at the last block /// of a staking epoch). This array is kept updated by the `_addPoolToBeRemoved` /// and `_deletePoolToBeRemoved` internal functions. A pool is added to this array when the pool's /// address withdraws (or orders) all of its own staking tokens from the pool, inactivating the pool. function getPoolsToBeRemoved() external view returns(uint256[] memory) { return _poolsToBeRemoved; } /// @dev Returns the list of pool ids into which the specified delegator have ever staked. /// @param _delegator The delegator address. /// @param _offset The index in the array at which the reading should start. Ignored if the `_length` is 0. /// @param _length The max number of items to return. function getDelegatorPools( address _delegator, uint256 _offset, uint256 _length ) external view returns(uint256[] memory result) { uint256[] storage delegatorPools = _delegatorPools[_delegator]; if (_length == 0) { return delegatorPools; } uint256 maxLength = delegatorPools.length.sub(_offset); result = new uint256[](_length > maxLength ? maxLength : _length); for (uint256 i = 0; i < result.length; i++) { result[i] = delegatorPools[_offset + i]; } } /// @dev Returns the length of the list of pools into which the specified delegator have ever staked. /// @param _delegator The delegator address. function getDelegatorPoolsLength(address _delegator) external view returns(uint256) { return _delegatorPools[_delegator].length; } /// @dev Determines whether staking/withdrawal operations are allowed at the moment. /// Used by all staking/withdrawal functions. function areStakeAndWithdrawAllowed() public view returns(bool) { uint256 currentBlock = _getCurrentBlockNumber(); if (currentBlock < stakingEpochStartBlock) return false; uint256 allowedDuration = stakingEpochDuration - stakeWithdrawDisallowPeriod; if (stakingEpochStartBlock == 0) allowedDuration++; return currentBlock - stakingEpochStartBlock < allowedDuration; } /// @dev Returns a boolean flag indicating if the `initialize` function has been called. function isInitialized() public view returns(bool) { return validatorSetContract != IValidatorSetAuRa(0); } /// @dev Returns a flag indicating whether a specified id is in the `pools` array. /// See the `getPools` getter. /// @param _poolId An id of the pool. function isPoolActive(uint256 _poolId) public view returns(bool) { uint256 index = poolIndex[_poolId]; return index < _pools.length && _pools[index] == _poolId; } /// @dev Returns the maximum amount which can be withdrawn from the specified pool by the specified staker /// at the moment. Used by the `withdraw` and `moveStake` functions. /// @param _poolStakingAddress The pool staking address from which the withdrawal will be made. /// @param _staker The staker address that is going to withdraw. function maxWithdrawAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0); bool isDelegator = _poolStakingAddress != _staker; if (!_isWithdrawAllowed(poolId, isDelegator)) { return 0; } uint256 canWithdraw = stakeAmount[poolId][delegatorOrZero]; if (!isDelegator) { // Initial validator cannot withdraw their initial stake canWithdraw = canWithdraw.sub(_stakeInitial[poolId]); } if (!validatorSetContract.isValidatorOrPending(poolId)) { // The pool is not a validator and is not going to become one, // so the staker can only withdraw staked amount minus already // ordered amount return canWithdraw; } // The pool is a validator (active or pending), so the staker can only // withdraw staked amount minus already ordered amount but // no more than the amount staked during the current staking epoch uint256 stakedDuringEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero); if (canWithdraw > stakedDuringEpoch) { canWithdraw = stakedDuringEpoch; } return canWithdraw; } /// @dev Returns the maximum amount which can be ordered to be withdrawn from the specified pool by the /// specified staker at the moment. Used by the `orderWithdraw` function. /// @param _poolStakingAddress The pool staking address from which the withdrawal will be ordered. /// @param _staker The staker address that is going to order the withdrawal. function maxWithdrawOrderAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); bool isDelegator = _poolStakingAddress != _staker; address delegatorOrZero = isDelegator ? _staker : address(0); if (!_isWithdrawAllowed(poolId, isDelegator)) { return 0; } if (!validatorSetContract.isValidatorOrPending(poolId)) { // If the pool is a candidate (not an active validator and not pending one), // no one can order withdrawal from the `_poolStakingAddress`, but // anyone can withdraw immediately (see the `maxWithdrawAllowed` getter) return 0; } // If the pool is an active or pending validator, the staker can order withdrawal // up to their total staking amount minus an already ordered amount // minus an amount staked during the current staking epoch uint256 canOrder = stakeAmount[poolId][delegatorOrZero]; if (!isDelegator) { // Initial validator cannot withdraw their initial stake canOrder = canOrder.sub(_stakeInitial[poolId]); } return canOrder.sub(stakeAmountByCurrentEpoch(poolId, delegatorOrZero)); } /// @dev Returns an array of the current active delegators of the specified pool. /// A delegator is considered active if they have staked into the specified /// pool and their stake is not ordered to be withdrawn. /// @param _poolId The pool id. function poolDelegators(uint256 _poolId) public view returns(address[] memory) { return _poolDelegators[_poolId]; } /// @dev Returns an array of the current inactive delegators of the specified pool. /// A delegator is considered inactive if their entire stake is ordered to be withdrawn /// but not yet claimed. /// @param _poolId The pool id. function poolDelegatorsInactive(uint256 _poolId) public view returns(address[] memory) { return _poolDelegatorsInactive[_poolId]; } /// @dev Returns the amount of staking tokens/coins staked into the specified pool by the specified staker /// during the current staking epoch (see the `stakingEpoch` getter). /// Used by the `stake`, `withdraw`, and `orderWithdraw` functions. /// @param _poolId The pool id. /// @param _delegatorOrZero The delegator's address (or zero address if the staker is the pool itself). function stakeAmountByCurrentEpoch(uint256 _poolId, address _delegatorOrZero) public view returns(uint256) { return _stakeAmountByEpoch[_poolId][_delegatorOrZero][stakingEpoch]; } /// @dev Returns the number of the last block of the current staking epoch. function stakingEpochEndBlock() public view returns(uint256) { uint256 startBlock = stakingEpochStartBlock; return startBlock + stakingEpochDuration - (startBlock == 0 ? 0 : 1); } // ============================================== Internal ======================================================== /// @dev Adds the specified pool id to the array of active pools returned by /// the `getPools` getter. Used by the `stake`, `addPool`, and `orderWithdraw` functions. /// @param _poolId The pool id added to the array of active pools. /// @param _toBeElected The boolean flag which defines whether the specified id should be /// added simultaneously to the `poolsToBeElected` array. See the `getPoolsToBeElected` getter. function _addPoolActive(uint256 _poolId, bool _toBeElected) internal { if (!isPoolActive(_poolId)) { poolIndex[_poolId] = _pools.length; _pools.push(_poolId); require(_pools.length <= _getMaxCandidates()); } _removePoolInactive(_poolId); if (_toBeElected) { _addPoolToBeElected(_poolId); } } /// @dev Adds the specified pool id to the array of inactive pools returned by /// the `getPoolsInactive` getter. Used by the `_removePool` internal function. /// @param _poolId The pool id added to the array of inactive pools. function _addPoolInactive(uint256 _poolId) internal { uint256 index = poolInactiveIndex[_poolId]; uint256 length = _poolsInactive.length; if (index >= length || _poolsInactive[index] != _poolId) { poolInactiveIndex[_poolId] = length; _poolsInactive.push(_poolId); } } /// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeElected` /// getter. Used by the `_addPoolActive` internal function. See the `getPoolsToBeElected` getter. /// @param _poolId The pool id added to the `poolsToBeElected` array. function _addPoolToBeElected(uint256 _poolId) internal { uint256 index = poolToBeElectedIndex[_poolId]; uint256 length = _poolsToBeElected.length; if (index >= length || _poolsToBeElected[index] != _poolId) { poolToBeElectedIndex[_poolId] = length; _poolsToBeElected.push(_poolId); _poolsLikelihood.push(0); // assumes the likelihood is set with `_setLikelihood` function hereinafter } _deletePoolToBeRemoved(_poolId); } /// @dev Adds the specified pool id to the array of pools returned by the `getPoolsToBeRemoved` /// getter. Used by withdrawal functions. See the `getPoolsToBeRemoved` getter. /// @param _poolId The pool id added to the `poolsToBeRemoved` array. function _addPoolToBeRemoved(uint256 _poolId) internal { uint256 index = poolToBeRemovedIndex[_poolId]; uint256 length = _poolsToBeRemoved.length; if (index >= length || _poolsToBeRemoved[index] != _poolId) { poolToBeRemovedIndex[_poolId] = length; _poolsToBeRemoved.push(_poolId); } _deletePoolToBeElected(_poolId); } /// @dev Deletes the specified pool id from the array of pools returned by the /// `getPoolsToBeElected` getter. Used by the `_addPoolToBeRemoved` and `_removePool` internal functions. /// See the `getPoolsToBeElected` getter. /// @param _poolId The pool id deleted from the `poolsToBeElected` array. function _deletePoolToBeElected(uint256 _poolId) internal { if (_poolsToBeElected.length != _poolsLikelihood.length) return; uint256 indexToDelete = poolToBeElectedIndex[_poolId]; if (_poolsToBeElected.length > indexToDelete && _poolsToBeElected[indexToDelete] == _poolId) { if (_poolsLikelihoodSum >= _poolsLikelihood[indexToDelete]) { _poolsLikelihoodSum -= _poolsLikelihood[indexToDelete]; } else { _poolsLikelihoodSum = 0; } uint256 lastPoolIndex = _poolsToBeElected.length - 1; uint256 lastPool = _poolsToBeElected[lastPoolIndex]; _poolsToBeElected[indexToDelete] = lastPool; _poolsLikelihood[indexToDelete] = _poolsLikelihood[lastPoolIndex]; poolToBeElectedIndex[lastPool] = indexToDelete; poolToBeElectedIndex[_poolId] = 0; _poolsToBeElected.length--; _poolsLikelihood.length--; } } /// @dev Deletes the specified pool id from the array of pools returned by the /// `getPoolsToBeRemoved` getter. Used by the `_addPoolToBeElected` and `_removePool` internal functions. /// See the `getPoolsToBeRemoved` getter. /// @param _poolId The pool id deleted from the `poolsToBeRemoved` array. function _deletePoolToBeRemoved(uint256 _poolId) internal { uint256 indexToDelete = poolToBeRemovedIndex[_poolId]; if (_poolsToBeRemoved.length > indexToDelete && _poolsToBeRemoved[indexToDelete] == _poolId) { uint256 lastPool = _poolsToBeRemoved[_poolsToBeRemoved.length - 1]; _poolsToBeRemoved[indexToDelete] = lastPool; poolToBeRemovedIndex[lastPool] = indexToDelete; poolToBeRemovedIndex[_poolId] = 0; _poolsToBeRemoved.length--; } } /// @dev Removes the specified pool id from the array of active pools returned by /// the `getPools` getter. Used by the `removePool`, `removeMyPool`, and withdrawal functions. /// @param _poolId The pool id removed from the array of active pools. function _removePool(uint256 _poolId) internal { uint256 indexToRemove = poolIndex[_poolId]; if (_pools.length > indexToRemove && _pools[indexToRemove] == _poolId) { uint256 lastPool = _pools[_pools.length - 1]; _pools[indexToRemove] = lastPool; poolIndex[lastPool] = indexToRemove; poolIndex[_poolId] = 0; _pools.length--; } if (_isPoolEmpty(_poolId)) { _removePoolInactive(_poolId); } else { _addPoolInactive(_poolId); } _deletePoolToBeElected(_poolId); _deletePoolToBeRemoved(_poolId); lastChangeBlock = _getCurrentBlockNumber(); } /// @dev Removes the specified pool id from the array of inactive pools returned by /// the `getPoolsInactive` getter. Used by withdrawal functions, by the `_addPoolActive` and /// `_removePool` internal functions. /// @param _poolId The pool id removed from the array of inactive pools. function _removePoolInactive(uint256 _poolId) internal { uint256 indexToRemove = poolInactiveIndex[_poolId]; if (_poolsInactive.length > indexToRemove && _poolsInactive[indexToRemove] == _poolId) { uint256 lastPool = _poolsInactive[_poolsInactive.length - 1]; _poolsInactive[indexToRemove] = lastPool; poolInactiveIndex[lastPool] = indexToRemove; poolInactiveIndex[_poolId] = 0; _poolsInactive.length--; } } /// @dev Used by `addPool` and `onTokenTransfer` functions. See their descriptions and code. /// @param _amount The amount of tokens to be staked. Ignored when staking in native coins /// because `msg.value` is used in that case. /// @param _stakingAddress The staking address of the new candidate. /// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address /// (msg.sender). This address cannot be equal to `_stakingAddress`. /// @param _byOnTokenTransfer A boolean flag defining whether this internal function is called /// by the `onTokenTransfer` function. /// @param _name A name of the pool as UTF-8 string (max length is 256 bytes). /// @param _description A short description of the pool as UTF-8 string (max length is 1024 bytes). function _addPool( uint256 _amount, address _stakingAddress, address _miningAddress, bool _byOnTokenTransfer, string memory _name, string memory _description ) internal returns(uint256) { uint256 poolId = validatorSetContract.addPool(_miningAddress, _stakingAddress, _name, _description); if (_byOnTokenTransfer) { _stake(_stakingAddress, _stakingAddress, _amount); } else { _stake(_stakingAddress, _amount); } emit AddedPool(_stakingAddress, _miningAddress, poolId); return poolId; } /// @dev Adds the specified address to the array of the current active delegators of the specified pool. /// Used by the `stake` and `orderWithdraw` functions. See the `poolDelegators` getter. /// @param _poolId The pool id. /// @param _delegator The delegator's address. function _addPoolDelegator(uint256 _poolId, address _delegator) internal { address[] storage delegators = _poolDelegators[_poolId]; uint256 index = poolDelegatorIndex[_poolId][_delegator]; uint256 length = delegators.length; if (index >= length || delegators[index] != _delegator) { poolDelegatorIndex[_poolId][_delegator] = length; delegators.push(_delegator); } _removePoolDelegatorInactive(_poolId, _delegator); } /// @dev Adds the specified address to the array of the current inactive delegators of the specified pool. /// Used by the `_removePoolDelegator` internal function. /// @param _poolId The pool id. /// @param _delegator The delegator's address. function _addPoolDelegatorInactive(uint256 _poolId, address _delegator) internal { address[] storage delegators = _poolDelegatorsInactive[_poolId]; uint256 index = poolDelegatorInactiveIndex[_poolId][_delegator]; uint256 length = delegators.length; if (index >= length || delegators[index] != _delegator) { poolDelegatorInactiveIndex[_poolId][_delegator] = length; delegators.push(_delegator); } } /// @dev Removes the specified address from the array of the current active delegators of the specified pool. /// Used by the withdrawal functions. See the `poolDelegators` getter. /// @param _poolId The pool id. /// @param _delegator The delegator's address. function _removePoolDelegator(uint256 _poolId, address _delegator) internal { address[] storage delegators = _poolDelegators[_poolId]; uint256 indexToRemove = poolDelegatorIndex[_poolId][_delegator]; if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) { address lastDelegator = delegators[delegators.length - 1]; delegators[indexToRemove] = lastDelegator; poolDelegatorIndex[_poolId][lastDelegator] = indexToRemove; poolDelegatorIndex[_poolId][_delegator] = 0; delegators.length--; } if (orderedWithdrawAmount[_poolId][_delegator] != 0) { _addPoolDelegatorInactive(_poolId, _delegator); } else { _removePoolDelegatorInactive(_poolId, _delegator); } } /// @dev Removes the specified address from the array of the inactive delegators of the specified pool. /// Used by the `_addPoolDelegator` and `_removePoolDelegator` internal functions. /// @param _poolId The pool id. /// @param _delegator The delegator's address. function _removePoolDelegatorInactive(uint256 _poolId, address _delegator) internal { address[] storage delegators = _poolDelegatorsInactive[_poolId]; uint256 indexToRemove = poolDelegatorInactiveIndex[_poolId][_delegator]; if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) { address lastDelegator = delegators[delegators.length - 1]; delegators[indexToRemove] = lastDelegator; poolDelegatorInactiveIndex[_poolId][lastDelegator] = indexToRemove; poolDelegatorInactiveIndex[_poolId][_delegator] = 0; delegators.length--; } } function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal; /// @dev Calculates (updates) the probability of being selected as a validator for the specified pool /// and updates the total sum of probability coefficients. Actually, the probability is equal to the /// amount totally staked into the pool. See the `getPoolsLikelihood` getter. /// Used by the staking and withdrawal functions. /// @param _poolId An id of the pool for which the probability coefficient must be updated. function _setLikelihood(uint256 _poolId) internal { lastChangeBlock = _getCurrentBlockNumber(); (bool isToBeElected, uint256 index) = _isPoolToBeElected(_poolId); if (!isToBeElected) return; uint256 oldValue = _poolsLikelihood[index]; uint256 newValue = stakeAmountTotal[_poolId]; _poolsLikelihood[index] = newValue; if (newValue >= oldValue) { _poolsLikelihoodSum = _poolsLikelihoodSum.add(newValue - oldValue); } else { _poolsLikelihoodSum = _poolsLikelihoodSum.sub(oldValue - newValue); } } /// @dev Makes a snapshot of the amount currently staked by the specified delegator /// into the specified pool. Used by the `orderWithdraw`, `_stake`, and `_withdraw` functions. /// @param _poolId An id of the pool. /// @param _delegator The address of the delegator. function _snapshotDelegatorStake(uint256 _poolId, address _delegator) internal { uint256 nextStakingEpoch = stakingEpoch + 1; uint256 newAmount = stakeAmount[_poolId][_delegator]; delegatorStakeSnapshot[_poolId][_delegator][nextStakingEpoch] = (newAmount != 0) ? newAmount : uint256(-1); if (stakeFirstEpoch[_poolId][_delegator] == 0) { stakeFirstEpoch[_poolId][_delegator] = nextStakingEpoch; } stakeLastEpoch[_poolId][_delegator] = (newAmount == 0) ? nextStakingEpoch : 0; } function _stake(address _toPoolStakingAddress, uint256 _amount) internal; /// @dev The internal function used by the `_stake`, `moveStake`, `initialValidatorStake`, `_addPool` functions. /// See the `stake` public function for more details. /// @param _poolStakingAddress The staking address of the pool where the tokens/coins should be staked. /// @param _staker The staker's address. /// @param _amount The amount of tokens/coins to be staked. function _stake( address _poolStakingAddress, address _staker, uint256 _amount ) internal gasPriceIsValid onlyInitialized { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); require(_poolStakingAddress != address(0)); require(poolId != 0); require(_amount != 0); require(!validatorSetContract.isValidatorIdBanned(poolId)); require(areStakeAndWithdrawAllowed()); address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0); uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].add(_amount); if (_staker == _poolStakingAddress) { // The staked amount must be at least CANDIDATE_MIN_STAKE require(newStakeAmount >= candidateMinStake); } else { // The staked amount must be at least DELEGATOR_MIN_STAKE require(newStakeAmount >= delegatorMinStake); // The delegator cannot stake into the pool of the candidate which hasn't self-staked. // Also, that candidate shouldn't want to withdraw all their funds. require(stakeAmount[poolId][address(0)] != 0); } stakeAmount[poolId][delegatorOrZero] = newStakeAmount; _stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] = stakeAmountByCurrentEpoch(poolId, delegatorOrZero).add(_amount); stakeAmountTotal[poolId] = stakeAmountTotal[poolId].add(_amount); if (_staker == _poolStakingAddress) { // `staker` places a stake for himself and becomes a candidate // Add `_poolStakingAddress` to the array of pools _addPoolActive(poolId, poolId != validatorSetContract.unremovableValidator()); } else { // Add `_staker` to the array of pool's delegators _addPoolDelegator(poolId, _staker); // Save/update amount value staked by the delegator _snapshotDelegatorStake(poolId, _staker); // Remember that the delegator (`_staker`) has ever staked into `_poolStakingAddress` uint256[] storage delegatorPools = _delegatorPools[_staker]; uint256 delegatorPoolsLength = delegatorPools.length; uint256 index = _delegatorPoolsIndexes[_staker][poolId]; bool neverStakedBefore = index >= delegatorPoolsLength || delegatorPools[index] != poolId; if (neverStakedBefore) { _delegatorPoolsIndexes[_staker][poolId] = delegatorPoolsLength; delegatorPools.push(poolId); } if (delegatorPoolsLength == 0) { // If this is the first time the delegator stakes, // make sure the delegator has never been a mining address require(validatorSetContract.hasEverBeenMiningAddress(_staker) == 0); } } _setLikelihood(poolId); emit PlacedStake(_poolStakingAddress, _staker, stakingEpoch, _amount, poolId); } /// @dev The internal function used by the `withdraw` and `moveStake` functions. /// See the `withdraw` public function for more details. /// @param _poolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn. /// @param _staker The staker's address. /// @param _amount The amount of the tokens/coins to be withdrawn. function _withdraw( address _poolStakingAddress, address _staker, uint256 _amount ) internal gasPriceIsValid onlyInitialized { uint256 poolId = validatorSetContract.idByStakingAddress(_poolStakingAddress); require(_poolStakingAddress != address(0)); require(_amount != 0); require(poolId != 0); // How much can `_staker` withdraw from `_poolStakingAddress` at the moment? require(_amount <= maxWithdrawAllowed(_poolStakingAddress, _staker)); address delegatorOrZero = (_staker != _poolStakingAddress) ? _staker : address(0); uint256 newStakeAmount = stakeAmount[poolId][delegatorOrZero].sub(_amount); // The amount to be withdrawn must be the whole staked amount or // must not exceed the diff between the entire amount and min allowed stake uint256 minAllowedStake; if (_poolStakingAddress == _staker) { // initial validator cannot withdraw their initial stake require(newStakeAmount >= _stakeInitial[poolId]); minAllowedStake = candidateMinStake; } else { minAllowedStake = delegatorMinStake; } require(newStakeAmount == 0 || newStakeAmount >= minAllowedStake); stakeAmount[poolId][delegatorOrZero] = newStakeAmount; uint256 amountByEpoch = stakeAmountByCurrentEpoch(poolId, delegatorOrZero); _stakeAmountByEpoch[poolId][delegatorOrZero][stakingEpoch] = amountByEpoch >= _amount ? amountByEpoch - _amount : 0; stakeAmountTotal[poolId] = stakeAmountTotal[poolId].sub(_amount); if (newStakeAmount == 0) { _withdrawCheckPool(poolId, _poolStakingAddress, _staker); } if (_staker != _poolStakingAddress) { _snapshotDelegatorStake(poolId, _staker); } _setLikelihood(poolId); } /// @dev The internal function used by the `_withdraw` and `claimOrderedWithdraw` functions. /// Contains a common logic for these functions. /// @param _poolId The id of the pool from which the tokens/coins are withdrawn. /// @param _poolStakingAddress The staking address of the pool from which the tokens/coins are withdrawn. /// @param _staker The staker's address. function _withdrawCheckPool(uint256 _poolId, address _poolStakingAddress, address _staker) internal { if (_staker == _poolStakingAddress) { uint256 unremovablePoolId = validatorSetContract.unremovableValidator(); if (_poolId != unremovablePoolId) { if (validatorSetContract.isValidatorById(_poolId)) { _addPoolToBeRemoved(_poolId); } else { _removePool(_poolId); } } } else { _removePoolDelegator(_poolId, _staker); if (_isPoolEmpty(_poolId)) { _removePoolInactive(_poolId); } } } /// @dev Returns the current block number. Needed mostly for unit tests. function _getCurrentBlockNumber() internal view returns(uint256) { return block.number; } /// @dev The internal function used by the `claimReward` function and `getRewardAmount` getter. /// Finds the stake amount made by a specified delegator into a specified pool before a specified /// staking epoch. function _getDelegatorStake( uint256 _epoch, uint256 _firstEpoch, uint256 _prevDelegatorStake, uint256 _poolId, address _delegator ) internal view returns(uint256 delegatorStake) { while (true) { delegatorStake = delegatorStakeSnapshot[_poolId][_delegator][_epoch]; if (delegatorStake != 0) { delegatorStake = (delegatorStake == uint256(-1)) ? 0 : delegatorStake; break; } else if (_epoch == _firstEpoch) { delegatorStake = _prevDelegatorStake; break; } _epoch--; } } /// @dev Returns the max number of candidates (including validators). See the MAX_CANDIDATES constant. /// Needed mostly for unit tests. function _getMaxCandidates() internal pure returns(uint256) { return MAX_CANDIDATES; } /// @dev Returns a boolean flag indicating whether the specified pool is fully empty /// (all stakes are withdrawn including ordered withdrawals). /// @param _poolId An id of the pool. function _isPoolEmpty(uint256 _poolId) internal view returns(bool) { return stakeAmountTotal[_poolId] == 0 && orderedWithdrawAmountTotal[_poolId] == 0; } /// @dev Determines if the specified pool is in the `poolsToBeElected` array. See the `getPoolsToBeElected` getter. /// Used by the `_setLikelihood` internal function. /// @param _poolId An id of the pool. /// @return `bool toBeElected` - The boolean flag indicating whether the `_poolId` is in the /// `poolsToBeElected` array. /// `uint256 index` - The position of the item in the `poolsToBeElected` array if `toBeElected` is `true`. function _isPoolToBeElected(uint256 _poolId) internal view returns(bool toBeElected, uint256 index) { index = poolToBeElectedIndex[_poolId]; if (_poolsToBeElected.length > index && _poolsToBeElected[index] == _poolId) { return (true, index); } return (false, 0); } /// @dev Returns `true` if the specified pool is banned or the pool is under a governance ballot. /// Used by the `_isWithdrawAllowed` internal function and the `claimOrderedWithdraw` function. /// @param _poolId An id of the validator's pool. /// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator. function _isPoolBanned(uint256 _poolId, bool _isDelegator) internal view returns(bool) { if (_isDelegator) { if (validatorSetContract.areIdDelegatorsBanned(_poolId)) { // The delegator cannot withdraw from the banned validator pool until the ban is expired return true; } } else { if (validatorSetContract.isValidatorIdBanned(_poolId)) { // The banned validator cannot withdraw from their pool until the ban is expired return true; } else if (governanceContract != IGovernance(0) && governanceContract.isValidatorUnderBallot(_poolId)) { // There is an active ballot in the Governance contract for this validator removal return true; } } return false; } /// @dev Returns `true` if withdrawal from the pool of the specified candidate/validator is allowed at the moment. /// Used by all withdrawal functions. /// @param _poolId An id of the validator's pool. /// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator. function _isWithdrawAllowed(uint256 _poolId, bool _isDelegator) internal view returns(bool) { if (_isPoolBanned(_poolId, _isDelegator)) { return false; } if (!areStakeAndWithdrawAllowed()) { return false; } return true; } /// @dev Returns the balance of this contract in staking tokens or coins /// depending on implementation. function _thisBalance() internal view returns(uint256); }
Returns the list of pool ids into which the specified delegator have ever staked. _delegator The delegator address. _offset The index in the array at which the reading should start. Ignored if the `_length` is 0. _length The max number of items to return.
) external view returns(uint256[] memory result) { uint256[] storage delegatorPools = _delegatorPools[_delegator]; function getDelegatorPools( address _delegator, uint256 _offset, uint256 _length if (_length == 0) { return delegatorPools; } uint256 maxLength = delegatorPools.length.sub(_offset); result = new uint256[](_length > maxLength ? maxLength : _length); for (uint256 i = 0; i < result.length; i++) { result[i] = delegatorPools[_offset + i]; } }
13,080,994
/** *Submitted for verification at Etherscan.io on 2021-04-27 */ // File: contracts\interface\INestMapping.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.3; /// @dev The interface defines methods for nest builtin contract address mapping interface INestMapping { /// @dev Set the built-in contract address of the system /// @param nestTokenAddress Address of nest token contract /// @param nestNodeAddress Address of nest node contract /// @param nestLedgerAddress INestLedger implementation contract address /// @param nestMiningAddress INestMining implementation contract address for nest /// @param ntokenMiningAddress INestMining implementation contract address for ntoken /// @param nestPriceFacadeAddress INestPriceFacade implementation contract address /// @param nestVoteAddress INestVote implementation contract address /// @param nestQueryAddress INestQuery implementation contract address /// @param nnIncomeAddress NNIncome contract address /// @param nTokenControllerAddress INTokenController implementation contract address function setBuiltinAddress( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ) external; /// @dev Get the built-in contract address of the system /// @return nestTokenAddress Address of nest token contract /// @return nestNodeAddress Address of nest node contract /// @return nestLedgerAddress INestLedger implementation contract address /// @return nestMiningAddress INestMining implementation contract address for nest /// @return ntokenMiningAddress INestMining implementation contract address for ntoken /// @return nestPriceFacadeAddress INestPriceFacade implementation contract address /// @return nestVoteAddress INestVote implementation contract address /// @return nestQueryAddress INestQuery implementation contract address /// @return nnIncomeAddress NNIncome contract address /// @return nTokenControllerAddress INTokenController implementation contract address function getBuiltinAddress() external view returns ( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ); /// @dev Get address of nest token contract /// @return Address of nest token contract function getNestTokenAddress() external view returns (address); /// @dev Get address of nest node contract /// @return Address of nest node contract function getNestNodeAddress() external view returns (address); /// @dev Get INestLedger implementation contract address /// @return INestLedger implementation contract address function getNestLedgerAddress() external view returns (address); /// @dev Get INestMining implementation contract address for nest /// @return INestMining implementation contract address for nest function getNestMiningAddress() external view returns (address); /// @dev Get INestMining implementation contract address for ntoken /// @return INestMining implementation contract address for ntoken function getNTokenMiningAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacadeAddress() external view returns (address); /// @dev Get INestVote implementation contract address /// @return INestVote implementation contract address function getNestVoteAddress() external view returns (address); /// @dev Get INestQuery implementation contract address /// @return INestQuery implementation contract address function getNestQueryAddress() external view returns (address); /// @dev Get NNIncome contract address /// @return NNIncome contract address function getNnIncomeAddress() external view returns (address); /// @dev Get INTokenController implementation contract address /// @return INTokenController implementation contract address function getNTokenControllerAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by nest system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string memory key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string memory key) external view returns (address); } // File: contracts\interface\INestGovernance.sol /// @dev This interface defines the governance methods interface INestGovernance is INestMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File: contracts\lib\IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts\interface\INestQuery.sol /// @dev This interface defines the methods for price query interface INestQuery { /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(address tokenAddress) external view returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(address tokenAddress) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ); /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height ) external view returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress) external view returns (uint blockNumber, uint price); /// @dev Get the last (num) effective price /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(address tokenAddress, uint count) external view returns (uint[] memory); /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress) external view returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Get the latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function triggeredPrice2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ); /// @dev Get the full information of latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) /// @return ntokenAvgPrice Average price of ntoken /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ ); /// @dev Get the latest effective price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function latestPrice2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ); } // File: contracts\lib\TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts\interface\INestLedger.sol /// @dev This interface defines the nest ledger methods interface INestLedger { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Configuration structure of nest ledger contract struct Config { // nest reward scale(10000 based). 2000 uint16 nestRewardScale; // // ntoken reward scale(10000 based). 8000 // uint16 ntokenRewardScale; } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config memory config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Carve reward /// @param ntokenAddress Destination ntoken address function carveETHReward(address ntokenAddress) external payable; /// @dev Add reward /// @param ntokenAddress Destination ntoken address function addETHReward(address ntokenAddress) external payable; /// @dev The function returns eth rewards of specified ntoken /// @param ntokenAddress The ntoken address function totalETHRewards(address ntokenAddress) external view returns (uint); /// @dev Pay /// @param ntokenAddress Destination ntoken address. Indicates which ntoken to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function pay(address ntokenAddress, address tokenAddress, address to, uint value) external; /// @dev Settlement /// @param ntokenAddress Destination ntoken address. Indicates which ntoken to settle with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address ntokenAddress, address tokenAddress, address to, uint value) external payable; } // File: contracts\NestBase.sol /// @dev Base contract of nest contract NestBase { // Address of nest token contract address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C; // Genesis block number of nest // NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0 // is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining // algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0 // on-line flow, the actual block is 5120000 uint constant NEST_GENESIS_BLOCK = 5120000; /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) virtual public { require(_governance == address(0), 'NEST:!initialize'); _governance = nestGovernanceAddress; } /// @dev INestGovernance implementation contract address address public _governance; /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) virtual public { address governance = _governance; require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _governance = nestGovernanceAddress; } /// @dev Migrate funds from current contract to NestLedger /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = INestGovernance(_governance).getNestLedgerAddress(); if (tokenAddress == address(0)) { INestLedger(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "NEST:!contract"); _; } } // File: contracts\NestMapping.sol /// @dev The contract is for nest builtin contract address mapping abstract contract NestMapping is NestBase, INestMapping { // constructor() { } /// @dev Address of nest token contract address _nestTokenAddress; /// @dev Address of nest node contract address _nestNodeAddress; /// @dev INestLedger implementation contract address address _nestLedgerAddress; /// @dev INestMining implementation contract address for nest address _nestMiningAddress; /// @dev INestMining implementation contract address for ntoken address _ntokenMiningAddress; /// @dev INestPriceFacade implementation contract address address _nestPriceFacadeAddress; /// @dev INestVote implementation contract address address _nestVoteAddress; /// @dev INestQuery implementation contract address address _nestQueryAddress; /// @dev NNIncome contract address address _nnIncomeAddress; /// @dev INTokenController implementation contract address address _nTokenControllerAddress; /// @dev Address registered in the system mapping(string=>address) _registeredAddress; /// @dev Set the built-in contract address of the system /// @param nestTokenAddress Address of nest token contract /// @param nestNodeAddress Address of nest node contract /// @param nestLedgerAddress INestLedger implementation contract address /// @param nestMiningAddress INestMining implementation contract address for nest /// @param ntokenMiningAddress INestMining implementation contract address for ntoken /// @param nestPriceFacadeAddress INestPriceFacade implementation contract address /// @param nestVoteAddress INestVote implementation contract address /// @param nestQueryAddress INestQuery implementation contract address /// @param nnIncomeAddress NNIncome contract address /// @param nTokenControllerAddress INTokenController implementation contract address function setBuiltinAddress( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ) override external onlyGovernance { if (nestTokenAddress != address(0)) { _nestTokenAddress = nestTokenAddress; } if (nestNodeAddress != address(0)) { _nestNodeAddress = nestNodeAddress; } if (nestLedgerAddress != address(0)) { _nestLedgerAddress = nestLedgerAddress; } if (nestMiningAddress != address(0)) { _nestMiningAddress = nestMiningAddress; } if (ntokenMiningAddress != address(0)) { _ntokenMiningAddress = ntokenMiningAddress; } if (nestPriceFacadeAddress != address(0)) { _nestPriceFacadeAddress = nestPriceFacadeAddress; } if (nestVoteAddress != address(0)) { _nestVoteAddress = nestVoteAddress; } if (nestQueryAddress != address(0)) { _nestQueryAddress = nestQueryAddress; } if (nnIncomeAddress != address(0)) { _nnIncomeAddress = nnIncomeAddress; } if (nTokenControllerAddress != address(0)) { _nTokenControllerAddress = nTokenControllerAddress; } } /// @dev Get the built-in contract address of the system /// @return nestTokenAddress Address of nest token contract /// @return nestNodeAddress Address of nest node contract /// @return nestLedgerAddress INestLedger implementation contract address /// @return nestMiningAddress INestMining implementation contract address for nest /// @return ntokenMiningAddress INestMining implementation contract address for ntoken /// @return nestPriceFacadeAddress INestPriceFacade implementation contract address /// @return nestVoteAddress INestVote implementation contract address /// @return nestQueryAddress INestQuery implementation contract address /// @return nnIncomeAddress NNIncome contract address /// @return nTokenControllerAddress INTokenController implementation contract address function getBuiltinAddress() override external view returns ( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ) { return ( _nestTokenAddress, _nestNodeAddress, _nestLedgerAddress, _nestMiningAddress, _ntokenMiningAddress, _nestPriceFacadeAddress, _nestVoteAddress, _nestQueryAddress, _nnIncomeAddress, _nTokenControllerAddress ); } /// @dev Get address of nest token contract /// @return Address of nest token contract function getNestTokenAddress() override external view returns (address) { return _nestTokenAddress; } /// @dev Get address of nest node contract /// @return Address of nest node contract function getNestNodeAddress() override external view returns (address) { return _nestNodeAddress; } /// @dev Get INestLedger implementation contract address /// @return INestLedger implementation contract address function getNestLedgerAddress() override external view returns (address) { return _nestLedgerAddress; } /// @dev Get INestMining implementation contract address for nest /// @return INestMining implementation contract address for nest function getNestMiningAddress() override external view returns (address) { return _nestMiningAddress; } /// @dev Get INestMining implementation contract address for ntoken /// @return INestMining implementation contract address for ntoken function getNTokenMiningAddress() override external view returns (address) { return _ntokenMiningAddress; } /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacadeAddress() override external view returns (address) { return _nestPriceFacadeAddress; } /// @dev Get INestVote implementation contract address /// @return INestVote implementation contract address function getNestVoteAddress() override external view returns (address) { return _nestVoteAddress; } /// @dev Get INestQuery implementation contract address /// @return INestQuery implementation contract address function getNestQueryAddress() override external view returns (address) { return _nestQueryAddress; } /// @dev Get NNIncome contract address /// @return NNIncome contract address function getNnIncomeAddress() override external view returns (address) { return _nnIncomeAddress; } /// @dev Get INTokenController implementation contract address /// @return INTokenController implementation contract address function getNTokenControllerAddress() override external view returns (address) { return _nTokenControllerAddress; } /// @dev Registered address. The address registered here is the address accepted by nest system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string memory key, address addr) override external onlyGovernance { _registeredAddress[key] = addr; } /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string memory key) override external view returns (address) { return _registeredAddress[key]; } } // File: contracts\NestGovernance.sol /// @dev Nest governance contract contract NestGovernance is NestMapping, INestGovernance { // constructor() { // _governance = address(this); // _governanceMapping[msg.sender] = GovernanceInfo(msg.sender, uint96(0xFFFFFFFFFFFFFFFFFFFFFFFF)); // } /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) override public { // While initialize NestGovernance, nestGovernanceAddress is address(this), // So must let nestGovernanceAddress to 0 require(nestGovernanceAddress == address(0), "NestGovernance:!address"); // nestGovernanceAddress is address(this) super.initialize(address(this)); // Add msg.sender to governance _governanceMapping[msg.sender] = GovernanceInfo(msg.sender, uint96(0xFFFFFFFFFFFFFFFFFFFFFFFF)); } /// @dev Structure of governance address information struct GovernanceInfo { address addr; uint96 flag; } /// @dev Governance address information mapping(address=>GovernanceInfo) _governanceMapping; /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) override external onlyGovernance { if (flag > 0) { _governanceMapping[addr] = GovernanceInfo(addr, uint96(flag)); } else { _governanceMapping[addr] = GovernanceInfo(address(0), uint96(0)); } } /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) override external view returns (uint) { return _governanceMapping[addr].flag; } /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) override public view returns (bool) { return _governanceMapping[addr].flag > flag; } /// @dev This method is for ntoken in created in nest3.0 /// @param addr Destination address /// @return True indicates permission function checkOwners(address addr) external view returns (bool) { return checkGovernance(addr, 0); } }
Get INestMining implementation contract address for ntoken return INestMining implementation contract address for ntoken
function getNTokenMiningAddress() override external view returns (address) { return _ntokenMiningAddress; }
2,450,880
./full_match/10200/0x5f02ad4d2E99172bd3414893fAeE05a208e2eA5D/sources/lib/MultiToken/src/MultiToken.sol
approveAsset Wrapping function for `approve` calls on various token interfaces. By using `safeApprove` for ERC20, caller can set allowance to 0 or from 0. Cannot set non-zero value if allowance is also non-zero. asset Struct defining all necessary context of a token. target Account/address that would be granted approval to `asset`./
function approveAsset(Asset memory asset, address target) internal { if (asset.category == Category.ERC20) { IERC20(asset.assetAddress).safeApprove(target, asset.amount); IERC721(asset.assetAddress).approve(target, asset.id); IERC1155(asset.assetAddress).setApprovalForAll(target, true); ICryptoKitties(asset.assetAddress).approve(target, asset.id); revert("MultiToken: Unsupported category"); } } |*----------------------------------------------------------*/
3,784,873
pragma solidity ^0.5.0; import "./Authors.sol"; /// @title Decentralized Research Publishing Platform , Paper's Smart contract /// @author Farhan Hameed Khan ([email protected] | [email protected]) /// @dev The main purpose of this contract is to store a paper information along its history and versions /// http://www.blockchainsfalcon.com contract Papers { // events event submittedPaper(uint32 paperid,address useraccount); event assignedReviewerEvent(uint paperid,address useraccount); // author contract object Authors authorsContractObj; // author contract deployed address address authorContractAddress; // enum states enum PaperStatus {LATEST,REVIEWING,PASSED,RESUBMIT,REJECTED,MODIFIED,NONE} // history information which contains the author's previous paper status and previous file stored on the IPFS server struct History { PaperStatus status; string ipfs_cid; } // Paper structure struct PaperFiles { // always unique assigned number to the paper uint32 paperUniqueNumber; // must be unique // New state of the paper address author; string title; string ipfs_cid; // reviewing data PaperStatus status; // Every paper has more than one keywords or tags assoiciated with it (String must be converted to bytes32 ) bytes32 [] keywords; //experiment: ["0x63616e6469646174653100000000000000000000000000000000000000000000","0x6332000000000000000000000000000000000000000000000000000000000000","0x6333000000000000000000000000000000000000000000000000000000000000"] address [] reviewers; uint totalReviewer; //put old state in this array associated with version number (which should be incremented on every modification) // old state should be inserted when new state is ready uint version_number; //should be incremeneted mapping(uint=> History) versionHistory; bool paperExist; } // unique PaperID is associated with its information in PaperFiles structure which has version and other info mapping(uint=> PaperFiles) private paperFiles; uint32 totalPapers; // represent id as well bytes32 testingBytes; // testing variable /** @dev the constructor simply gets the author contract address and store it in the authors contract object. * this address is later used for initializing the author contract. * @param _authorContractAddress must be the existing deployed Author contract address */ constructor(address _authorContractAddress) public { totalPapers = 0; authorContractAddress =_authorContractAddress; authorsContractObj = Authors(authorContractAddress); } /** @dev uploadNewPaper - This function adds a new paper information by taking all the paper related information * from the caller. * then it stores them by associating it with the new paper id. * @param _ipfs newly added ipfs based file hash CID * @param _title the title of the paper * @param _keywords string keywords for the paper in bytes32 */ function uploadNewPaper(string memory _ipfs,string memory _title,bytes32[] memory _keywords) public { // _keywords[0] =0x63616e6469646174653100000000000000000000000000000000000000000000; //always remmember we cant insert value like this // but you can get the value using bytes32 keywordFirst= updateP.keywords[0]; // updateP.keywords.push(0x63616e6469646174653100000000000000000000000000000000000000000000); // always use this way to insert // updateP.keywords.push(0x43316e6469646174653100000000000000000000000000000000000000000000); // always use this way to insert require(bytes(_title).length <= 100, "Title is too long."); require(bytes(_ipfs).length <= 69, "IPFS CID is wrong"); uint32 paperId = totalPapers; PaperFiles storage updateP = paperFiles[paperId]; //LATEST PAPER paperId = totalPapers; //new paper id updateP.status = PaperStatus.LATEST; updateP.author = msg.sender; updateP.title = _title; updateP.ipfs_cid = _ipfs; updateP.keywords = _keywords; updateP.paperUniqueNumber = paperId; updateP.totalReviewer = 0; updateP.version_number = 0; updateP.paperExist = true; totalPapers++; authorsContractObj.addPaperInUserFolder(paperId,msg.sender); emit submittedPaper(paperId,msg.sender); } /** @dev uploadModifiedPaper - This function takes new information and stored against the existing paperid * then it stores them by associating it with the new paper id. * @param _paper_id existing paper id * @param _ipfs newly added ipfs based file hash CID * @param _title the title of the paper * @param _keywords string keywords for the paper in bytes32 */ function uploadModifiedPaper(uint32 _paper_id,string memory _ipfs,string memory _title,bytes32[] memory _keywords) public returns(uint32) { // _keywords[0] =0x63616e6469646174653100000000000000000000000000000000000000000000; //always remmember we cant insert value like this // but you can get the value using bytes32 keywordFirst= updateP.keywords[0]; // updateP.keywords.push(0x63616e6469646174653100000000000000000000000000000000000000000000); // always use this way to insert // updateP.keywords.push(0x43316e6469646174653100000000000000000000000000000000000000000000); // always use this way to insert require(paperFiles[_paper_id].paperExist,"Paper must be exist"); require(bytes(_title).length <= 100, "Title is too long."); require(bytes(_ipfs).length <= 69, "IPFS CID is wrong"); uint32 paperId = _paper_id; uint oldversion = paperFiles[paperId].version_number; History storage updateH = paperFiles[paperId].versionHistory[oldversion]; // Since we never assing anything to version history therefore we need to have a seprate variable updateH.ipfs_cid = paperFiles[paperId].ipfs_cid; // save old ipfs id updateH.status = paperFiles[paperId].status; // save old ipfs status //Since we have this existting object in our array so we will directly call the structure to update paperFiles[paperId].author = msg.sender; // again add author name paperFiles[paperId].title = _title; // change title name if required paperFiles[paperId].ipfs_cid = _ipfs; // new ipfs paperFiles[paperId].status = PaperStatus.MODIFIED; // remove all the previous keywords which this paper had for(uint loop = 0; loop<=paperFiles[paperId].keywords.length;loop++) paperFiles[paperId].keywords.pop(); // add the new keywords paperFiles[paperId].keywords = _keywords; // add the new version id paperFiles[paperId].version_number = paperFiles[paperId].version_number + 1 ; // increase the version number return paperId; } /** @dev getLatestId - This function only returns the number of papers on the paper contract * @return uint returns the total stored papers */ function getLatestId() public view returns(uint) { return totalPapers; } /** @dev getPaperValues - This function returns the paper attributes associated with its paper id * @param _paperId paper id * @return string _title the title of the paper * @return string _ipfs ipfs based file hash CID * @return address author author address of the associated paper * @return PaperStatus status the status of the paper * @return address[] reviewers the array of reviewer addresses * @return bytes32[] keywords the keywords attached to the paper * @return uint version the current paper version */ function getPaperValues(uint _paperId) public view returns(string memory title,string memory ipfscid,address author,PaperStatus status,address[] memory reviewers,bytes32[] memory keywords,uint version) { return (paperFiles[_paperId].title,paperFiles[_paperId].ipfs_cid,paperFiles[_paperId].author,paperFiles[_paperId].status,paperFiles[_paperId].reviewers,paperFiles[_paperId].keywords, paperFiles[_paperId].version_number); } /** @dev getVersionHistory - This function returns the author's old paper ipfs hash cid and its status. * @param _paperId paper id * @param version_number number of the version * @return string _ipfs ipfs based file hash CID * @return PaperStatus status the status of the paper */ function getVersionHistory(uint _paperId,uint version_number) public view returns(string memory,PaperStatus ) { return (paperFiles[_paperId].versionHistory[version_number].ipfs_cid,paperFiles[_paperId].versionHistory[version_number].status); } /** @dev getPaperKeyword - This function returns the keyword value * @param _paperId paper id * @param keywordIndex the index of the keyword you are looking for(Make sure index exist) * @return bytes32 the keyword value */ function getPaperKeyword(uint _paperId,uint keywordIndex) public view returns(bytes32) { return paperFiles[_paperId].keywords[keywordIndex]; } /** @dev getSetBytes32Test - testing function */ function getSetBytes32Test(bytes32 para1) public { testingBytes = para1; } /** @dev getBytes32Test - testing function */ function getBytes32Test() public view returns(bytes32) { return testingBytes; } /** @dev getAllLatestPapersIds - This function returns only the latest paper ids. * @return uint[] paperids the array of latest paper ids. */ function getAllLatestPapersIds() public view returns(uint[] memory ids) { uint index = 0; ids = new uint[](totalPapers+1); for(uint loop=0; loop<totalPapers;loop++) { if(paperFiles[loop].status == PaperStatus.LATEST) { ids[index] = loop; index++; } } ids[index] = 0; //end of array return ids; } /** @dev getAllPapersIds - This function returns all the stored paper ids regardless their status * @return uint[] paperids the array of latest paper ids. */ function getAllPapersIds() public view returns(uint[] memory ids) { uint index = 0; ids = new uint[](totalPapers+1); for(uint loop=0; loop<totalPapers;loop++) { ids[index] = loop; index++; } // ids[index] = 0; //end of array return ids; } /** @dev isPaperExist - This function verify if the paper id exist in the paper contract or not. * @param _paperId the paper id * @return bool returns true if paper id exist otherwise false. */ function isPaperExist(uint _paperId) public view returns (bool ret) { if(paperFiles[_paperId].paperExist) return true; return false; } /** @dev isReviewerAlreadyAssigned - Verify if the caller who wants to get assigned on this paper is already assigned * on this paper. Otherwise return false. * @param _paperId the paper id * @return bool returns true if the reviewer is already assigned on this paper id otherwise false. */ function isReviewerAlreadyAssigned(uint _paperId) public view returns(bool ret) { if(paperFiles[_paperId].totalReviewer>0) { // check if this reviewer exist already inside this paper for(uint loop =0; loop<paperFiles[_paperId].totalReviewer; loop++) { if(paperFiles[_paperId].reviewers[loop]==tx.origin) { return true; } } } return false; } // All below functions must be called by Reviewer contract ================================================================ /** @dev assignReviewerToPaper - This function assign the caller to the paper as a reviewer. This function will only be called * by the reviewer contract. * @param _paperId the paper id */ function assignReviewerToPaper(uint _paperId) public { require(paperFiles[_paperId].paperExist,"Paper must be exist"); require(!isReviewerAlreadyAssigned(_paperId),"Reviewer is already assigned for this paper"); if(paperFiles[_paperId].totalReviewer==0) { paperFiles[_paperId].status = PaperStatus.REVIEWING; } paperFiles[_paperId].reviewers.push(tx.origin); paperFiles[_paperId].totalReviewer++; } /** @dev setPaperStatusByReviewer - This function allows the reviewer to set the new status for the paper associated with paper id * by the reviewer contract. * @param _paperId the paper id * @param _status the new status to be set for the paper */ function setPaperStatusByReviewer(uint _paperId,PaperStatus _status) public { require(paperFiles[_paperId].paperExist,"Paper must be exist"); require(isReviewerAlreadyAssigned(_paperId),"Reviewer is not assigned for this paper, he must be assigned on this before changing any status"); paperFiles[_paperId].status = _status; emit assignedReviewerEvent(_paperId,tx.origin); } }
setPaperStatusByReviewer - This function allows the reviewer to set the new status for the paper associated with paper id by the reviewer contract. _paperId the paper id _status the new status to be set for the paper/
function setPaperStatusByReviewer(uint _paperId,PaperStatus _status) public { require(paperFiles[_paperId].paperExist,"Paper must be exist"); require(isReviewerAlreadyAssigned(_paperId),"Reviewer is not assigned for this paper, he must be assigned on this before changing any status"); paperFiles[_paperId].status = _status; emit assignedReviewerEvent(_paperId,tx.origin); }
13,027,341
./partial_match/42/0xC579B84bd628d2F10EAc7B0E7eB328812e0e7ae2/sources/RIS3Farm.sol
Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./
interface IRIS3GOVERNMENT { function startNewCycle() external view returns (uint256); function mintRewards() external view returns (uint256); function getCurrentLaws() external view returns (uint256, uint256, string memory); function getCycleStartTime() external view returns (uint256); function getWithdrawingStartTime() external view returns (uint256); function getgovElectionStartTime() external view returns (uint256); } }
3,369,471
pragma solidity ^0.4.24; import "../openzeppelin-solidity/contracts/ownership/HasNoEther.sol"; import "../openzeppelin-solidity/contracts/ownership/HasNoTokens.sol"; import "../openzeppelin-solidity/contracts/ownership/Claimable.sol"; import "../openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./TrueVND.sol"; import "./NamableAddressList.sol"; // The TimeLockedController contract is intended to be the initial Owner of the TrueVND // contract and TrueVND's AddressLists. It splits ownership into two accounts: an "admin" account and an // "owner" account. The admin of TimeLockedController can initiate minting TrueVND. // However, these transactions must be stored for ~1 day's worth of blocks first before they can be forwarded to the // TrueVND contract. In the event that the admin account is compromised, this setup allows the owner of TimeLockedController // (which can be stored extremely securely since it is never used in normal operation) to replace the admin. // Once a day has passed, requests can be finalized by the admin. // Requests initiated by an admin that has since been deposed cannot be finalized. // The admin is also able to update TrueVND's AddressLists (without a day's delay). // The owner can mint without the day's delay, and also change other aspects of TrueVND like the staking fees. contract TimeLockedController is HasNoEther, HasNoTokens, Claimable { using SafeMath for uint256; uint public constant blocksDelay = 24 * 60 * 60 / 15; // 5760 blocks struct MintOperation { address to; uint256 amount; address admin; uint deferBlock; } address public admin; TrueVND public trueVND; MintOperation[] public mintOperations; modifier onlyAdminOrOwner() { require(msg.sender == admin || msg.sender == owner); _; } event MintOperationEvent(address indexed _to, uint256 amount, uint deferBlock, uint opIndex); event TransferChildEvent(address indexed _child, address indexed _newOwner); event ReclaimEvent(address indexed other); event ChangeBurnBoundsEvent(uint newMin, uint newMax); event WipedAccount(address indexed account); event ChangeStakingFeesEvent(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat); event ChangeStakerEvent(address newStaker); event DelegateEvent(DelegateERC20 delegate); event SetDelegatedFromEvent(address source); event ChangeTrueVNDEvent(TrueVND newContract); event ChangeNameEvent(string name, string symbol); event AdminshipTransferred(address indexed previousAdmin, address indexed newAdmin); // admin initiates a request to mint _amount TrueVND for account _to function requestMint(address _to, uint256 _amount) public onlyAdminOrOwner { uint deferBlock = block.number; if (msg.sender != owner) { deferBlock = deferBlock.add(blocksDelay); } MintOperation memory op = MintOperation(_to, _amount, admin, deferBlock); emit MintOperationEvent(_to, _amount, deferBlock, mintOperations.length); mintOperations.push(op); } // after a day, admin finalizes mint request by providing the // index of the request (visible in the MintOperationEvent accompanying the original request) function finalizeMint(uint index) public onlyAdminOrOwner { MintOperation memory op = mintOperations[index]; require(op.admin == admin); //checks that the requester's adminship has not been revoked require(op.deferBlock <= block.number); //checks that enough time has elapsed address to = op.to; uint256 amount = op.amount; delete mintOperations[index]; trueVND.mint(to, amount); } // Transfer ownership of _child to _newOwner // Can be used e.g. to upgrade this TimeLockedController contract. function transferChild(Ownable _child, address _newOwner) public onlyOwner { emit TransferChildEvent(_child, _newOwner); _child.transferOwnership(_newOwner); } // Transfer ownership of a contract from trueVND // to this TimeLockedController. Can be used e.g. to reclaim balance sheet // in order to transfer it to an upgraded TrueVND contract. function requestReclaim(Ownable other) public onlyOwner { emit ReclaimEvent(other); trueVND.reclaimContract(other); } // Change the minimum and maximum amounts that TrueVND users can // burn to newMin and newMax function changeBurnBounds(uint newMin, uint newMax) public onlyOwner { emit ChangeBurnBoundsEvent(newMin, newMax); trueVND.changeBurnBounds(newMin, newMax); } function wipeBlacklistedAccount(address account) public onlyOwner { emit WipedAccount(account); trueVND.wipeBlacklistedAccount(account); } // Change the transaction fees charged on transfer/mint/burn function changeStakingFees(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat) public onlyOwner { emit ChangeStakingFeesEvent(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat); trueVND.changeStakingFees(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat); } // Change the recipient of staking fees to newStaker function changeStaker(address newStaker) public onlyOwner { emit ChangeStakerEvent(newStaker); trueVND.changeStaker(newStaker); } // Future ERC20 calls to trueVND be delegated to _delegate function delegateToNewContract(DelegateERC20 delegate) public onlyOwner { emit DelegateEvent(delegate); trueVND.delegateToNewContract(delegate); } // Incoming delegate* calls from _source will be accepted by trueVND function setDelegatedFrom(address _source) public onlyOwner { emit SetDelegatedFromEvent(_source); trueVND.setDelegatedFrom(_source); } // Update this contract's trueVND pointer to newContract (e.g. if the // contract is upgraded) function setTrueVND(TrueVND newContract) public onlyOwner { emit ChangeTrueVNDEvent(newContract); trueVND = newContract; } // change trueVND's name and symbol function changeName(string name, string symbol) public onlyOwner { emit ChangeNameEvent(name, symbol); trueVND.changeName(name, symbol); } // Replace the current admin with newAdmin function transferAdminship(address newAdmin) public onlyOwner { emit AdminshipTransferred(admin, newAdmin); admin = newAdmin; } // Swap out TrueVND's address lists function setLists(AddressList _canReceiveMintWhiteList, AddressList _canBurnWhiteList, AddressList _blackList, AddressList _noFeesList) onlyOwner public { trueVND.setLists(_canReceiveMintWhiteList, _canBurnWhiteList, _blackList, _noFeesList); } // Update a whitelist/blacklist function updateList(address list, address entry, bool flag) public onlyAdminOrOwner { AddressList(list).changeList(entry, flag); } // Rename a whitelist/blacklist function renameList(address list, string name) public onlyAdminOrOwner { NamableAddressList(list).changeName(name); } // Claim ownership of an arbitrary Claimable contract function issueClaimOwnership(address _other) public onlyAdminOrOwner { Claimable other = Claimable(_other); other.claimOwnership(); } }
Update this contract's trueVND pointer to newContract (e.g. if the contract is upgraded)
function setTrueVND(TrueVND newContract) public onlyOwner { emit ChangeTrueVNDEvent(newContract); trueVND = newContract; }
12,685,445
pragma solidity ^0.5.0; // --------------------------------------------------------------------------- // Pirate Lottery // // players purchase numbered tickets while a round is open; all the player's addresses are hashed together. // // after the round closes, the winner of the *previous* round can claim his prize, by signing a message: // message = "Pirate Lottery" + hash(previous-round-player-addresses) // // the signature is hashed with hash(current-round-player-addresses) to produce a number X; and the // winner of the current round is selected as the holder of ticket number X modulo N, where N is the number // of tickets sold in the current round. the next round is then opened. // // there are only 2 possible lottery states: // 1) current round is open // in this state players can purchase tickets. // the previous round winner has been selected, but he cannot claim his prize yet. // the round closes when all tickets have been sold or the maximum round duration elapses // // 2) current round closed // in this state players cannot purchase tickets. // the winner of the previous round can claim his prize. // if the prize is not claimed within a certain time, then the prize is considered abandoned. in // that case any participant in the round can claim half the prize. // when the prize is claimed: // a) the winner of the current round is selected // b) a new round is opened // c) what was the current round becomes the previous round // // --------------------------------------------------------------------------- //import './iPlpPointsRedeemer.sol'; // interface for redeeming PLP Points contract iPlpPointsRedeemer { function reserveTokens() public view returns (uint remaining); function transferFromReserve(address _to, uint _value) public; } contract PirateLottery { // // events // event WinnerEvent(uint256 round, uint256 ticket, uint256 prize); event PayoutEvent(uint256 round, address payee, uint256 prize, uint256 payout); // // defines // uint constant MIN_TICKETS = 10; uint constant MAX_TICKETS = 50000000; uint constant LONG_DURATION = 5 days; uint constant SHORT_DURATION = 12 hours; uint constant MAX_CLAIM_DURATION = 5 days; uint constant TOKEN_HOLDOVER_THRESHOLD = 20 finney; // // Round structure // all data pertinent to a single round of the lottery // struct Round { uint256 maxTickets; uint256 ticketPrice; uint256 ticketCount; bytes32 playersHash; uint256 begDate; uint256 endDate; uint256 winner; uint256 prize; bool isOpen; mapping (uint256 => address) ticketOwners; mapping (address => uint256) playerTicketCounts; mapping (address => mapping (uint256 => uint256)) playerTickets; } // // Claim structure // this struture must be signed, ala EIP 712, in order to claim the lottery prize // struct Claim { uint256 ticket; uint256 playerHash; } bytes32 private DOMAIN_SEPARATOR; bytes32 private constant CLAIM_TYPEHASH = keccak256("Claim(string lottery,uint256 round,uint256 ticket,uint256 playerHash)"); bytes32 private constant EIP712DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); // ------------------------------------------------------------------------- // data storage // ------------------------------------------------------------------------- bool public isLocked; string public name; address payable public owner; bytes32 nameHash; uint256 public min_ticket_price; uint256 public max_ticket_price; uint256 public roundCount; mapping (uint256 => Round) public rounds; mapping (address => uint256) public balances; mapping (address => uint256) public plpPoints; iPlpPointsRedeemer plpToken; uint256 public tokenHoldoverBalance; // ------------------------------------------------------------------------- // modifiers // ------------------------------------------------------------------------- modifier ownerOnly { require(msg.sender == owner, "owner only"); _; } modifier unlockedOnly { require(!isLocked, "unlocked only"); _; } // // constructor // constructor(address _plpToken, uint256 _chainId, string memory _name, uint256 _min_ticket_price, uint256 _max_ticket_price) public { owner = msg.sender; name = _name; min_ticket_price = _min_ticket_price; max_ticket_price = _max_ticket_price; plpToken = iPlpPointsRedeemer(_plpToken); Round storage _currentRound = rounds[1]; Round storage _previousRound = rounds[0]; _previousRound.maxTickets = 1; //_previousRound.ticketPrice = 0; _previousRound.ticketCount = 1; _previousRound.playersHash = keccak256(abi.encodePacked(bytes32(0), owner)); _previousRound.begDate = now; _previousRound.endDate = now; _previousRound.winner = 1; _previousRound.ticketOwners[1] = msg.sender; _previousRound.playerTickets[msg.sender][0] = 1; _previousRound.playerTicketCounts[msg.sender]++; //_previousRound.prize = 0; _currentRound.maxTickets = 2; _currentRound.ticketPrice = (min_ticket_price + max_ticket_price) / 2; //_currentRound.ticketCount = 0; //_currentRound.playersHash = 0; //_currentRound.begDate = 0; //_currentRound.endDate = 0; //_currentRound.winner = 0; //_currentRound.prize = 0; _currentRound.isOpen = true; roundCount = 1; //eip 712 DOMAIN_SEPARATOR = keccak256(abi.encode(EIP712DOMAIN_TYPEHASH, keccak256("Pirate Lottery"), keccak256("1.0"), _chainId, address(this))); nameHash = keccak256(abi.encodePacked(name)); } //for debug only... function setToken(address _plpToken) public unlockedOnly ownerOnly { plpToken = iPlpPointsRedeemer(_plpToken); } function lock() public ownerOnly { isLocked = true; } // // buy a ticket for the current round // function buyTicket() public payable { Round storage _currentRound = rounds[roundCount]; require(_currentRound.isOpen == true, "current round is closed"); require(msg.value == _currentRound.ticketPrice, "incorrect ticket price"); if (_currentRound.ticketCount == 0) _currentRound.begDate = now; _currentRound.ticketCount++; _currentRound.prize += msg.value; plpPoints[msg.sender]++; uint256 _ticket = _currentRound.ticketCount; _currentRound.ticketOwners[_ticket] = msg.sender; uint256 _playerTicketCount = _currentRound.playerTicketCounts[msg.sender]; _currentRound.playerTickets[msg.sender][_playerTicketCount] = _ticket; _currentRound.playerTicketCounts[msg.sender]++; _currentRound.playersHash = keccak256(abi.encodePacked(_currentRound.playersHash, msg.sender)); uint256 _currentDuration = now - _currentRound.begDate; if (_currentRound.ticketCount == _currentRound.maxTickets || _currentDuration > LONG_DURATION) { _currentRound.playersHash = keccak256(abi.encodePacked(_currentRound.playersHash, block.coinbase)); _currentRound.isOpen = false; _currentRound.endDate = now; } } // // get info for the current round // if the round is closed, then we are waiting for the winner of the previous round to claim his prize // function getCurrentInfo(address _addr) public view returns(uint256 _round, uint256 _playerTicketCount, uint256 _ticketPrice, uint256 _ticketCount, uint256 _begDate, uint256 _endDate, uint256 _prize, bool _isOpen, uint256 _maxTickets) { Round storage _currentRound = rounds[roundCount]; _round = roundCount; _playerTicketCount = _currentRound.playerTicketCounts[_addr]; _ticketPrice = _currentRound.ticketPrice; _ticketCount = _currentRound.ticketCount; _begDate = _currentRound.begDate; _endDate = _currentRound.isOpen ? (_currentRound.begDate + LONG_DURATION) : _currentRound.endDate; _prize = _currentRound.prize; _isOpen = _currentRound.isOpen; _maxTickets = _currentRound.maxTickets; } // // get the winner of the previous round // function getPreviousInfo(address _addr) public view returns(uint256 _round, uint256 _playerTicketCount, uint256 _ticketPrice, uint256 _ticketCount, uint256 _begDate, uint256 _endDate, uint256 _prize, uint256 _winningTicket, address _winner, uint256 _claimDeadline, bytes32 _playersHash) { Round storage _currentRound = rounds[roundCount]; Round storage _previousRound = rounds[roundCount - 1]; _round = roundCount - 1; _playerTicketCount = _previousRound.playerTicketCounts[_addr]; _ticketPrice = _previousRound.ticketPrice; _ticketCount = _previousRound.ticketCount; _begDate = _previousRound.begDate; _endDate = _previousRound.endDate; _prize = _previousRound.prize; _winningTicket = _previousRound.winner; _winner = _previousRound.ticketOwners[_previousRound.winner]; if (_currentRound.isOpen == true) { _playersHash = bytes32(0); _claimDeadline = 0; } else { _playersHash = _currentRound.playersHash; _claimDeadline = _currentRound.endDate + MAX_CLAIM_DURATION; } } // get array of tickets owned by address // // note that array will always have _maxResults entries. ignore messageID = 0 // function getTickets(address _addr, uint256 _round, uint256 _startIdx, uint256 _maxResults) public view returns(uint256 _idx, uint256[] memory _tickets) { uint _count = 0; Round storage _subjectRound = rounds[_round]; _tickets = new uint256[](_maxResults); uint256 _playerTicketCount = _subjectRound.playerTicketCounts[_addr]; mapping(uint256 => uint256) storage _playerTickets = _subjectRound.playerTickets[_addr]; for (_idx = _startIdx; _idx < _playerTicketCount; ++_idx) { _tickets[_count] = _playerTickets[_idx]; if (++_count >= _maxResults) break; } } // get owner of passed ticket // function getTicketOwner(uint256 _round, uint256 _ticket) public view returns(address _owner) { Round storage _subjectRound = rounds[_round]; _owner = _subjectRound.ticketOwners[_ticket]; } // // winner of previous round claims his prize here // note: you can only claim your prize while the current round is closed // when the winner of the previous round claims his prize, we are then able to determine // the winner of the current round, and then immediately start a new round // function claimPrize(uint8 _sigV, bytes32 _sigR, bytes32 _sigS, uint256 _ticket) public { Round storage _currentRound = rounds[roundCount]; Round storage _previousRound = rounds[roundCount - 1]; require(_currentRound.isOpen == false, "wait until current round is closed"); require(_previousRound.winner == _ticket, "not the winning ticket"); claimPrizeForTicket(_sigV, _sigR, _sigS, _ticket, 2); newRound(); } // // any participant of previous round claims an abandoned prize here // only after MAX_CLAIM_DURATION // function claimAbondonedPrize(uint8 _sigV, bytes32 _sigR, bytes32 _sigS, uint256 _ticket) public { Round storage _currentRound = rounds[roundCount]; require(_currentRound.isOpen == false, "wait until current round is closed"); require(now >= _currentRound.endDate + MAX_CLAIM_DURATION, "prize is not abondoned yet"); claimPrizeForTicket(_sigV, _sigR, _sigS, _ticket, 50); newRound(); } // // verifies signature against claimed ticket; sends prize to claimer // computes winner of current round // function claimPrizeForTicket(uint8 _sigV, bytes32 _sigR, bytes32 _sigS, uint256 _ticket, uint256 _ownerCutPct) internal { Round storage _currentRound = rounds[roundCount]; Round storage _previousRound = rounds[roundCount - 1]; bytes32 _claimHash = keccak256(abi.encode(CLAIM_TYPEHASH, nameHash, roundCount - 1, _ticket, _currentRound.playersHash)); bytes32 _domainClaimHash = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, _claimHash)); address _recovered = ecrecover(_domainClaimHash, _sigV, _sigR, _sigS); require(_previousRound.ticketOwners[_ticket] == _recovered, "claim is not valid"); uint256 _tokenCut = _ownerCutPct * _previousRound.prize / 100; tokenHoldoverBalance += _tokenCut; uint256 _payout = _previousRound.prize - _tokenCut; balances[msg.sender] += _payout; bytes32 _winningHash = keccak256(abi.encodePacked(_currentRound.playersHash, _sigV, _sigR, _sigS)); _currentRound.winner = uint256(_winningHash) % _currentRound.ticketCount + 1; emit PayoutEvent(roundCount - 1, msg.sender, _previousRound.prize, _payout); emit WinnerEvent(roundCount, _currentRound.winner, _currentRound.prize); // if (tokenHoldoverBalance > TOKEN_HOLDOVER_THRESHOLD) { uint _amount = tokenHoldoverBalance; tokenHoldoverBalance = 0; (bool paySuccess, ) = address(plpToken).call.value(_amount)(""); if (!paySuccess) revert(); } } // // open a new round - adjust lottery parameters // goal is that duration should be between SHORT_DURATION and LONG_DURATION // first we adjust ticket price, but if price is already at the corresponding limit, then we adjust maxTickets // function newRound() internal { ++roundCount; Round storage _nextRound = rounds[roundCount]; Round storage _currentRound = rounds[roundCount - 1]; uint256 _currentDuration = _currentRound.endDate - _currentRound.begDate; // if (_currentDuration < SHORT_DURATION) { if (_currentRound.ticketPrice < max_ticket_price && _currentRound.maxTickets > MIN_TICKETS * 10) { _nextRound.ticketPrice = max_ticket_price; _nextRound.maxTickets = _currentRound.maxTickets; } else { _nextRound.ticketPrice = _currentRound.ticketPrice; _nextRound.maxTickets = 2 * _currentRound.maxTickets; if (_nextRound.maxTickets > MAX_TICKETS) _nextRound.maxTickets = MAX_TICKETS; } } else if (_currentDuration > LONG_DURATION) { if (_currentRound.ticketPrice > min_ticket_price) { _nextRound.ticketPrice = min_ticket_price; _nextRound.maxTickets = _currentRound.maxTickets; } else { _nextRound.ticketPrice = min_ticket_price; _nextRound.maxTickets = _currentRound.maxTickets / 2; if (_nextRound.maxTickets < MIN_TICKETS) _nextRound.maxTickets = MIN_TICKETS; } } else { _nextRound.maxTickets = _currentRound.maxTickets; _nextRound.ticketPrice = (min_ticket_price + max_ticket_price) / 2; } //_nextRound.ticketCount = 0; //_nextRound.endDate = 0; //_nextRound.begDate = 0; _nextRound.isOpen = true; } // // redeem caller's transfer-points for PLP Tokens // make sure the reserve account has sufficient tokens before calling // function redeemPlpPoints() public { uint256 noTokens = plpPoints[msg.sender]; plpPoints[msg.sender] = 0; plpToken.transferFromReserve(msg.sender, noTokens); } // // withdraw accumulated prize // function withdraw() public { uint256 _amount = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(_amount); } // // for debug // only available before the contract is locked // function killContract() public ownerOnly unlockedOnly { selfdestruct(owner); } }
withdraw accumulated prize
function withdraw() public { uint256 _amount = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(_amount); }
15,843,022
/* * MIT License * =========== * * 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 */ pragma solidity >= 0.4.22<0.6.0; library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } contract HertzNetworkToken { using SafeMath for uint; uint private totalSupplyAmount; address private owner; mapping(address => uint) private balances; mapping(address => mapping(address => uint)) private allowed; string private tokenName; string private tokenSymbol; uint8 private decimalPoints; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4) ; _; } constructor(string name,string symbol, uint initialSupply,uint8 decimals) public { tokenName=name; tokenSymbol=symbol; decimalPoints=decimals; uint supply=SafeMath.mul(initialSupply,10**uint(decimalPoints)); totalSupplyAmount=supply; owner=msg.sender; balances[owner]=SafeMath.add(balances[owner],totalSupplyAmount); emit Transfer(address(0),owner,totalSupplyAmount); } function name() public view returns(string memory){ return tokenName; } function symbol() public view returns(string memory){ return tokenSymbol; } function decimals() public view returns(uint){ return decimalPoints; } function totalSupply() public view returns(uint){ return totalSupplyAmount; } function balanceOf(address findingBalanceAddress) public view returns(uint){ return balances[findingBalanceAddress]; } function getTokenOwnerAddress() public view returns(address){ return owner; } function transfer(address to,uint tokenAmountInWEI) public returns(bool){ require(balances[msg.sender]>=tokenAmountInWEI); require(tokenAmountInWEI>0); require((SafeMath.add(balances[to],tokenAmountInWEI))>balances[to]); balances[msg.sender] = SafeMath.sub(balances[msg.sender],tokenAmountInWEI); balances[to] = SafeMath.add(balances[to],tokenAmountInWEI); emit Transfer(msg.sender,to,tokenAmountInWEI); return true; } function transferFrom(address from,address to,uint tokenAmountInWEI) onlyPayloadSize(3 * 32) public returns(bool){ require(balances[from]>=tokenAmountInWEI); require(allowed[from] [msg.sender]>=tokenAmountInWEI); require(tokenAmountInWEI>0); require((SafeMath.add(balances[to],tokenAmountInWEI))>balances[to]); balances[to] = SafeMath.add(balances[to],tokenAmountInWEI); balances[from] = SafeMath.sub(balances[from],tokenAmountInWEI); allowed[from][msg.sender] = SafeMath.sub(allowed[from][msg.sender],tokenAmountInWEI); emit Transfer(from,to,tokenAmountInWEI); return true; } function approve(address spender,uint tokenAmountInWEI) public returns(bool){ allowed[msg.sender][spender]=SafeMath.add(allowed[msg.sender][spender],tokenAmountInWEI); emit Approval(msg.sender,spender,tokenAmountInWEI); return true; } function allownce(address from,address spender) public view returns(uint){ return allowed[from][spender]; } function burn (uint tokenAmount) public returns(bool){ uint amountInWEI=SafeMath.mul(tokenAmount,10**uint(decimalPoints)); require(msg.sender==owner && balances[msg.sender]>=amountInWEI && totalSupplyAmount>=amountInWEI); totalSupplyAmount=SafeMath.sub(totalSupplyAmount,amountInWEI); balances[msg.sender]=SafeMath.sub(balances[msg.sender],amountInWEI); emit Transfer(msg.sender,address(0),amountInWEI); return true; } event Transfer(address indexed from,address indexed to,uint amount); event Approval(address indexed indexer,address indexed spender,uint amount); }
assert(b > 0); Solidity automatically throws when dividing by 0 assert(a == b c + a % b); There is no case in which this doesn't hold
function div(uint a, uint b) internal pure returns (uint) { uint c = a / b; return c; }
5,869,167
// File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/Pausable.sol pragma solidity 0.6.12; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * */ contract Pausable is Context { event Paused(address account); event Shutdown(address account); event Unpaused(address account); event Open(address account); bool public paused; bool public stopEverything; modifier whenNotPaused() { require(!paused, "Pausable: paused"); _; } modifier whenPaused() { require(paused, "Pausable: not paused"); _; } modifier whenNotShutdown() { require(!stopEverything, "Pausable: shutdown"); _; } modifier whenShutdown() { require(stopEverything, "Pausable: not shutdown"); _; } function _pause() internal virtual whenNotPaused { paused = true; emit Paused(_msgSender()); } function _unpause() internal virtual whenPaused whenNotShutdown { paused = false; emit Unpaused(_msgSender()); } function _shutdown() internal virtual whenNotShutdown { stopEverything = true; paused = true; emit Shutdown(_msgSender()); } function _open() internal virtual whenShutdown { stopEverything = false; emit Open(_msgSender()); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.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]. */ 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; } } // File: contracts/interfaces/vesper/IController.sol pragma solidity 0.6.12; interface IController { function aaveProvider() external view returns (address); function aaveReferralCode() external view returns (uint16); function builderFee() external view returns (uint256); function builderVault() external view returns (address); function collateralToken(address pool) external view returns (address); function fee(address) external view returns (uint256); function feeCollector(address pool) external view returns (address); function getPoolCount() external view returns (uint256); function getPools() external view returns (address[] memory); function highWater(address) external view returns (uint256); function lowWater(address) external view returns (uint256); function isPool(address pool) external view returns (bool); function mcdDaiJoin() external view returns (address); function mcdJug() external view returns (address); function mcdManager() external view returns (address); function mcdSpot() external view returns (address); function pools(uint256 index) external view returns (address); function poolStrategy(address pool) external view returns (address); function poolCollateralManager(address pool) external view returns (address); function rebalanceFriction(address) external view returns (uint256); function treasuryPool() external view returns (address); function uniswapRouter() external view returns (address); } // File: contracts/pools/PoolRewards.sol pragma solidity 0.6.12; contract PoolRewards is ERC20, ReentrancyGuard { IERC20 public immutable rewardsToken; IController public immutable controller; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public constant REWARD_DURATION = 7 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); /** * @dev Constructor. */ constructor( string memory name, string memory symbol, address _controller, address _rewardsToken ) public ERC20(name, symbol) { controller = IController(_controller); rewardsToken = IERC20(_rewardsToken); } event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address _account) { _updateReward(_account); _; } function notifyRewardAmount(uint256 reward) external updateReward(address(0)) { require(_msgSender() == address(controller), "Not authorized"); if (block.timestamp >= periodFinish) { rewardRate = reward.div(REWARD_DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(REWARD_DURATION); } uint256 balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(REWARD_DURATION), "Reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(REWARD_DURATION); emit RewardAdded(reward); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(REWARD_DURATION); } function getReward() public nonReentrant updateReward(_msgSender()) { uint256 reward = rewards[_msgSender()]; if (reward != 0) { rewards[_msgSender()] = 0; rewardsToken.transfer(_msgSender(), reward); emit RewardPaid(_msgSender(), reward); } } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function lastTimeRewardApplicable() public view returns (uint256) { return block.timestamp < periodFinish ? block.timestamp : periodFinish; } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div( totalSupply() ) ); } function _updateReward(address _account) private { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (_account != address(0)) { rewards[_account] = earned(_account); userRewardPerTokenPaid[_account] = rewardPerTokenStored; } } } // File: contracts/pools/PoolShareToken.sol pragma solidity 0.6.12; // solhint-disable no-empty-blocks abstract contract PoolShareToken is PoolRewards, Pausable { IERC20 public immutable token; /// @dev The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /// @dev The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 public immutable domainSeparator; uint256 internal constant MAX_UINT_VALUE = uint256(-1); mapping(address => uint256) public nonces; event Deposit(address indexed owner, uint256 shares, uint256 amount); event Withdraw(address indexed owner, uint256 shares, uint256 amount); /** * @dev Constructor. */ constructor( string memory _name, string memory _symbol, address _token, address _controller, address _rewardsToken ) public PoolRewards(_name, _symbol, _controller, _rewardsToken) { uint256 chainId; require(_rewardsToken != _token, "Reward and collateral same"); assembly { chainId := chainid() } token = IERC20(_token); domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(_name)), keccak256(bytes("1")), chainId, address(this) ) ); } /** * @dev Receives ERC20 token amount and grants new tokens to the sender * depending on the value of each contract's share. */ function deposit(uint256 amount) external virtual nonReentrant whenNotPaused updateReward(_msgSender()) { require( _msgSender() == 0xdf826ff6518e609E4cEE86299d40611C148099d5 || totalSupply() < 50e18, "Test limit reached" ); _deposit(amount); } /** * @dev Burns tokens and retuns deposited tokens or ETH value for those. */ function withdraw(uint256 shares) external virtual nonReentrant whenNotShutdown updateReward(_msgSender()) { _withdraw(shares); } /** * @dev Burns tokens and retuns the collateral value of those. */ function withdrawByFeeCollector(uint256 shares) external virtual nonReentrant whenNotShutdown updateReward(_msgSender()) { require(_msgSender() == _getFeeCollector(), "Not a fee collector."); _withdrawByFeeCollector(shares); } /** * @dev Calculate and returns price per share of the pool. */ function getPricePerShare() external view returns (uint256) { if (totalSupply() == 0) { return convertFrom18(1e18); } return totalValue().mul(1e18).div(totalSupply()); } /** * @dev Convert to 18 decimals from token defined decimals. Default no conversion. */ function convertTo18(uint256 amount) public virtual pure returns (uint256) { return amount; } /** * @dev Convert from 18 decimals to token defined decimals. Default no conversion. */ function convertFrom18(uint256 amount) public virtual pure returns (uint256) { return amount; } /** * @dev Returns the value stored in the pool. */ function tokensHere() public virtual view returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Returns sum of value locked in other contract and value stored in the pool. */ function totalValue() public virtual view returns (uint256) { return tokensHere(); } /** * @dev Hook that is called just before burning tokens. To be used i.e. if * collateral is stored in a different contract and needs to be withdrawn. */ function _beforeBurning(uint256 share) internal virtual {} /** * @dev Hook that is called just after burning tokens. To be used i.e. if * collateral stored in a different/this contract needs to be transferred. */ function _afterBurning(uint256 amount) internal virtual {} /** * @dev Hook that is called just before minting new tokens. To be used i.e. * if the deposited amount is to be transferred to a different contract. */ function _beforeMinting(uint256 amount) internal virtual {} /** * @dev Hook that is called just after minting new tokens. To be used i.e. * if the minted token/share is to be transferred to a different contract. */ function _afterMinting(uint256 amount) internal virtual {} /** * @dev Get withdraw fee for this pool */ function _getFee() internal virtual view returns (uint256) {} /** * @dev Get fee collector address */ function _getFeeCollector() internal virtual view returns (address) {} /** * @dev Calculate share based on share price and given amount. */ function _calculateShares(uint256 amount) internal view returns (uint256) { require(amount != 0, "amount is 0"); uint256 _totalSupply = totalSupply(); uint256 _totalValue = convertTo18(totalValue()); uint256 shares = (_totalSupply == 0 || _totalValue == 0) ? amount : amount.mul(_totalSupply).div(_totalValue); return shares; } /** * @dev Deposit incoming token and mint pool token i.e. shares. */ function _deposit(uint256 amount) internal whenNotPaused { uint256 shares = _calculateShares(convertTo18(amount)); _beforeMinting(amount); _mint(_msgSender(), shares); _afterMinting(amount); emit Deposit(_msgSender(), shares, amount); } /** * @dev Handle fee calculation and fee transfer to fee collector. */ function _handleFee(uint256 shares) internal returns (uint256 _sharesAfterFee) { if (_getFee() != 0) { uint256 _fee = shares.mul(_getFee()).div(1e18); _sharesAfterFee = shares.sub(_fee); _transfer(_msgSender(), _getFeeCollector(), _fee); } else { _sharesAfterFee = shares; } } /** * @dev Burns tokens and retuns the collateral value, after fee, of those. */ function _withdraw(uint256 shares) internal whenNotShutdown { require(shares != 0, "share is 0"); _beforeBurning(shares); uint256 sharesAfterFee = _handleFee(shares); uint256 amount = convertFrom18( sharesAfterFee.mul(convertTo18(totalValue())).div(totalSupply()) ); _burn(_msgSender(), sharesAfterFee); _afterBurning(amount); emit Withdraw(_msgSender(), shares, amount); } function _withdrawByFeeCollector(uint256 shares) internal { require(shares != 0, "Withdraw must be greater than 0"); _beforeBurning(shares); uint256 amount = convertFrom18(shares.mul(convertTo18(totalValue())).div(totalSupply())); _burn(_msgSender(), shares); _afterBurning(amount); emit Withdraw(_msgSender(), shares, amount); } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "Expired"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline) ) ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0) && signatory == owner, "Invalid signature"); _approve(owner, spender, amount); } } // File: contracts/interfaces/uniswap/IUniswapV2Router01.sol pragma solidity 0.6.12; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // File: contracts/interfaces/uniswap/IUniswapV2Router02.sol pragma solidity 0.6.12; interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // File: contracts/interfaces/vesper/IStrategy.sol pragma solidity 0.6.12; interface IStrategy { function rebalance() external; function deposit(uint256 amount) external; function beforeWithdraw() external; function withdraw(uint256 amount) external; function isEmpty() external view returns (bool); function isReservedToken(address _token) external view returns (bool); function token() external view returns (address); function totalLocked() external view returns (uint256); //Lifecycle functions function pause() external; function unpause() external; function shutdown() external; function open() external; } // File: contracts/pools/VTokenBase.sol pragma solidity 0.6.12; abstract contract VTokenBase is PoolShareToken { address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; constructor( string memory name, string memory symbol, address _token, address _controller, address _rewardsToken ) public PoolShareToken(name, symbol, _token, _controller, _rewardsToken) { require(_controller != address(0), "Controller address is zero"); } modifier onlyController() { require(address(controller) == _msgSender(), "Caller is not the controller"); _; } function pause() external onlyController { IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); strategy.pause(); _pause(); } function unpause() external onlyController { IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); strategy.unpause(); _unpause(); } function shutdown() external onlyController { IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); strategy.shutdown(); _shutdown(); } function open() external onlyController { IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); strategy.open(); _open(); } function approveToken(address spender) external virtual { require(spender == controller.poolStrategy(address(this)), "Can not approve"); token.approve(spender, MAX_UINT_VALUE); IERC20(IStrategy(spender).token()).approve(spender, MAX_UINT_VALUE); } function resetApproval(address spender) external virtual onlyController { require(spender == controller.poolStrategy(address(this)), "Can not reset approval"); token.approve(spender, 0); IERC20(IStrategy(spender).token()).approve(spender, 0); } function rebalance() external virtual { require(!stopEverything || (_msgSender() == address(controller)), "Contract has shutdown"); IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); strategy.rebalance(); } function sweepErc20(address _erc20) external virtual { _sweepErc20(_erc20); } function withdrawAll() external virtual onlyController { _withdrawCollateral(uint256(-1)); } function withdrawByFeeCollector(uint256 shares) external override nonReentrant whenNotShutdown updateReward(_msgSender()) { address feeCollector = _getFeeCollector(); require( _msgSender() == feeCollector || _msgSender() == controller.poolStrategy(feeCollector), "Not a fee collector." ); _withdrawByFeeCollector(shares); } function tokenLocked() public virtual view returns (uint256) { IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); return strategy.totalLocked(); } function totalValue() public override view returns (uint256) { return tokenLocked().add(tokensHere()); } function _afterBurning(uint256 _amount) internal override { uint256 balanceHere = tokensHere(); if (balanceHere < _amount) { _withdrawCollateral(_amount.sub(balanceHere)); balanceHere = tokensHere(); _amount = balanceHere < _amount ? balanceHere : _amount; } token.transfer(_msgSender(), _amount); } function _beforeBurning( uint256 /* shares */ ) internal override { IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); strategy.beforeWithdraw(); } function _beforeMinting(uint256 amount) internal override { token.transferFrom(_msgSender(), address(this), amount); } function _depositCollateral(uint256 amount) internal virtual { IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); strategy.deposit(amount); } function _getFee() internal override view returns (uint256) { return controller.fee(address(this)); } function _getFeeCollector() internal override view returns (address) { return controller.feeCollector(address(this)); } function _withdrawCollateral(uint256 amount) internal virtual { IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); strategy.withdraw(amount); } function _sweepErc20(address _from) internal { IStrategy strategy = IStrategy(controller.poolStrategy(address(this))); require( _from != address(token) && _from != address(this) && !strategy.isReservedToken(_from) && _from != address(rewardsToken), "Not allowed to sweep" ); IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(controller.uniswapRouter()); uint256 amt = IERC20(_from).balanceOf(address(this)); IERC20(_from).approve(address(uniswapRouter), amt); address[] memory path; if (address(token) == WETH) { path = new address[](2); path[0] = _from; path[1] = address(token); } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = address(token); } uniswapRouter.swapExactTokensForTokens(amt, 1, path, address(this), now + 30); } } // File: contracts/interfaces/token/IToken.sol pragma solidity 0.6.12; interface TokenLike { function approve(address, uint256) external; function balanceOf(address) external view returns (uint256); function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; } // File: contracts/pools/VETH.sol pragma solidity 0.6.12; contract VUSDC is VTokenBase { constructor(address _controller, address _rewardsToken) public VTokenBase( "VUSDC Pool Test", "VUSDCT", 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, _controller, _rewardsToken ) {} /** * @dev Convert to 18 decimal from 8 decimal value. */ function convertTo18(uint256 amount) public override pure returns (uint256) { return amount.mul(10**12); } /** * @dev Convert to 8 decimal from 18 decimal value. */ function convertFrom18(uint256 amount) public override pure returns (uint256) { return amount.div(10**12); } }
Calculate share based on share price and given amount./
function _calculateShares(uint256 amount) internal view returns (uint256) { require(amount != 0, "amount is 0"); uint256 _totalSupply = totalSupply(); uint256 _totalValue = convertTo18(totalValue()); uint256 shares = (_totalSupply == 0 || _totalValue == 0) ? amount : amount.mul(_totalSupply).div(_totalValue); return shares; }
1,333,577
./full_match/1/0x32ee46755AE81ce917392ed1fB21f74a8104515B/sources/contracts/strategies/angle/AngleMerklClaimer.sol
function to claim and notify the ANGLE reward via merkle _proofs merkle proofs _vault vault to claim the reward for _token reward token _amount amount to notify the reward will be send to the vault transfer reward from vault to here
function claimAndNotify( bytes32[][] calldata _proofs, address _vault, address _token, uint256 _amount ) external { address[] memory users = new address[](1); users[0] = _vault; address[] memory tokens = new address[](1); tokens[0] = _token; uint256[] memory amounts = new uint256[](1); amounts[0] = _amount; uint256 balanceBefore = ERC20(_token).balanceOf(_vault); merkleDistributor.claim(users, tokens, amounts, _proofs); uint256 reward = ERC20(_token).balanceOf(_vault) - balanceBefore; if (reward > 0) { ERC20(_token).transferFrom(_vault, address(this), reward); uint256 rewardToNotify = _chargeFees(_token, reward); address liquidityGauge = IAngleVault(_vault).liquidityGauge(); ERC20(_token).approve(liquidityGauge, rewardToNotify); ILiquidityGaugeStrat(liquidityGauge).deposit_reward_token(_token, rewardToNotify); } }
16,489,072
./full_match/1/0xedDF24978021B8498f9f92457c6bAA24549eAb8a/sources/browser/OXStaking.sol
------------------------------------------------------------------------ This will stop the existing staking ------------------------------------------------------------------------ update staking stats check if we have any pending rewards, add it to previousGains var update amount reset last claimed figure as well withdraw the tokens and move from contract to the caller
function StopStaking() external { require(users[msg.sender].activeDeposit >= 0, "No active stake"); uint256 _activeDeposit = users[msg.sender].activeDeposit; users[msg.sender].pendingGains = PendingReward(msg.sender); users[msg.sender].activeDeposit = 0; users[msg.sender].lastClaimedDate = now; require(IERC20(OXS).transfer(msg.sender, _activeDeposit)); emit StakingStopped(_activeDeposit); }
2,910,240
./full_match/3/0x30de7ADec3a055Ca5b482c79A751a067e9568bed/sources/newcontract.sol
silence state mutability warning without generating bytecode - see https:github.com/ethereum/solidity/issues/2691
function _msgData ( ) internal view virtual returns (bytes memory) { this ; return msg . data ; }
14,139,741
./full_match/1/0x998a3c80807d1Df43f17453123538E4D9934b7Ca/sources/EthernaalNF2T.sol
This function is used to whitelist a tattoo partner on the platform/
function whitelistPartners(address _partner) public onlyOwner returns(bool) { require(_partner != address(0), "Partner address has to be non-zero"); whitelistPartnerMapping[_partner] = true; return whitelistPartnerMapping[_partner]; }
9,820,030
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/PoolRegistry.sol
Tests whether the given initialization by the given user is authorized on this specific pool. If not, reverts the transaction. If pool is permissionless this function will just noop. /
function verifyPermitInit (PoolSpecs.PoolCursor memory pool, address base, address quote, uint256 poolIdx) internal { if (pool.oracle_ != address(0)) { bool approved = ICrocPermitOracle(pool.oracle_). checkApprovedForCrocInit(lockHolder_, msg.sender, base, quote, poolIdx); require(approved, "Z"); } }
4,651,127
// SPDX-License-Identifier: MIT import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./ERC721A.sol"; pragma solidity ^0.8.0; /** * @title Shark Society contract * @dev Extends ERC721A Non-Fungible Token Standard basic implementation */ contract SharkSociety is ERC721A { using SafeMath for uint256; using Strings for uint256; string public PROVENANCE; uint256 public constant MAX_TOKENS = 5000; uint256 public constant MAX_TOKENS_PLUS_ONE = 5001; uint256 public sharkPrice = 0.04 ether; uint256 public presaleSharkPrice = 0.03 ether; uint public constant maxSharksPlusOne = 6; uint public constant maxOwnedPlusOne = 9; uint public constant maxForPresalePlusOne = 3; bool public saleIsActive = false; // Metadata base URI string public baseURI; // Whitelist and Presale mapping(address => bool) Whitelist; bool public presaleIsActive = false; uint256 _maxBatchSize = 5; uint256 _maxTotalSupply = 5000; /** @param name - Name of ERC721 as used in openzeppelin @param symbol - Symbol of ERC721 as used in openzeppelin @param provenance - The sha256 string of concatenated sha256 of all images in their natural order - AKA Provenance. @param baseUri - Base URI for token metadata */ constructor(string memory name, string memory symbol, string memory provenance, string memory baseUri) ERC721A(name, symbol, _maxBatchSize, _maxTotalSupply){ PROVENANCE = provenance; baseURI = baseUri; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(0x0Cf7d58A50d5b3683Fd38c9f3934723DeC75A3c0).transfer(balance.mul(200).div(1000)); payable(0x8A7fA1106068DD75427525631b086208884111a5).transfer(balance.mul(200).div(1000)); payable(0xfc9DA6Edc4ABB3f3E4Ec2AD5B606514Ce1DE0dA4).transfer(balance.mul(240).div(1000)); payable(0xF5278A7BCc1546F22f7CD6b2B23286293139aF9B).transfer(balance.mul(100).div(1000)); payable(0x946f817599B788a58f4e85689F8D4a508dc3C801).transfer(balance.mul(150).div(1000)); payable(0xC68b81FBDff9587c3a024e7179a29329Ee9c1C8e).transfer(balance.mul(100).div(1000)); payable(0x38dE2236b854A8E06293237AeFaE4FDa94b2a2c3).transfer(balance.mul(10).div(1000)); } /** * @dev Sets the Base URI for computing {tokenURI}. */ function setBaseURI(string calldata _tokenBaseURI) external onlyOwner { baseURI = _tokenBaseURI; } /** * @dev Returns the base URI. Overrides empty string returned by base class. * Unused because we override {tokenURI}. * Included for completeness-sake. */ function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @dev Adds addresses to the whitelist */ function addToWhitelist(address[] calldata addrs) external onlyOwner { for (uint i = 0; i < addrs.length; i++) { Whitelist[addrs[i]] = true; } } /** * @dev Removes addresses from the whitelist */ function removeFromWhitelist(address[] calldata addrs) external onlyOwner { for (uint i = 0; i < addrs.length; i++) { Whitelist[addrs[i]] = false; } } /** * @dev Checks if an address is in the whitelist */ function isAddressInWhitelist(address addr) public view returns (bool) { return Whitelist[addr]; } /** * @dev Checks if the sender's address is in the whitelist */ function isSenderInWhitelist() public view returns (bool) { return Whitelist[msg.sender]; } /** * @dev Pause sale if active, activate if paused */ function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } /** * @dev Pause presale if active, activate if paused */ function flipPresaleState() public onlyOwner { presaleIsActive = !presaleIsActive; } /* * Set provenance hash - just in case there is an error * Provenance hash is set in the contract construction time, * ideally there is no reason to ever call it. */ function setProvenanceHash(string memory provenanceHash) public onlyOwner { PROVENANCE = provenanceHash; } /** * @dev Sets the mint price */ function setPrice(uint256 price) external onlyOwner { require(price > 0, "Invalid price."); sharkPrice = price; } /** * @dev Sets the mint price */ function setPresalePrice(uint256 price) external onlyOwner { require(price > 0, "Invalid price."); presaleSharkPrice = price; } function registerForPresale() external { require(!presaleIsActive, "The presale has already begun!"); Whitelist[msg.sender] = true; } /** * @dev Mints Sharks * Ether value sent must exactly match. */ function mintSharks(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Sharks."); require(numberOfTokens < maxSharksPlusOne, "Can only mint 5 Sharks at a time."); require(balanceOf(msg.sender).add(numberOfTokens) < maxOwnedPlusOne, "Purchase would exceed presale limit of 8 Sharks per address."); require(totalSupply().add(numberOfTokens) < MAX_TOKENS_PLUS_ONE, "Purchase would exceed max supply of Sharks."); require(sharkPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct."); _safeMint(msg.sender, numberOfTokens); } /** * @dev Mints Sharks during the presale. * Ether value sent must exactly match - * and only addresses in {Whitelist} are allowed to participate in the presale. */ function presaleMintSharks(uint numberOfTokens) public payable { require(presaleIsActive && !saleIsActive, "Presale is not active."); require(isSenderInWhitelist(), "Your address is not in the whitelist."); require(balanceOf(msg.sender).add(numberOfTokens) < maxForPresalePlusOne, "Purchase would exceed presale limit of 2 Sharks per address."); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Sharks."); require(presaleSharkPrice.mul(numberOfTokens) == msg.value, "Ether value sent is not correct."); _safeMint(msg.sender, numberOfTokens); } /** * Reserve Sharks for future marketing and the team */ function reserveSharks(uint256 amount, address to) public onlyOwner { uint supply = totalSupply(); require(supply.add(amount) < MAX_TOKENS_PLUS_ONE, "Reserving would exceed supply."); _safeMint(to, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, Ownable, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 public collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721B: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require( owner != address(0), "ERC721A: balance query for the zero address" ); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require( _exists(tokenId), "ERC721A: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev 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 = ERC721A.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return (tokenId < currentIndex); } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721A.ownerOf(tokenId); AddressData memory addressData = _addressData[owner]; _addressData[owner] = AddressData( addressData.balance - 1, addressData.numberMinted - 1 ); _ownerships[tokenId] = TokenOwnership( address(0), uint64(block.timestamp) ); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721A: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // SPDX-License-Identifier: MIT // 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 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
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 = ERC721A.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); }
370,610
./partial_match/80001/0x07DDC851a1bee757335EBcd7B14348359fDaB60f/sources/PlotXToken.sol
change operator address _newOperator address of new operator/
function changeOperator(address _newOperator) public onlyOperator returns (bool) { require(_newOperator != address(0), "New operator cannot be 0 address"); operator = _newOperator; return true; }
8,810,495
pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @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 { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public _totalSupply; function totalSupply() public constant returns (uint); function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public; event Transfer(address indexed from, address indexed to, uint value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint); function transferFrom(address from, address to, uint value) public; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is Ownable, ERC20Basic { using SafeMath for uint; mapping(address => uint) public balances; // additional variables for use if transaction fees ever became necessary uint public basisPointsRate = 0; uint public maximumFee = 0; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } /** * @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, uint _value) public onlyPayloadSize(2 * 32) { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); Transfer(msg.sender, owner, fee); } Transfer(msg.sender, _to, sendAmount); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint 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 oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) public allowed; uint public constant MAX_UINT = 2**256 - 1; /** * @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 uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); Transfer(_from, owner, fee); } Transfer(_from, _to, sendAmount); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than 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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract BlackList is Ownable, BasicToken { /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded EUROQUINNToken) /////// function getBlackListStatus(address _maker) external constant returns (bool) { return isBlackListed[_maker]; } function getOwner() external constant returns (address) { return owner; } mapping (address => bool) public isBlackListed; function addBlackList (address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; AddedBlackList(_evilUser); } function removeBlackList (address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; RemovedBlackList(_clearedUser); } function destroyBlackFunds (address _blackListedUser) public onlyOwner { require(isBlackListed[_blackListedUser]); uint dirtyFunds = balanceOf(_blackListedUser); balances[_blackListedUser] = 0; _totalSupply -= dirtyFunds; DestroyedBlackFunds(_blackListedUser, dirtyFunds); } event DestroyedBlackFunds(address _blackListedUser, uint _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); } contract UpgradedStandardToken is StandardToken{ // those methods are called by the legacy contract // and they must ensure msg.sender to be the contract address function transferByLegacy(address from, address to, uint value) public; function transferFromByLegacy(address sender, address from, address spender, uint value) public; function approveByLegacy(address from, address spender, uint value) public; } contract EUROQUINNToken is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // The contract can be initialized with a number of tokens // All the tokens are deposited to the owner address // // @param _balance Initial supply of the contract // @param _name Token Name // @param _symbol Token symbol // @param _decimals Token decimals function EUROQUINNToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Forward ERC20 methods to upgraded contract if this one is deprecated function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // deprecate current contract in favour of a new one function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; Deprecate(_upgradedAddress); } // deprecate current contract if favour of a new one function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issuedi function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; Issue(amount); } // Redeem tokens. // These tokens are withdrawn from the owner address // if the balance must be enough to cover the redeem // or the call will fail. // @param _amount Number of tokens to be issued function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; Redeem(amount); } function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Ensure transparency by hardcoding limit beyond which fees can never be added require(newBasisPoints < 20); require(newMaxFee < 50); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); Params(basisPointsRate, maximumFee); } // Called when new token are issued event Issue(uint amount); // Called when tokens are redeemed event Redeem(uint amount); // Called when contract is deprecated event Deprecate(address newAddress); // Called if contract ever adds fees event Params(uint feeBasisPoints, uint maxFee); }
Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); return super.transfer(_to, _value); } }
436,260
./full_match/42/0xd86721346245a47354D22a99CB31d3eC4436d9AE/sources/browser/ACOFactory.sol
Internal function to set the operator permission. operator Address of the operator. newPermission Whether the operator will be authorized./
function _setOperator(address operator, bool newPermission) internal virtual { emit SetOperator(operator, operators[operator], newPermission); operators[operator] = newPermission; }
9,567,697
// File: @openzeppelin/contracts/GSN/Context.sol 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; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.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. * * 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 { _owner = _msgSender(); 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(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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // 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 != 0x0 && codehash != accountHash); } /** * @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"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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"); } } } // File: contracts/protocol/interfaces/IOffChainAssetValuatorV2.sol /* * Copyright 2020 DMM Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; interface IOffChainAssetValuatorV2 { // ************************* // ***** Events // ************************* event AssetsValueUpdated(uint newAssetsValue); event AssetTypeSet(uint tokenId, string assetType, bool isAdded); // ************************* // ***** Admin Functions // ************************* function initialize( address owner, address guardian, address linkToken, uint oraclePayment, uint offChainAssetsValue, bytes32 offChainAssetsValueJobId ) external; /** * @dev Adds an asset type to be supported by the provided principal / affiliate. Use `tokenId` 0 to denote all * asset introducers. */ function addSupportedAssetTypeByTokenId( uint tokenId, string calldata assetType ) external; /** * @dev Removes an asset type to be supported by the provided principal / affiliate. Use `tokenId` 0 to denote all * asset introducers. */ function removeSupportedAssetTypeByTokenId( uint tokenId, string calldata assetType ) external; /** * Sets the oracle job ID for getting all collateral for the ecosystem. */ function setCollateralValueJobId( bytes32 jobId ) external; /** * Sets the amount of LINK to be paid for the `collateralValueJobId` */ function setOraclePayment( uint oraclePayment ) external; function submitGetOffChainAssetsValueRequest( address oracle ) external; function fulfillGetOffChainAssetsValueRequest( bytes32 requestId, uint offChainAssetsValue ) external; // ************************* // ***** Misc Functions // ************************* /** * @return The amount of LINK to be paid for fulfilling this oracle request. */ function oraclePayment() external view returns (uint); /** * @return The timestamp at which the oracle was last pinged */ function lastUpdatedTimestamp() external view returns (uint); /** * @return The block number at which the oracle was last pinged */ function lastUpdatedBlockNumber() external view returns (uint); /** * @return The off-chain assets job ID for getting all assets. NOTE this will be broken down by asset introducer * (token ID) in the future so this function will be deprecated. */ function offChainAssetsValueJobId() external view returns (bytes32); /** * @dev Gets the DMM ecosystem's collateral's value from Chainlink's on-chain data feed. * * @return The value of all of the ecosystem's collateral, as a number with 18 decimals */ function getOffChainAssetsValue() external view returns (uint); /** * @dev Gets the DMM ecosystem's collateral's value from Chainlink's on-chain data feed. * * @param tokenId The ID of the asset introducer whose assets should be valued or use 0 to denote all introducers. * @return The value of the asset introducer's ecosystem collateral, as a number with 18 decimals. */ function getOffChainAssetsValueByTokenId( uint tokenId ) external view returns (uint); /** * @param tokenId The token ID of the asset introducer; 0 to denote all of them * @param assetType The asset type for the collateral (lien) held by the DMM DAO * @return True if the asset type is supported, or false otherwise */ function isSupportedAssetTypeByAssetIntroducer( uint tokenId, string calldata assetType ) external view returns (bool); /** * @return All of the different asset types that can be used by the DMM Ecosystem. */ function getAllAssetTypes() external view returns (string[] memory); } // File: contracts/protocol/impl/AtmLike.sol /* * Copyright 2020 DMM Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.5.0; contract AtmLike is Ownable { using SafeERC20 for IERC20; function deposit(address token, uint amount) public onlyOwner { IERC20(token).safeTransferFrom(_msgSender(), address(this), amount); } function withdraw(address token, address recipient, uint amount) public onlyOwner { IERC20(token).safeTransfer(recipient, amount); } } // File: chainlink/v0.5/contracts/vendor/Buffer.sol pragma solidity ^0.5.0; /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library Buffer { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } // File: chainlink/v0.5/contracts/vendor/CBOR.sol pragma solidity ^0.5.0; library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.appendUint8(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.appendUint8(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.appendUint8(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.appendUint8(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.appendUint8(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes 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); } } // File: chainlink/v0.5/contracts/Chainlink.sol pragma solidity ^0.5.0; /** * @title Library for common Chainlink functions * @dev Uses imported CBOR library for encoding to buffer */ library Chainlink { uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase using CBOR for Buffer.buffer; struct Request { bytes32 id; address callbackAddress; bytes4 callbackFunctionId; uint256 nonce; Buffer.buffer buf; } /** * @notice Initializes a Chainlink request * @dev Sets the ID, callback address, and callback function signature on the request * @param self The uninitialized request * @param _id The Job Specification ID * @param _callbackAddress The callback address * @param _callbackFunction The callback function signature * @return The initialized request */ function initialize( Request memory self, bytes32 _id, address _callbackAddress, bytes4 _callbackFunction ) internal pure returns (Chainlink.Request memory) { Buffer.init(self.buf, defaultBufferSize); self.id = _id; self.callbackAddress = _callbackAddress; self.callbackFunctionId = _callbackFunction; return self; } /** * @notice Sets the data for the buffer without encoding CBOR on-chain * @dev CBOR can be closed with curly-brackets {} or they can be left off * @param self The initialized request * @param _data The CBOR data */ function setBuffer(Request memory self, bytes memory _data) internal pure { Buffer.init(self.buf, _data.length); Buffer.append(self.buf, _data); } /** * @notice Adds a string value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The string value to add */ function add(Request memory self, string memory _key, string memory _value) internal pure { self.buf.encodeString(_key); self.buf.encodeString(_value); } /** * @notice Adds a bytes value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The bytes value to add */ function addBytes(Request memory self, string memory _key, bytes memory _value) internal pure { self.buf.encodeString(_key); self.buf.encodeBytes(_value); } /** * @notice Adds a int256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The int256 value to add */ function addInt(Request memory self, string memory _key, int256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeInt(_value); } /** * @notice Adds a uint256 value to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _value The uint256 value to add */ function addUint(Request memory self, string memory _key, uint256 _value) internal pure { self.buf.encodeString(_key); self.buf.encodeUInt(_value); } /** * @notice Adds an array of strings to the request with a given key name * @param self The initialized request * @param _key The name of the key * @param _values The array of string values to add */ function addStringArray(Request memory self, string memory _key, string[] memory _values) internal pure { self.buf.encodeString(_key); self.buf.startArray(); for (uint256 i = 0; i < _values.length; i++) { self.buf.encodeString(_values[i]); } self.buf.endSequence(); } } // File: chainlink/v0.5/contracts/interfaces/ENSInterface.sol pragma solidity ^0.5.0; interface ENSInterface { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address _owner) external; function setResolver(bytes32 node, address _resolver) external; function setOwner(bytes32 node, address _owner) external; function setTTL(bytes32 node, uint64 _ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } // File: chainlink/v0.5/contracts/interfaces/LinkTokenInterface.sol pragma solidity ^0.5.0; interface LinkTokenInterface { function allowance(address owner, address spender) external returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external returns (uint256 balance); function decimals() external returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external returns (string memory tokenName); function symbol() external returns (string memory tokenSymbol); function totalSupply() external returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // File: chainlink/v0.5/contracts/interfaces/ChainlinkRequestInterface.sol pragma solidity ^0.5.0; interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 requestPrice, bytes32 serviceAgreementID, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 dataVersion, // Currently unused, always "1" bytes calldata data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } // File: chainlink/v0.5/contracts/interfaces/PointerInterface.sol pragma solidity ^0.5.0; interface PointerInterface { function getAddress() external view returns (address); } // File: chainlink/v0.5/contracts/vendor/ENSResolver.sol pragma solidity ^0.5.0; contract ENSResolver { function addr(bytes32 node) public view returns (address); } // File: chainlink/v0.5/contracts/vendor/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ // File: chainlink/v0.5/contracts/ChainlinkClient.sol pragma solidity ^0.5.0; /** * @title The ChainlinkClient contract * @notice Contract writers can inherit this contract in order to create requests for the * Chainlink network */ contract ChainlinkClient { using Chainlink for Chainlink.Request; using SafeMath for uint256; uint256 constant internal LINK = 10**18; uint256 constant private AMOUNT_OVERRIDE = 0; address constant private SENDER_OVERRIDE = address(0); uint256 constant private ARGS_VERSION = 1; bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle"); address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; ENSInterface private ens; bytes32 private ensNode; LinkTokenInterface private link; ChainlinkRequestInterface private oracle; uint256 private requestCount = 1; mapping(bytes32 => address) private pendingRequests; event ChainlinkRequested(bytes32 indexed id); event ChainlinkFulfilled(bytes32 indexed id); event ChainlinkCancelled(bytes32 indexed id); /** * @notice Creates a request that can hold additional parameters * @param _specId The Job Specification ID that the request will be created for * @param _callbackAddress The callback address that the response will be sent to * @param _callbackFunctionSignature The callback function signature to use for the callback address * @return A Chainlink Request struct in memory */ function buildChainlinkRequest( bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionSignature ) internal pure returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev Calls `chainlinkRequestTo` with the stored oracle address * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return The request ID */ function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32) { return sendChainlinkRequestTo(address(oracle), _req, _payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param _oracle The address of the oracle for the request * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return The request ID */ function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, requestCount)); _req.nonce = requestCount; pendingRequests[requestId] = _oracle; emit ChainlinkRequested(requestId); require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle"); requestCount += 1; return requestId; } /** * @notice Allows a request to be cancelled if it has not been fulfilled * @dev Requires keeping track of the expiration value emitted from the oracle contract. * Deletes the request from the `pendingRequests` mapping. * Emits ChainlinkCancelled event. * @param _requestId The request ID * @param _payment The amount of LINK sent for the request * @param _callbackFunc The callback function specified for the request * @param _expiration The time of the expiration for the request */ function cancelChainlinkRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal { ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]); delete pendingRequests[_requestId]; emit ChainlinkCancelled(_requestId); requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration); } /** * @notice Sets the stored oracle address * @param _oracle The address of the oracle contract */ function setChainlinkOracle(address _oracle) internal { oracle = ChainlinkRequestInterface(_oracle); } /** * @notice Sets the LINK token address * @param _link The address of the LINK token contract */ function setChainlinkToken(address _link) internal { link = LinkTokenInterface(_link); } /** * @notice Sets the Chainlink token address for the public * network as given by the Pointer contract */ function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } /** * @notice Retrieves the stored address of the LINK token * @return The address of the LINK token */ function chainlinkTokenAddress() internal view returns (address) { return address(link); } /** * @notice Retrieves the stored address of the oracle contract * @return The address of the oracle contract */ function chainlinkOracleAddress() internal view returns (address) { return address(oracle); } /** * @notice Allows for a request which was created on another contract to be fulfilled * on this contract * @param _oracle The address of the oracle contract that will fulfill the request * @param _requestId The request ID used for the response */ function addChainlinkExternalRequest(address _oracle, bytes32 _requestId) internal notPendingRequest(_requestId) { pendingRequests[_requestId] = _oracle; } /** * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS * @dev Accounts for subnodes having different resolvers * @param _ens The address of the ENS contract * @param _node The ENS node hash */ function useChainlinkWithENS(address _ens, bytes32 _node) internal { ens = ENSInterface(_ens); ensNode = _node; bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME)); ENSResolver resolver = ENSResolver(ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } /** * @notice Sets the stored oracle contract with the address resolved by ENS * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously */ function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME)); ENSResolver resolver = ENSResolver(ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } /** * @notice Encodes the request to be sent to the oracle contract * @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types * will be validated in the oracle contract. * @param _req The initialized Chainlink Request * @return The bytes payload for the `transferAndCall` method */ function encodeRequest(Chainlink.Request memory _req) private view returns (bytes memory) { return abi.encodeWithSelector( oracle.oracleRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent _req.id, _req.callbackAddress, _req.callbackFunctionId, _req.nonce, ARGS_VERSION, _req.buf.buf); } /** * @notice Ensures that the fulfillment is valid for this contract * @dev Use if the contract developer prefers methods instead of modifiers for validation * @param _requestId The request ID for fulfillment */ function validateChainlinkCallback(bytes32 _requestId) internal recordChainlinkFulfillment(_requestId) // solhint-disable-next-line no-empty-blocks {} /** * @dev Reverts if the sender is not the oracle of the request. * Emits ChainlinkFulfilled event. * @param _requestId The request ID for fulfillment */ modifier recordChainlinkFulfillment(bytes32 _requestId) { require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request"); delete pendingRequests[_requestId]; emit ChainlinkFulfilled(_requestId); _; } /** * @dev Reverts if the request is already pending * @param _requestId The request ID for fulfillment */ modifier notPendingRequest(bytes32 _requestId) { require(pendingRequests[_requestId] == address(0), "Request is already pending"); _; } } // File: contracts/external/chainlink/UpgradeableChainlinkClient.sol pragma solidity ^0.5.0; /** * @title The ChainlinkClient contract * @notice Contract writers can inherit this contract in order to create requests for the Chainlink network. This file * is a copy/paste of the original Chainlink Client from the SDK to ensure that the state variables, their respective * names, and positions do not change. */ contract UpgradeableChainlinkClient { using Chainlink for Chainlink.Request; using SafeMath for uint256; uint256 constant internal LINK = 10 ** 18; uint256 constant private AMOUNT_OVERRIDE = 0; address constant private SENDER_OVERRIDE = address(0); uint256 constant private ARGS_VERSION = 1; bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link"); bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle"); address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571; // ****************************** // ***** DO NOT CHANGE OR MOVE // ****************************** ENSInterface private ens; bytes32 private ensNode; LinkTokenInterface private link; ChainlinkRequestInterface private oracle; uint256 private requestCount = 1; mapping(bytes32 => address) private pendingRequests; // ****************************** // ***** DO NOT CHANGE OR MOVE // ****************************** event ChainlinkRequested(bytes32 indexed id); event ChainlinkFulfilled(bytes32 indexed id); event ChainlinkCancelled(bytes32 indexed id); /** * @notice Creates a request that can hold additional parameters * @param _specId The Job Specification ID that the request will be created for * @param _callbackAddress The callback address that the response will be sent to * @param _callbackFunctionSignature The callback function signature to use for the callback address * @return A Chainlink Request struct in memory */ function buildChainlinkRequest( bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionSignature ) internal pure returns (Chainlink.Request memory) { Chainlink.Request memory req; return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature); } /** * @notice Creates a Chainlink request to the stored oracle address * @dev Calls `chainlinkRequestTo` with the stored oracle address * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return The request ID */ function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32) { return sendChainlinkRequestTo(address(oracle), _req, _payment); } /** * @notice Creates a Chainlink request to the specified oracle address * @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to * send LINK which creates a request on the target oracle contract. * Emits ChainlinkRequested event. * @param _oracle The address of the oracle for the request * @param _req The initialized Chainlink Request * @param _payment The amount of LINK to send for the request * @return The request ID */ function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment) internal returns (bytes32 requestId) { requestId = keccak256(abi.encodePacked(this, requestCount)); _req.nonce = requestCount; pendingRequests[requestId] = _oracle; emit ChainlinkRequested(requestId); require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle"); requestCount += 1; return requestId; } /** * @notice Allows a request to be cancelled if it has not been fulfilled * @dev Requires keeping track of the expiration value emitted from the oracle contract. * Deletes the request from the `pendingRequests` mapping. * Emits ChainlinkCancelled event. * @param _requestId The request ID * @param _payment The amount of LINK sent for the request * @param _callbackFunc The callback function specified for the request * @param _expiration The time of the expiration for the request */ function cancelChainlinkRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal { ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]); delete pendingRequests[_requestId]; emit ChainlinkCancelled(_requestId); requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration); } /** * @notice Sets the stored oracle address * @param _oracle The address of the oracle contract */ function setChainlinkOracle(address _oracle) internal { oracle = ChainlinkRequestInterface(_oracle); } /** * @notice Sets the LINK token address * @param _link The address of the LINK token contract */ function setChainlinkToken(address _link) internal { link = LinkTokenInterface(_link); } /** * @notice Sets the Chainlink token address for the public * network as given by the Pointer contract */ function setPublicChainlinkToken() internal { setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress()); } /** * @notice Retrieves the stored address of the LINK token * @return The address of the LINK token */ function chainlinkTokenAddress() internal view returns (address) { return address(link); } /** * @notice Retrieves the stored address of the oracle contract * @return The address of the oracle contract */ function chainlinkOracleAddress() internal view returns (address) { return address(oracle); } /** * @notice Allows for a request which was created on another contract to be fulfilled * on this contract * @param _oracle The address of the oracle contract that will fulfill the request * @param _requestId The request ID used for the response */ function addChainlinkExternalRequest(address _oracle, bytes32 _requestId) internal notPendingRequest(_requestId) { pendingRequests[_requestId] = _oracle; } /** * @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS * @dev Accounts for subnodes having different resolvers * @param _ens The address of the ENS contract * @param _node The ENS node hash */ function useChainlinkWithENS(address _ens, bytes32 _node) internal { ens = ENSInterface(_ens); ensNode = _node; bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME)); ENSResolver resolver = ENSResolver(ens.resolver(linkSubnode)); setChainlinkToken(resolver.addr(linkSubnode)); updateChainlinkOracleWithENS(); } /** * @notice Sets the stored oracle contract with the address resolved by ENS * @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously */ function updateChainlinkOracleWithENS() internal { bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME)); ENSResolver resolver = ENSResolver(ens.resolver(oracleSubnode)); setChainlinkOracle(resolver.addr(oracleSubnode)); } /** * @notice Encodes the request to be sent to the oracle contract * @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types * will be validated in the oracle contract. * @param _req The initialized Chainlink Request * @return The bytes payload for the `transferAndCall` method */ function encodeRequest(Chainlink.Request memory _req) private view returns (bytes memory) { return abi.encodeWithSelector( oracle.oracleRequest.selector, SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent _req.id, _req.callbackAddress, _req.callbackFunctionId, _req.nonce, ARGS_VERSION, _req.buf.buf); } /** * @notice Ensures that the fulfillment is valid for this contract * @dev Use if the contract developer prefers methods instead of modifiers for validation * @param _requestId The request ID for fulfillment */ function validateChainlinkCallback(bytes32 _requestId) internal recordChainlinkFulfillment(_requestId) // solhint-disable-next-line no-empty-blocks {} /** * @dev Reverts if the sender is not the oracle of the request. * Emits ChainlinkFulfilled event. * @param _requestId The request ID for fulfillment */ modifier recordChainlinkFulfillment(bytes32 _requestId) { require(msg.sender == pendingRequests[_requestId], "Source must be the oracle of the request"); delete pendingRequests[_requestId]; emit ChainlinkFulfilled(_requestId); _; } /** * @dev Reverts if the request is already pending * @param _requestId The request ID for fulfillment */ modifier notPendingRequest(bytes32 _requestId) { require(pendingRequests[_requestId] == address(0), "Request is already pending"); _; } } // File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ 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; } // File: contracts/protocol/interfaces/IOwnableOrGuardian.sol /* * Copyright 2020 DMM Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.5.0; /** * NOTE: THE STATE VARIABLES IN THIS CONTRACT CANNOT CHANGE NAME OR POSITION BECAUSE THIS CONTRACT IS USED IN * UPGRADEABLE CONTRACTS. */ contract IOwnableOrGuardian is Initializable { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event GuardianTransferred(address indexed previousGuardian, address indexed newGuardian); modifier onlyOwnerOrGuardian { require( msg.sender == _owner || msg.sender == _guardian, "OwnableOrGuardian: UNAUTHORIZED_OWNER_OR_GUARDIAN" ); _; } modifier onlyOwner { require( msg.sender == _owner, "OwnableOrGuardian: UNAUTHORIZED" ); _; } // ********************************************* // ***** State Variables DO NOT CHANGE OR MOVE // ********************************************* // ****************************** // ***** DO NOT CHANGE OR MOVE // ****************************** address internal _owner; address internal _guardian; // ****************************** // ***** DO NOT CHANGE OR MOVE // ****************************** // ****************************** // ***** Misc Functions // ****************************** function owner() external view returns (address) { return _owner; } function guardian() external view returns (address) { return _guardian; } // ****************************** // ***** Admin Functions // ****************************** function initialize( address owner, address guardian ) public initializer { _transferOwnership(owner); _transferGuardian(guardian); } function transferOwnership( address owner ) public onlyOwner { require( owner != address(0), "OwnableOrGuardian::transferOwnership: INVALID_OWNER" ); _transferOwnership(owner); } function renounceOwnership() public onlyOwner { _transferOwnership(address(0)); } function transferGuardian( address guardian ) public onlyOwner { require( guardian != address(0), "OwnableOrGuardian::transferGuardian: INVALID_OWNER" ); _transferGuardian(guardian); } function renounceGuardian() public onlyOwnerOrGuardian { _transferGuardian(address(0)); } // ****************************** // ***** Internal Functions // ****************************** function _transferOwnership( address owner ) internal { address previousOwner = _owner; _owner = owner; emit OwnershipTransferred(previousOwner, owner); } function _transferGuardian( address guardian ) internal { address previousGuardian = _guardian; _guardian = guardian; emit GuardianTransferred(previousGuardian, guardian); } } // File: contracts/protocol/impl/OwnableOrGuardian.sol /* * Copyright 2020 DMM Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.5.0; /** * NOTE: THE STATE VARIABLES IN THIS CONTRACT CANNOT CHANGE NAME OR POSITION BECAUSE THIS CONTRACT IS USED IN * UPGRADEABLE CONTRACTS. */ contract OwnableOrGuardian is IOwnableOrGuardian { constructor( address owner, address guardian ) public { IOwnableOrGuardian.initialize(owner, guardian); } } // File: contracts/protocol/impl/data/OffChainAssetValuatorData.sol /* * Copyright 2020 DMM Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.5.0; contract OffChainAssetValuatorData is IOwnableOrGuardian, UpgradeableChainlinkClient { using SafeERC20 for IERC20; // **************************************** // ***** State Variables - DO NOT MODIFY // **************************************** /// The amount of LINK to be paid per request uint internal _oraclePayment; /// The job ID that's fired on the LINK nodes to fulfill this contract's need for off-chain data bytes32 internal _offChainAssetsValueJobId; /// The value of all off-chain collateral, as determined by Chainlink. This number has 18 decimal places of precision. uint internal _offChainAssetsValue; /// The timestamp (in Unix seconds) at which this contract's _offChainAssetsValue field was last updated. uint internal _lastUpdatedTimestamp; /// The block number at which this contract's _offChainAssetsValue field was last updated. uint internal _lastUpdatedBlockNumber; /// All of the supported asset types bytes32[] internal _allAssetTypes; /// All of the supported asset types, represented as a mapping mapping(bytes32 => uint) internal _assetTypeToNumberOfUsesMap; /// A mapping from asset introducer (token ID) to an asset type, to whether or not it's supported. mapping(uint => mapping(bytes32 => bool)) internal _assetIntroducerToAssetTypeToIsSupportedMap; // ************************* // ***** Functions // ************************* function deposit(address token, uint amount) public onlyOwnerOrGuardian { IERC20(token).safeTransferFrom(msg.sender, address(this), amount); } function withdraw(address token, address recipient, uint amount) public onlyOwnerOrGuardian { IERC20(token).safeTransfer(recipient, amount); } } // File: contracts/protocol/impl/OffChainAssetValuatorImplV2.sol /* * Copyright 2020 DMM Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.5.0; contract OffChainAssetValuatorImplV2 is IOffChainAssetValuatorV2, OffChainAssetValuatorData { // ************************* // ***** Admin Functions // ************************* function initialize( address owner, address guardian, address linkToken, uint oraclePayment, uint offChainAssetsValue, bytes32 offChainAssetsValueJobId ) external initializer { IOwnableOrGuardian.initialize(owner, guardian); setChainlinkToken(linkToken); _oraclePayment = oraclePayment; _offChainAssetsValueJobId = offChainAssetsValueJobId; _offChainAssetsValue = offChainAssetsValue; _lastUpdatedTimestamp = block.timestamp; _lastUpdatedBlockNumber = block.number; } function addSupportedAssetTypeByTokenId( uint tokenId, string calldata assetType ) external onlyOwnerOrGuardian { bytes32 bytesAssetType = _sanitizeAndConvertAssetTypeToBytes(assetType); require( !_assetIntroducerToAssetTypeToIsSupportedMap[tokenId][bytesAssetType], "OffChainAssetValuatorImplV2::addSupportedAssetTypeByTokenId: ALREADY_SUPPORTED" ); uint numberOfUses = _assetTypeToNumberOfUsesMap[bytesAssetType]; if (numberOfUses == 0) { _allAssetTypes.push(bytesAssetType); } _assetTypeToNumberOfUsesMap[bytesAssetType] = numberOfUses.add(1); _assetIntroducerToAssetTypeToIsSupportedMap[tokenId][bytesAssetType] = true; emit AssetTypeSet(tokenId, assetType, true); } function removeSupportedAssetTypeByTokenId( uint tokenId, string calldata assetType ) onlyOwnerOrGuardian external { bytes32 bytesAssetType = _sanitizeAndConvertAssetTypeToBytes(assetType); require( _assetIntroducerToAssetTypeToIsSupportedMap[tokenId][bytesAssetType], "OffChainAssetValuatorImplV2::addSupportedAssetTypeByTokenId: NOT_SUPPORTED" ); uint numberOfUses = _assetTypeToNumberOfUsesMap[bytesAssetType]; if (numberOfUses == 1) { // We no longer support it. Remove it. bytes32[] memory allAssetTypes = _allAssetTypes; for (uint i = 0; i < allAssetTypes.length; i++) { if (allAssetTypes[i] == bytesAssetType) { delete _allAssetTypes[i]; break; } } } _assetTypeToNumberOfUsesMap[bytesAssetType] = numberOfUses.sub(1); _assetIntroducerToAssetTypeToIsSupportedMap[tokenId][bytesAssetType] = false; emit AssetTypeSet(tokenId, assetType, false); } function setCollateralValueJobId( bytes32 offChainAssetsValueJobId ) public onlyOwnerOrGuardian { _offChainAssetsValueJobId = offChainAssetsValueJobId; } function setOraclePayment( uint oraclePayment ) public onlyOwnerOrGuardian { _oraclePayment = oraclePayment; } function submitGetOffChainAssetsValueRequest( address oracle ) public onlyOwnerOrGuardian { Chainlink.Request memory request = buildChainlinkRequest( _offChainAssetsValueJobId, address(this), this.fulfillGetOffChainAssetsValueRequest.selector ); request.add("action", "sumActive"); request.addInt("times", 1 ether); sendChainlinkRequestTo(oracle, request, _oraclePayment); } function fulfillGetOffChainAssetsValueRequest( bytes32 requestId, uint offChainAssetsValue ) public recordChainlinkFulfillment(requestId) { _offChainAssetsValue = offChainAssetsValue; _lastUpdatedTimestamp = block.timestamp; _lastUpdatedBlockNumber = block.number; emit AssetsValueUpdated(offChainAssetsValue); } // ************************* // ***** Misc Functions // ************************* function oraclePayment() external view returns (uint) { return _oraclePayment; } function lastUpdatedTimestamp() external view returns (uint) { return _lastUpdatedTimestamp; } function lastUpdatedBlockNumber() external view returns (uint) { return _lastUpdatedBlockNumber; } function offChainAssetsValueJobId() external view returns (bytes32) { return _offChainAssetsValueJobId; } function getOffChainAssetsValue() external view returns (uint) { return _offChainAssetsValue; } function getOffChainAssetsValueByTokenId( uint tokenId ) external view returns (uint) { if (tokenId == 0) { return _offChainAssetsValue; } else { revert("OffChainAssetValuatorImplV2::getOffChainAssetsValueByTokenId NOT_IMPLEMENTED"); } } function isSupportedAssetTypeByAssetIntroducer( uint tokenId, string calldata assetType ) external view returns (bool) { bytes32 bytesAssetType = _sanitizeAndConvertAssetTypeToBytes(assetType); return _assetIntroducerToAssetTypeToIsSupportedMap[0][bytesAssetType] || _assetIntroducerToAssetTypeToIsSupportedMap[tokenId][bytesAssetType]; } function getAllAssetTypes() external view returns (string[] memory) { bytes32[] memory allAssetTypes = _allAssetTypes; string[] memory result = new string[](allAssetTypes.length); for (uint i = 0; i < allAssetTypes.length; i++) { result[i] = string(abi.encodePacked(allAssetTypes[i])); } return result; } // ************************* // ***** Internal Functions // ************************* function _sanitizeAndConvertAssetTypeToBytes( string memory assetType ) internal pure returns (bytes32 bytesAssetType) { require( bytes(assetType).length <= 32, "OffChainAssetValuatorImplV2::_sanitizeAndConvertAssetTypeString: INVALID_LENGTH" ); assembly { bytesAssetType := mload(add(assetType, 32)) } } }
Allows a request to be cancelled if it has not been fulfilled Requires keeping track of the expiration value emitted from the oracle contract. Deletes the request from the `pendingRequests` mapping. Emits ChainlinkCancelled event. _requestId The request ID _payment The amount of LINK sent for the request _callbackFunc The callback function specified for the request _expiration The time of the expiration for the request/
function cancelChainlinkRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) internal { ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]); delete pendingRequests[_requestId]; emit ChainlinkCancelled(_requestId); requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration); }
1,262,272
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "./@rarible/royalties/contracts/impl/RoyaltiesV2Impl.sol"; import "./@rarible/royalties/contracts/LibPart.sol"; import "./@rarible/royalties/contracts/LibRoyaltiesV2.sol"; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a creator role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * 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 creator and pauser * roles, as well as the default admin role, which will let it grant both creator * and pauser roles to other accounts. */ contract Creatify is Context, AccessControlEnumerable, ERC721Enumerable, ERC721Burnable, ERC721Pausable, RoyaltiesV2Impl { using Counters for Counters.Counter; bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; bytes32 public constant CREATIFY_ADMIN_ROLE = keccak256("CREATIFY_ADMIN_ROLE"); bytes32 public constant CREATIFY_OPERATOR_ROLE = keccak256("CREATIFY_OPERATOR_ROLE"); bytes32 public constant CREATIFY_CREATOR_ROLE = keccak256("CREATIFY_CREATOR_ROLE"); Counters.Counter private _tokenIdTracker; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; address public marketplace; event ArtifactCreated( uint256 tokenID, address indexed creator, string metaDataUri ); using Strings for uint256; /** * @dev Grants `CREATIFY_ADMIN_ROLE`, `CREATIFY_CREATOR_ROLE` and `CREATIFY_OPERATOR_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor( string memory name, string memory symbol, address marketplaceAddress ) ERC721(name, symbol) { _setupRole(CREATIFY_ADMIN_ROLE, _msgSender()); marketplace = marketplaceAddress; _setRoleAdmin(CREATIFY_ADMIN_ROLE, CREATIFY_ADMIN_ROLE); _setRoleAdmin(CREATIFY_CREATOR_ROLE, CREATIFY_OPERATOR_ROLE); _setRoleAdmin(CREATIFY_OPERATOR_ROLE, CREATIFY_ADMIN_ROLE); } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_safeMint}. * * Requirements: * * - the caller must have the `CREATIFY_CREATOR_ROLE`. */ function createArtifact(string memory metadataHash) public onlyRole(CREATIFY_CREATOR_ROLE) returns (uint256) { // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _tokenIdTracker.increment(); uint256 currentTokenID = _tokenIdTracker.current(); _safeMint(_msgSender(), currentTokenID); _setTokenURI(currentTokenID, metadataHash); // Approve marketplace to transfer NFTs setApprovalForAll(marketplace, true); emit ArtifactCreated( currentTokenID, _msgSender(), tokenURI(currentTokenID) ); return currentTokenID; } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_safeMint}. * * Requirements: * * - the caller must have the `CREATIFY_CREATOR_ROLE`. */ function delegateArtifactCreation( address creator, string memory metadataHash ) public onlyRole(CREATIFY_OPERATOR_ROLE) returns (uint256) { // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _tokenIdTracker.increment(); uint256 currentTokenID = _tokenIdTracker.current(); _safeMint(creator, currentTokenID); _setTokenURI(currentTokenID, metadataHash); // Approve marketplace to transfer NFTs setApprovalForAll(marketplace, true); emit ArtifactCreated(currentTokenID, creator, metadataHash); return currentTokenID; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Creatify: Non-Existent Artifact"); string memory _tokenURI = _tokenURIs[tokenId]; return _tokenURI; } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "Creatify: Non-Existent Artifact"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `CREATIFY_OPERATOR_ROLE`. */ function pause() public onlyRole(CREATIFY_OPERATOR_ROLE) { _pause(); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { LibPart.Part[] memory _royalties = royalties[_tokenId]; if (_royalties.length > 0) { return ( _royalties[0].account, (_salePrice * _royalties[0].value) / 10000 ); } return (address(0), 0); } function setRoyalties( uint256 _tokenId, address payable _royaltiesReceipientAddress, uint96 _percentageBasisPoints ) public onlyRole(CREATIFY_ADMIN_ROLE) { LibPart.Part[] memory _royalties = new LibPart.Part[](1); _royalties[0].value = _percentageBasisPoints; _royalties[0].account = _royaltiesReceipientAddress; _saveRoyalties(_tokenId, _royalties); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `CREATIFY_OPERATOR_ROLE`. */ function unpause() public onlyRole(CREATIFY_OPERATOR_ROLE) { _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) { if (interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES) { return true; } if (interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(interfaceId); } }
See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721, ERC721Enumerable) returns (bool) { if (interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES) { return true; } if (interfaceId == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(interfaceId); }
7,241,088
./partial_match/1/0x5638C146B1BA9e47EF62206B0f21d818A59f626c/sources/ESP.sol
Calculate bonus Suns for a new stake, if any newStakedSuns Number of Suns to stake newStakedDays Number of days to stake// Must be more than 1 day for Longer-Pays-Better /
function _stakeStartBonusSuns(uint256 newStakedSuns, uint256 newStakedDays) private pure returns (uint256 bonusSuns) { LONGER PAYS BETTER: If longer than 1 day stake is committed to, each extra day gives bonus shares of approximately 0.0548%, which is approximately 20% extra per year of increased stake length committed to, but capped to a maximum of 200% extra. extraDays = stakedDays - 1 longerBonus% = (extraDays / 364) * 20% = (extraDays / 364) / 5 = extraDays / 1820 = extraDays / LPB extraDays = longerBonus% * 1820 extraDaysMax = longerBonusMax% * 1820 = 200% * 1820 = 3640 = LPB_MAX_DAYS BIGGER PAYS BETTER: Bonus percentage scaled 0% to 10% for the first 7M ESP of stake. biggerBonus% = (cappedSuns / BPB_MAX_SUNS) * 10% = (cappedSuns / BPB_MAX_SUNS) / 10 = cappedSuns / (BPB_MAX_SUNS * 10) = cappedSuns / BPB COMBINED: combinedBonus% = longerBonus% + biggerBonus% cappedExtraDays cappedSuns = --------------- + ------------ LPB BPB cappedExtraDays * BPB cappedSuns * LPB = --------------------- + ------------------ LPB * BPB LPB * BPB cappedExtraDays * BPB + cappedSuns * LPB = -------------------------------------------- LPB * BPB bonusSuns = suns * combinedBonus% = suns * (cappedExtraDays * BPB + cappedSuns * LPB) / (LPB * BPB) uint256 cappedExtraDays = 0; if (newStakedDays > 1) { cappedExtraDays = newStakedDays <= LPB_MAX_DAYS ? newStakedDays - 1 : LPB_MAX_DAYS; } uint256 cappedStakedSuns = newStakedSuns <= BPB_MAX_SUNS ? newStakedSuns : BPB_MAX_SUNS; bonusSuns = cappedExtraDays * BPB + cappedStakedSuns * LPB; bonusSuns = newStakedSuns * bonusSuns / (LPB * BPB); return bonusSuns; }
11,027,585
pragma solidity ^0.4.19; // 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; 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; } } // File: contracts/Administrable.sol contract Administrable is Ownable { mapping (address => bool) private administrators; uint256 public administratorsLength = 0; /** * @dev Throws if called by any account other than the owner or administrator. */ modifier onlyAdministratorOrOwner() { require(msg.sender == owner || administrators[msg.sender]); _; } function addAdministrator(address _wallet) onlyOwner public { require(!administrators[_wallet]); require(_wallet != address(0) && _wallet != owner); administrators[_wallet] = true; administratorsLength++; } function removeAdministrator(address _wallet) onlyOwner public { require(_wallet != address(0)); require(administrators[_wallet]); administrators[_wallet] = false; administratorsLength--; } function isAdministrator(address _wallet) public constant returns (bool) { return administrators[_wallet]; } } // File: contracts/FreezableToken.sol /** * @title Freezable Token * @dev Token that can be freezed for chosen token holder. */ contract FreezableToken is Administrable { mapping (address => bool) public frozenList; event FrozenFunds(address indexed wallet, bool frozen); /** * @dev Owner can freeze the token balance for chosen token holder. * @param _wallet The address of token holder whose tokens to be frozen. */ function freezeAccount(address _wallet) onlyAdministratorOrOwner public { require(_wallet != address(0)); frozenList[_wallet] = true; FrozenFunds(_wallet, true); } /** * @dev Owner can unfreeze the token balance for chosen token holder. * @param _wallet The address of token holder whose tokens to be unfrozen. */ function unfreezeAccount(address _wallet) onlyAdministratorOrOwner public { require(_wallet != address(0)); frozenList[_wallet] = false; FrozenFunds(_wallet, false); } /** * @dev Check the specified token holder whether his/her token balance is frozen. * @param _wallet The address of token holder to check. */ function isFrozen(address _wallet) constant public returns (bool) { return frozenList[_wallet]; } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @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); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @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); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @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&#39;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; } } // File: contracts/MintableToken.sol /** * @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, Administrable { 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) onlyAdministratorOrOwner 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; } } // File: contracts/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Administrable { 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() onlyAdministratorOrOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyAdministratorOrOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } // File: contracts/OncoToken.sol contract OncoToken is MintableToken, Pausable, FreezableToken, BurnableToken { string constant public name = "ONCO"; string constant public symbol = "ONCO"; uint8 constant public decimals = 18; /** * @dev Empty OncoToken constructor */ function OncoToken() public {} /** * @dev Transfer token for a specified address with pause and freeze features for owner. * @dev Only applies when the transfer is allowed by the owner. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) whenNotPaused public returns (bool) { require(!isFrozen(msg.sender)); super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another with pause and freeze features for owner. * @dev Only applies when the transfer is allowed by the owner. * @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) whenNotPaused public returns (bool) { require(!isFrozen(msg.sender)); require(!isFrozen(_from)); super.transferFrom(_from, _to, _value); } }
Transfer tokens from one address to another with pause and freeze features for owner. Only applies when the transfer is allowed by the owner. _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused public returns (bool) { require(!isFrozen(msg.sender)); require(!isFrozen(_from)); super.transferFrom(_from, _to, _value); }
15,111,966
./full_match/4/0xAd8d2D5Fa5B33704f290c37BFb13fFa1dc31a257/sources/contracts/interfaces/dydx/ICallee.sol
ICallee dYdX Interface that Callees for Solo must implement in order to ingest data./ ============ Public Functions ============
interface ICallee { function callFunction( address sender, Account.Info calldata accountInfo, bytes calldata data ) external; pragma solidity ^0.8; import {Account} from "./ISoloMargin.sol"; }
12,476,160
pragma solidity ^0.5.16; // Inheritance import "./access/LimitedSetup.sol"; import "./SynthetixState.sol"; // Internal References import "./interfaces/IFeePool.sol"; // https://docs.synthetix.io/contracts/source/contracts/synthetixstate contract SynthetixStateWithLimitedSetup is SynthetixState, LimitedSetup { IFeePool public feePool; // Import state uint public importedDebtAmount; constructor(address _owner, address _associatedContract) public SynthetixState(_owner, _associatedContract) LimitedSetup(1 weeks) {} /* ========== SETTERS ========== */ /** * @notice set the FeePool contract as it is the only authority to be able to call * appendVestingEntry with the onlyFeePool modifer */ function setFeePool(IFeePool _feePool) external onlyOwner { feePool = _feePool; emit FeePoolUpdated(address(_feePool)); } // /** // * @notice Import issuer data // * @dev Only callable by the contract owner, and only for 1 week after deployment. // */ function importIssuerData(address[] calldata accounts, uint[] calldata sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } // /** // * @notice Import issuer debt data // * @dev Only used from importIssuerData above, meant to be disposable // */ function _addToDebtRegister(address account, uint amount) internal { // What is the value that we've previously imported? uint totalDebtIssued = importedDebtAmount; // What will the new total be including the new value? uint newTotalDebtIssued = amount.add(totalDebtIssued); // Save that for the next import. importedDebtAmount = newTotalDebtIssued; // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // We ignore any existingDebt as this is being imported in as amount // Are they a new issuer? If so, record them. (same as incrementTotalIssuerCount) if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } // Save the debt entry parameters (same as setCurrentIssuanceData) issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (debtLedger.length > 0) { debtLedger.push(debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta)); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } // append issuanceData to FeePoolState feePool.appendAccountIssuanceRecord( account, issuanceData[account].initialDebtOwnership, issuanceData[account].debtEntryIndex ); } /* ========== EVENTS ========== */ event FeePoolUpdated(address newFeePool); }
/ Import issuer data Only callable by the contract owner, and only for 1 week after deployment. /
function importIssuerData(address[] calldata accounts, uint[] calldata sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } }
12,710,163
./partial_match/1/0xAe46E888aF6318aED82FE715b1b98b78F74e7b65/sources/LiquidityPoolV1Converter.sol
returns the number of decimal digits in a given positive integer _x positive integer return the number of decimal digits in the given positive integer/
function decimalLength(uint256 _x) internal pure returns (uint256) { uint256 y = 0; for (uint256 x = _x; x > 0; x /= 10) y++; return y; }
9,362,046
./partial_match/56/0x173BB4D9ECEfB2777C524501d876444Cf1018101/sources/O2Token.sol
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "O2T::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "O2T::delegateBySig: invalid nonce"); require(now <= expiry, "O2T::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
11,329,118
pragma solidity ^0.4.19; import './GroupAdmin.sol'; import './zeppelin/lifecycle/Destructible.sol'; contract Conference is Destructible, GroupAdmin { string public name; uint256 public deposit; uint public limitOfParticipants; uint public registered; uint public attended; bool public ended; bool public cancelled; uint public endedAt; uint public coolingPeriod; uint256 public payoutAmount; string public encryption; mapping (address => Participant) public participants; mapping (uint => address) public participantsIndex; bool paid; struct Participant { string participantName; address addr; bool attended; bool paid; } event RegisterEvent(address addr, string participantName, string _encryption); event AttendEvent(address addr); event PaybackEvent(uint256 _payout); event WithdrawEvent(address addr, uint256 _payout); event CancelEvent(); event ClearEvent(address addr, uint256 leftOver); /* Modifiers */ modifier onlyActive { require(!ended); _; } modifier onlyEnded { require(ended); _; } /* Public functions */ function Conference ( string _name, uint256 _deposit, uint _limitOfParticipants, uint _coolingPeriod, string _encryption ) public { if(bytes(_name).length != 0){ name = _name; }else{ name = 'Test'; } if(_deposit != 0){ deposit = _deposit; }else{ deposit = 0.02 ether; } if(_limitOfParticipants !=0){ limitOfParticipants = _limitOfParticipants; }else{ limitOfParticipants = 20; } if (_coolingPeriod != 0) { coolingPeriod = _coolingPeriod; } else { coolingPeriod = 1 weeks; } if (bytes(_encryption).length != 0) { encryption = _encryption; } } function registerWithEncryption(string _participant, string _encrypted) external payable onlyActive{ registerInternal(_participant); RegisterEvent(msg.sender, _participant, _encrypted); } function register(string _participant) external payable onlyActive{ registerInternal(_participant); RegisterEvent(msg.sender, _participant, ''); } function registerInternal(string _participant) internal { require(msg.value == deposit); require(registered < limitOfParticipants); require(!isRegistered(msg.sender)); registered++; participantsIndex[registered] = msg.sender; participants[msg.sender] = Participant(_participant, msg.sender, false, false); } function withdraw() external onlyEnded{ require(payoutAmount > 0); Participant participant = participants[msg.sender]; require(participant.addr == msg.sender); require(cancelled || participant.attended); require(participant.paid == false); participant.paid = true; participant.addr.transfer(payoutAmount); WithdrawEvent(msg.sender, payoutAmount); } /* Constants */ function totalBalance() constant public returns (uint256){ return this.balance; } function isRegistered(address _addr) constant public returns (bool){ return participants[_addr].addr != address(0); } function isAttended(address _addr) constant public returns (bool){ return isRegistered(_addr) && participants[_addr].attended; } function isPaid(address _addr) constant public returns (bool){ return isRegistered(_addr) && participants[_addr].paid; } function payout() constant public returns(uint256){ if (attended == 0) return 0; return uint(totalBalance()) / uint(attended); } /* Admin only functions */ function payback() external onlyOwner onlyActive{ payoutAmount = payout(); ended = true; endedAt = now; PaybackEvent(payoutAmount); } function cancel() external onlyOwner onlyActive{ payoutAmount = deposit; cancelled = true; ended = true; endedAt = now; CancelEvent(); } /* return the remaining of balance if there are any unclaimed after cooling period */ function clear() external onlyOwner onlyEnded{ require(now > endedAt + coolingPeriod); require(ended); var leftOver = totalBalance(); owner.transfer(leftOver); ClearEvent(owner, leftOver); } function setLimitOfParticipants(uint _limitOfParticipants) external onlyOwner onlyActive{ limitOfParticipants = _limitOfParticipants; } function attend(address[] _addresses) external onlyAdmin onlyActive{ for(uint i=0;i<_addresses.length;i++){ var _addr = _addresses[i]; require(isRegistered(_addr)); require(!isAttended(_addr)); AttendEvent(_addr); participants[_addr].attended = true; attended++; } } }
return the remaining of balance if there are any unclaimed after cooling period /
function clear() external onlyOwner onlyEnded{ require(now > endedAt + coolingPeriod); require(ended); var leftOver = totalBalance(); owner.transfer(leftOver); ClearEvent(owner, leftOver); }
14,033,820
./full_match/5/0x72D4379301daE59D52FeeA82CC82B77E92B2E995/sources/contracts/SokuNFT721.sol
See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable, ERC2981, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); }
1,894,966
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondCut } from "./diamond/LibDiamondCut.sol"; import { DiamondFacet } from "./diamond/DiamondFacet.sol"; import { OwnershipFacet } from "./diamond/OwnershipFacet.sol"; import { LibDiamondStorage } from "./diamond/LibDiamondStorage.sol"; import { IDiamondCut } from "./diamond/IDiamondCut.sol"; import { IDiamondLoupe } from "./diamond/IDiamondLoupe.sol"; import { IERC165 } from "./diamond/IERC165.sol"; import { LibDiamondStorageDerivaDEX } from "./storage/LibDiamondStorageDerivaDEX.sol"; import { IDDX } from "./tokens/interfaces/IDDX.sol"; /** * @title DerivaDEX * @author DerivaDEX * @notice This is the diamond for DerivaDEX. All current * and future logic runs by way of this contract. * @dev This diamond implements the Diamond Standard (EIP #2535). */ contract DerivaDEX { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This constructor initializes the upgrade machinery (as * per the Diamond Standard), sets the admin of the proxy * to be the deploying address (very temporary), and sets * the native DDX governance/operational token. * @param _ddxToken The native DDX token address. */ constructor(IDDX _ddxToken) public { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Temporarily set admin to the deploying address to facilitate // adding the Diamond functions dsDerivaDEX.admin = msg.sender; // Set DDX token address for token logic in facet contracts require(address(_ddxToken) != address(0), "DerivaDEX: ddx token is zero address."); dsDerivaDEX.ddxToken = _ddxToken; emit OwnershipTransferred(address(0), msg.sender); // Create DiamondFacet contract - // implements DiamondCut interface and DiamondLoupe interface DiamondFacet diamondFacet = new DiamondFacet(); // Create OwnershipFacet contract which implements ownership // functions and supportsInterface function OwnershipFacet ownershipFacet = new OwnershipFacet(); IDiamondCut.FacetCut[] memory diamondCut = new IDiamondCut.FacetCut[](2); // adding diamondCut function and diamond loupe functions diamondCut[0].facetAddress = address(diamondFacet); diamondCut[0].action = IDiamondCut.FacetCutAction.Add; diamondCut[0].functionSelectors = new bytes4[](6); diamondCut[0].functionSelectors[0] = DiamondFacet.diamondCut.selector; diamondCut[0].functionSelectors[1] = DiamondFacet.facetFunctionSelectors.selector; diamondCut[0].functionSelectors[2] = DiamondFacet.facets.selector; diamondCut[0].functionSelectors[3] = DiamondFacet.facetAddress.selector; diamondCut[0].functionSelectors[4] = DiamondFacet.facetAddresses.selector; diamondCut[0].functionSelectors[5] = DiamondFacet.supportsInterface.selector; // adding ownership functions diamondCut[1].facetAddress = address(ownershipFacet); diamondCut[1].action = IDiamondCut.FacetCutAction.Add; diamondCut[1].functionSelectors = new bytes4[](2); diamondCut[1].functionSelectors[0] = OwnershipFacet.transferOwnershipToSelf.selector; diamondCut[1].functionSelectors[1] = OwnershipFacet.getAdmin.selector; // execute internal diamondCut function to add functions LibDiamondCut.diamondCut(diamondCut, address(0), new bytes(0)); // adding ERC165 data ds.supportedInterfaces[IERC165.supportsInterface.selector] = true; ds.supportedInterfaces[IDiamondCut.diamondCut.selector] = true; bytes4 interfaceID = IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector; ds.supportedInterfaces[interfaceID] = true; } // TODO(jalextowle): Remove this linter directive when // https://github.com/protofire/solhint/issues/248 is merged and released. /* solhint-disable ordering */ receive() external payable { revert("DerivaDEX does not directly accept ether."); } // Finds facet for function that is called and executes the // function if it is found and returns any value. fallback() external payable { LibDiamondStorage.DiamondStorage storage ds; bytes32 position = LibDiamondStorage.DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress; require(facet != address(0), "Function does not exist."); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(0, 0, size) switch result case 0 { revert(0, size) } default { return(0, size) } } } /* solhint-enable ordering */ } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of internal diamondCut function. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./IDiamondCut.sol"; library LibDiamondCut { event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'FacetCut[] memory _diamondCut' instead of // 'FacetCut[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { require(_diamondCut.length > 0, "LibDiamondCut: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addReplaceRemoveFacetSelectors( address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); // add or replace functions if (_newFacetAddress != address(0)) { uint256 facetAddressPosition = ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition; // add new facet address if it does not exist if ( facetAddressPosition == 0 && ds.facetFunctionSelectors[_newFacetAddress].functionSelectors.length == 0 ) { ensureHasContractCode(_newFacetAddress, "LibDiamondCut: New facet has no code"); facetAddressPosition = ds.facetAddresses.length; ds.facetAddresses.push(_newFacetAddress); ds.facetFunctionSelectors[_newFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } // add or replace selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; // add if (_action == IDiamondCut.FacetCutAction.Add) { require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); addSelector(_newFacetAddress, selector); } else if (_action == IDiamondCut.FacetCutAction.Replace) { // replace require( oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function" ); removeSelector(oldFacetAddress, selector); addSelector(_newFacetAddress, selector); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } } else { require( _action == IDiamondCut.FacetCutAction.Remove, "LibDiamondCut: action not set to FacetCutAction.Remove" ); // remove selectors for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; removeSelector(ds.selectorToFacetAndPosition[selector].facetAddress, selector); } } } function addSelector(address _newFacet, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 selectorPosition = ds.facetFunctionSelectors[_newFacet].functionSelectors.length; ds.facetFunctionSelectors[_newFacet].functionSelectors.push(_selector); ds.selectorToFacetAndPosition[_selector].facetAddress = _newFacet; ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = uint16(selectorPosition); } function removeSelector(address _oldFacetAddress, bytes4 _selector) internal { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); require(_oldFacetAddress != address(0), "LibDiamondCut: Can't remove or replace function that doesn't exist"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.length - 1; bytes4 lastSelector = ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[lastSelectorPosition]; // if not the same then replace _selector with lastSelector if (lastSelector != _selector) { ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; uint256 facetAddressPosition = ds.facetFunctionSelectors[_oldFacetAddress].facetAddressPosition; if (_oldFacetAddress != lastFacetAddress) { ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_oldFacetAddress]; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { LibDiamondCut.ensureHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function ensureHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of diamondCut external function and DiamondLoupe interface. /******************************************************************************/ import "./LibDiamondStorage.sol"; import "./LibDiamondCut.sol"; import "../storage/LibDiamondStorageDerivaDEX.sol"; import "./IDiamondCut.sol"; import "./IDiamondLoupe.sol"; import "./IERC165.sol"; contract DiamondFacet is IDiamondCut, IDiamondLoupe, IERC165 { // Standard diamondCut external function /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "DiamondFacet: Must own the contract"); require(_diamondCut.length > 0, "DiamondFacet: No facets to cut"); for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { LibDiamondCut.addReplaceRemoveFacetSelectors( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } emit DiamondCut(_diamondCut, _init, _calldata); LibDiamondCut.initializeDiamondCut(_init, _calldata); } // Diamond Loupe Functions //////////////////////////////////////////////////////////////////// /// These functions are expected to be called frequently by tools. // // struct Facet { // address facetAddress; // bytes4[] functionSelectors; // } // /// @notice Gets all facets and their selectors. /// @return facets_ Facet function facets() external view override returns (Facet[] memory facets_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); uint256 numFacets = ds.facetAddresses.length; facets_ = new Facet[](numFacets); for (uint256 i; i < numFacets; i++) { address facetAddress_ = ds.facetAddresses[i]; facets_[i].facetAddress = facetAddress_; facets_[i].functionSelectors = ds.facetFunctionSelectors[facetAddress_].functionSelectors; } } /// @notice Gets all the function selectors provided by a facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view override returns (bytes4[] memory facetFunctionSelectors_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetFunctionSelectors_ = ds.facetFunctionSelectors[_facet].functionSelectors; } /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view override returns (address[] memory facetAddresses_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddresses_ = ds.facetAddresses; } /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view override returns (address facetAddress_) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); facetAddress_ = ds.selectorToFacetAndPosition[_functionSelector].facetAddress; } // This implements ERC-165. function supportsInterface(bytes4 _interfaceId) external view override returns (bool) { LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage(); return ds.supportedInterfaces[_interfaceId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { LibDiamondStorageDerivaDEX } from "../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorage } from "../diamond/LibDiamondStorage.sol"; import { IERC165 } from "./IERC165.sol"; contract OwnershipFacet { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice This function transfers ownership to self. This is done * so that we can ensure upgrades (using diamondCut) and * various other critical parameter changing scenarios * can only be done via governance (a facet). */ function transferOwnershipToSelf() external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Not authorized"); dsDerivaDEX.admin = address(this); emit OwnershipTransferred(msg.sender, address(this)); } /** * @notice This gets the admin for the diamond. * @return Admin address. */ function getAdmin() external view returns (address) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); return dsDerivaDEX.admin; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ library LibDiamondStorage { struct FacetAddressAndPosition { address facetAddress; uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint16 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the facet address in the facetAddresses array // and the position of the selector in the facetSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; } bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ interface IDiamondCut { enum FacetCutAction { Add, Replace, Remove } struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ import "./IDiamondCut.sol"; // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceId The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "../tokens/interfaces/IDDX.sol"; library LibDiamondStorageDerivaDEX { struct DiamondStorageDerivaDEX { string name; address admin; IDDX ddxToken; } bytes32 constant DIAMOND_STORAGE_POSITION_DERIVADEX = keccak256("diamond.standard.diamond.storage.DerivaDEX.DerivaDEX"); function diamondStorageDerivaDEX() internal pure returns (DiamondStorageDerivaDEX storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_DERIVADEX; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IDDX { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDDX } from "./interfaces/IDDX.sol"; /** * @title DDXWalletCloneable * @author DerivaDEX * @notice This is a cloneable on-chain DDX wallet that holds a trader's * stakes and issued rewards. */ contract DDXWalletCloneable { // Whether contract has already been initialized once before bool initialized; /** * @notice This function initializes the on-chain DDX wallet * for a given trader. * @param _trader Trader address. * @param _ddxToken DDX token address. * @param _derivaDEX DerivaDEX Proxy address. */ function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external { // Prevent initializing more than once require(!initialized, "DDXWalletCloneable: already init."); initialized = true; // Automatically delegate the holdings of this contract/wallet // back to the trader. _ddxToken.delegate(_trader); // Approve the DerivaDEX Proxy contract for unlimited transfers _ddxToken.approve(_derivaDEX, uint96(-1)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { DDXWalletCloneable } from "../../tokens/DDXWalletCloneable.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; import { LibTraderInternal } from "./LibTraderInternal.sol"; /** * @title Trader * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to traders - staking DDX, withdrawing * DDX, receiving DDX rewards, etc. */ contract Trader { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event RewardCliffSet(bool rewardCliffSet); event DDXRewardIssued(address trader, uint96 amount); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Trader: must be called by Gov."); _; } /** * @notice Limits functions to only be called post reward cliff. */ modifier postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); require(dsTrader.rewardCliff, "Trader: prior to reward cliff."); _; } /** * @notice This function initializes the state with some critical * information, including the on-chain wallet cloneable * contract address. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. */ function initialize(IDDXWalletCloneable _ddxWalletCloneable) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the on-chain DDX wallet cloneable contract address dsTrader.ddxWalletCloneable = _ddxWalletCloneable; } /** * @notice This function sets the reward cliff. * @param _rewardCliff Reward cliff. */ function setRewardCliff(bool _rewardCliff) external onlyAdmin { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Set the reward cliff (boolean value) dsTrader.rewardCliff = _rewardCliff; emit RewardCliffSet(_rewardCliff); } /** * @notice This function issues DDX rewards to a trader. It can * only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _trader Trader recipient address. */ function issueDDXReward(uint96 _amount, address _trader) external onlyAdmin { // Call the internal function to issue DDX rewards. This // internal function is shareable with other facets that import // the LibTraderInternal library. LibTraderInternal.issueDDXReward(_amount, _trader); } /** * @notice This function issues DDX rewards to an external address. * It can only be called via governance. * @param _amount DDX tokens to be rewarded. * @param _recipient External recipient address. */ function issueDDXToRecipient(uint96 _amount, address _recipient) external onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(_recipient, _amount); emit DDXRewardIssued(_recipient, _amount); } /** * @notice This function lets traders take DDX from their wallet * into their on-chain DDX wallet. It's important to note * that any DDX staked from the trader to this wallet * delegates the voting rights of that stake back to the * user. To be more explicit, if Alice's personal wallet is * delegating to Bob, and she now stakes a portion of her * DDX into this on-chain DDX wallet of hers, those tokens * will now count towards her voting power, not Bob's, since * her on-chain wallet is automatically delegating back to * her. * @param _amount The DDX tokens to be staked. */ function stakeDDXFromTrader(uint96 _amount) external { transferDDXToWallet(msg.sender, _amount); } /** * @notice This function lets traders send DDX from their wallet * into another trader's on-chain DDX wallet. It's * important to note that any DDX staked to this wallet * delegates the voting rights of that stake back to the * user. * @param _trader Trader address to receive DDX (inside their * wallet, which will be created if it does not already * exist). * @param _amount The DDX tokens to be staked. */ function sendDDXFromTraderToTraderWallet(address _trader, uint96 _amount) external { transferDDXToWallet(_trader, _amount); } /** * @notice This function lets traders withdraw DDX from their * on-chain DDX wallet to their personal wallet. It's * important to note that the voting rights for any DDX * withdrawn are returned back to the delegatee of the * user's personal wallet. To be more explicit, if Alice is * personal wallet is delegating to Bob, and she now * withdraws a portion of her DDX from this on-chain DDX * wallet of hers, those tokens will now count towards Bob's * voting power, not her's, since her on-chain wallet is * automatically delegating back to her, but her personal * wallet is delegating to Bob. Withdrawals can only happen * when the governance cliff is lifted. * @param _amount The DDX tokens to be withdrawn. */ function withdrawDDXToTrader(uint96 _amount) external postRewardCliff { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[msg.sender]; LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Subtract trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.sub96(_amount); // Transfer DDX from trader's on-chain wallet to the trader dsDerivaDEX.ddxToken.transferFrom(trader.ddxWalletContract, msg.sender, _amount); } /** * @notice This function gets the attributes for a given trader. * @param _trader Trader address. */ function getTrader(address _trader) external view returns (TraderDefs.Trader memory) { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); return dsTrader.traders[_trader]; } /** * @notice This function transfers DDX from the sender * to another trader's DDX wallet. * @param _trader Trader address' DDX wallet address to transfer * into. * @param _amount Amount of DDX to transfer. */ function transferDDXToWallet(address _trader, uint96 _amount) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { LibTraderInternal.createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.transferFrom(msg.sender, trader.ddxWalletContract, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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.12; /** * @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 SafeMath96 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add96(uint96 a, uint96 b) internal pure returns (uint96) { uint96 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 sub96(uint96 a, uint96 b) internal pure returns (uint96) { return sub96(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 sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); uint96 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title TraderDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * traders. */ library TraderDefs { // Consists of trader attributes, including the DDX balance and // the onchain DDX wallet contract address struct Trader { uint96 ddxBalance; address ddxWalletContract; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { TraderDefs } from "../libs/defs/TraderDefs.sol"; import { IDDXWalletCloneable } from "../tokens/interfaces/IDDXWalletCloneable.sol"; library LibDiamondStorageTrader { struct DiamondStorageTrader { mapping(address => TraderDefs.Trader) traders; bool rewardCliff; IDDXWalletCloneable ddxWalletCloneable; } bytes32 constant DIAMOND_STORAGE_POSITION_TRADER = keccak256("diamond.standard.diamond.storage.DerivaDEX.Trader"); function diamondStorageTrader() internal pure returns (DiamondStorageTrader storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_TRADER; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { IDDX } from "./IDDX.sol"; interface IDDXWalletCloneable { function initialize( address _trader, IDDX _ddxToken, address _derivaDEX ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { LibClone } from "../../libs/LibClone.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { TraderDefs } from "../../libs/defs/TraderDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { IDDXWalletCloneable } from "../../tokens/interfaces/IDDXWalletCloneable.sol"; /** * @title TraderInternalLib * @author DerivaDEX * @notice This is a library of internal functions mainly defined in * the Trader facet, but used in other facets. */ library LibTraderInternal { using SafeMath96 for uint96; using SafeMath for uint256; using SafeERC20 for IERC20; event DDXRewardIssued(address trader, uint96 amount); /** * @notice This function creates a new DDX wallet for a trader. * @param _trader Trader address. */ function createDDXWallet(address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); // Leveraging the minimal proxy contract/clone factory pattern // as described here (https://eips.ethereum.org/EIPS/eip-1167) IDDXWalletCloneable ddxWallet = IDDXWalletCloneable(LibClone.createClone(address(dsTrader.ddxWalletCloneable))); LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Cloneable contracts have no constructor, so instead we use // an initialize function. This initialize delegates this // on-chain DDX wallet back to the trader and sets the allowance // for the DerivaDEX Proxy contract to be unlimited. ddxWallet.initialize(_trader, dsDerivaDEX.ddxToken, address(this)); // Store the on-chain wallet address in the trader's storage dsTrader.traders[_trader].ddxWalletContract = address(ddxWallet); } /** * @notice This function issues DDX rewards to a trader. It can be * called by any facet part of the diamond. * @param _amount DDX tokens to be rewarded. * @param _trader Trader address. */ function issueDDXReward(uint96 _amount, address _trader) internal { LibDiamondStorageTrader.DiamondStorageTrader storage dsTrader = LibDiamondStorageTrader.diamondStorageTrader(); TraderDefs.Trader storage trader = dsTrader.traders[_trader]; // If trader does not have a DDX on-chain wallet yet, create one if (trader.ddxWalletContract == address(0)) { createDDXWallet(_trader); } LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); // Add trader's DDX balance in the contract trader.ddxBalance = trader.ddxBalance.add96(_amount); // Transfer DDX from trader to trader's on-chain wallet dsDerivaDEX.ddxToken.mint(trader.ddxWalletContract, _amount); emit DDXRewardIssued(_trader, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. 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. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly library LibClone { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))) } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { InsuranceFundDefs } from "../../libs/defs/InsuranceFundDefs.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageInsuranceFund } from "../../storage/LibDiamondStorageInsuranceFund.sol"; import { LibDiamondStorageTrader } from "../../storage/LibDiamondStorageTrader.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; import { IDDX } from "../../tokens/interfaces/IDDX.sol"; import { LibTraderInternal } from "../trader/LibTraderInternal.sol"; import { IAToken } from "../interfaces/IAToken.sol"; import { IComptroller } from "../interfaces/IComptroller.sol"; import { ICToken } from "../interfaces/ICToken.sol"; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; import { IDIFundTokenFactory } from "../../tokens/interfaces/IDIFundTokenFactory.sol"; interface IERCCustom { function decimals() external view returns (uint8); } /** * @title InsuranceFund * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to insurance mining - staking directly * into the insurance fund and receiving a DDX issuance to be * used in governance/operations. * @dev This facet at the moment only handles insurance mining. It can * and will grow to handle the remaining functions of the insurance * fund, such as receiving quote-denominated fees and liquidation * spreads, among others. The Diamond storage will only be * affected when facet functions are called via the proxy * contract, no checks are necessary. */ contract InsuranceFund { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath for uint96; using SafeMath for uint256; using MathHelpers for uint32; using MathHelpers for uint96; using MathHelpers for uint224; using MathHelpers for uint256; using SafeERC20 for IERC20; // Compound-related constant variables // kovan: 0x5eAe89DC1C671724A672ff0630122ee834098657 IComptroller public constant COMPTROLLER = IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); // kovan: 0x61460874a7196d6a22D1eE4922473664b3E95270 IERC20 public constant COMP_TOKEN = IERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); event InsuranceFundInitialized( uint32 interval, uint32 withdrawalFactor, uint96 mineRatePerBlock, uint96 advanceIntervalReward, uint256 miningFinalBlockNumber ); event InsuranceFundCollateralAdded( bytes32 collateralName, address underlyingToken, address collateralToken, InsuranceFundDefs.Flavor flavor ); event StakedToInsuranceFund(address staker, uint96 amount, bytes32 collateralName); event WithdrawnFromInsuranceFund(address withdrawer, uint96 amount, bytes32 collateralName); event AdvancedOtherRewards(address intervalAdvancer, uint96 advanceReward); event InsuranceMineRewardsClaimed(address claimant, uint96 minedAmount); event MineRatePerBlockSet(uint96 mineRatePerBlock); event AdvanceIntervalRewardSet(uint96 advanceIntervalReward); event WithdrawalFactorSet(uint32 withdrawalFactor); event InsuranceMiningExtended(uint256 miningFinalBlockNumber); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "IFund: must be called by Gov."); _; } /** * @notice Limits functions to only be called while insurance * mining is ongoing. */ modifier insuranceMiningOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(block.number < dsInsuranceFund.miningFinalBlockNumber, "IFund: mining ended."); _; } /** * @notice Limits functions to only be called while other * rewards checkpointing is ongoing. */ modifier otherRewardsOngoing { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require( dsInsuranceFund.otherRewardsCheckpointBlock < dsInsuranceFund.miningFinalBlockNumber, "IFund: other rewards checkpointing ended." ); _; } /** * @notice Limits functions to only be called via governance. */ modifier isNotPaused { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); require(!dsPause.isPaused, "IFund: paused."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _interval The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @param _withdrawalFactor Specifies the withdrawal fee if users * redeem their insurance tokens. * @param _mineRatePerBlock The DDX tokens to be mined each interval * for insurance mining. * @param _advanceIntervalReward DDX reward for participant who * advances the insurance mining interval. * @param _insuranceMiningLength Insurance mining length (blocks). */ function initialize( uint32 _interval, uint32 _withdrawalFactor, uint96 _mineRatePerBlock, uint96 _advanceIntervalReward, uint256 _insuranceMiningLength, IDIFundTokenFactory _diFundTokenFactory ) external onlyAdmin { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) dsInsuranceFund.interval = _interval; // Keep track of the block number for other rewards checkpoint, // which is initialized to the block number the insurance fund // facet is added to the diamond dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Set the withdrawal factor, capped at 1000, implying 0% fee require(_withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); // Set withdrawal ratio, which will be used with a 1e3 scaling // factor, meaning a value of 995 implies a withdrawal fee of // 0.5% since 995/1e3 => 0.995 dsInsuranceFund.withdrawalFactor = _withdrawalFactor; // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; // Incentive to advance the other rewards interval // (e.g. 100e18 = 100 DDX) dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; // Set the final block number for insurance mining dsInsuranceFund.miningFinalBlockNumber = block.number.add(_insuranceMiningLength); // DIFundToken factory to deploy DerivaDEX Insurance Fund token // contracts pertaining to each supported collateral dsInsuranceFund.diFundTokenFactory = _diFundTokenFactory; // Initialize the DDX market state index and block. These values // are critical for computing the DDX continuously issued per // block dsInsuranceFund.ddxMarketState.index = 1e36; dsInsuranceFund.ddxMarketState.block = block.number.safe32("IFund: exceeds 32 bits"); emit InsuranceFundInitialized( _interval, _withdrawalFactor, _mineRatePerBlock, _advanceIntervalReward, dsInsuranceFund.miningFinalBlockNumber ); } /** * @notice This function sets the DDX mine rate per block. * @param _mineRatePerBlock The DDX tokens mine rate per block. */ function setMineRatePerBlock(uint96 _mineRatePerBlock) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // NOTE(jalextowle): We must update the DDX Market State prior to // changing the mine rate per block in order to lock in earned rewards // for insurance mining participants. updateDDXMarketState(dsInsuranceFund); require(_mineRatePerBlock != dsInsuranceFund.mineRatePerBlock, "IFund: same as current value."); // Set the insurance mine rate per block. // (e.g. 1.189e18 ~ 5% liquidity mine (50mm tokens)) dsInsuranceFund.mineRatePerBlock = _mineRatePerBlock; emit MineRatePerBlockSet(_mineRatePerBlock); } /** * @notice This function sets the advance interval reward. * @param _advanceIntervalReward DDX reward for advancing interval. */ function setAdvanceIntervalReward(uint96 _advanceIntervalReward) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_advanceIntervalReward != dsInsuranceFund.advanceIntervalReward, "IFund: same as current value."); // Set the advance interval reward dsInsuranceFund.advanceIntervalReward = _advanceIntervalReward; emit AdvanceIntervalRewardSet(_advanceIntervalReward); } /** * @notice This function sets the withdrawal factor. * @param _withdrawalFactor Withdrawal factor. */ function setWithdrawalFactor(uint32 _withdrawalFactor) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_withdrawalFactor != dsInsuranceFund.withdrawalFactor, "IFund: same as current value."); // Set the withdrawal factor, capped at 1000, implying 0% fee require(dsInsuranceFund.withdrawalFactor <= 1000, "IFund: withdrawal fee too high."); dsInsuranceFund.withdrawalFactor = _withdrawalFactor; emit WithdrawalFactorSet(_withdrawalFactor); } /** * @notice This function extends insurance mining. * @param _insuranceMiningExtension Insurance mining extension * (blocks). */ function extendInsuranceMining(uint256 _insuranceMiningExtension) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); require(_insuranceMiningExtension != 0, "IFund: invalid extension."); // Extend the mining final block number dsInsuranceFund.miningFinalBlockNumber = dsInsuranceFund.miningFinalBlockNumber.add(_insuranceMiningExtension); emit InsuranceMiningExtended(dsInsuranceFund.miningFinalBlockNumber); } /** * @notice This function adds a new supported collateral type that * can be staked to the insurance fund. It can only * be called via governance. * @dev For vanilla contracts (e.g. USDT, USDC, etc.), the * underlying token equals address(0). * @param _collateralName Name of collateral. * @param _collateralSymbol Symbol of collateral. * @param _underlyingToken Deployed address of underlying token. * @param _collateralToken Deployed address of collateral token. * @param _flavor Collateral flavor (Vanilla, Compound, Aave, etc.). */ function addInsuranceFundCollateral( string memory _collateralName, string memory _collateralSymbol, address _underlyingToken, address _collateralToken, InsuranceFundDefs.Flavor _flavor ) external onlyAdmin insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain bytes32 representation of collateral name bytes32 result; assembly { result := mload(add(_collateralName, 32)) } // Ensure collateral has not already been added require( dsInsuranceFund.stakeCollaterals[result].collateralToken == address(0), "IFund: collateral already added." ); require(_collateralToken != address(0), "IFund: collateral address must be non-zero."); require(!isCollateralTokenPresent(_collateralToken), "IFund: collateral token already present."); require(_underlyingToken != _collateralToken, "IFund: token addresses are same."); if (_flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of vanilla flavor, there should only be // a value for collateral token, and underlying token should // be empty require(_underlyingToken == address(0), "IFund: underlying address non-zero for Vanilla."); } // Add collateral type to storage, including its underlying // token and collateral token addresses, and its flavor dsInsuranceFund.stakeCollaterals[result].underlyingToken = _underlyingToken; dsInsuranceFund.stakeCollaterals[result].collateralToken = _collateralToken; dsInsuranceFund.stakeCollaterals[result].flavor = _flavor; // Create a DerivaDEX Insurance Fund token contract associated // with this supported collateral dsInsuranceFund.stakeCollaterals[result].diFundToken = IDIFundToken( dsInsuranceFund.diFundTokenFactory.createNewDIFundToken( _collateralName, _collateralSymbol, IERCCustom(_collateralToken).decimals() ) ); dsInsuranceFund.collateralNames.push(result); emit InsuranceFundCollateralAdded(result, _underlyingToken, _collateralToken, _flavor); } /** * @notice This function allows participants to stake a supported * collateral type to the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function stakeToInsuranceFund(bytes32 _collateralName, uint96 _amount) external insuranceMiningOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero stake amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for staking user. We do this prior to the stake // taking effect, thereby preventing someone from being rewarded // instantly for the stake. claimDDXFromInsuranceMining(msg.sender); // Increment the underlying capitalization stakeCollateral.cap = stakeCollateral.cap.add96(_amount); // Transfer collateral amount from user to proxy contract IERC20(stakeCollateral.collateralToken).safeTransferFrom(msg.sender, address(this), _amount); // Mint DIFund tokens to user stakeCollateral.diFundToken.mint(msg.sender, _amount); emit StakedToInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice This function allows participants to withdraw a supported * collateral type from the insurance fund. * @param _collateralName Name of collateral. * @param _amount Amount to stake. */ function withdrawFromInsuranceFund(bytes32 _collateralName, uint96 _amount) external isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Ensure this is a supported collateral type and that the user // has approved the proxy contract for transfer require(stakeCollateral.collateralToken != address(0), "IFund: invalid collateral."); // Ensure non-zero withdraw amount require(_amount > 0, "IFund: non-zero amount."); // Claim DDX for withdrawing user. We do this prior to the // redeem taking effect. claimDDXFromInsuranceMining(msg.sender); // Determine underlying to transfer based on how much underlying // can be redeemed given the current underlying capitalization // and how many DIFund tokens are globally available. This // theoretically fails in the scenario where globally there are // 0 insurance fund tokens, however that would mean the user // also has 0 tokens in their possession, and thus would have // nothing to be redeemed anyways. uint96 underlyingToTransferNoFee = _amount.proportion96(stakeCollateral.cap, stakeCollateral.diFundToken.totalSupply()); uint96 underlyingToTransfer = underlyingToTransferNoFee.proportion96(dsInsuranceFund.withdrawalFactor, 1e3); // Decrement the capitalization stakeCollateral.cap = stakeCollateral.cap.sub96(underlyingToTransferNoFee); // Increment the withdrawal fee cap stakeCollateral.withdrawalFeeCap = stakeCollateral.withdrawalFeeCap.add96( underlyingToTransferNoFee.sub96(underlyingToTransfer) ); // Transfer collateral amount from proxy contract to user IERC20(stakeCollateral.collateralToken).safeTransfer(msg.sender, underlyingToTransfer); // Burn DIFund tokens being redeemed from user stakeCollateral.diFundToken.burnFrom(msg.sender, _amount); emit WithdrawnFromInsuranceFund(msg.sender, _amount, _collateralName); } /** * @notice Advance other rewards interval */ function advanceOtherRewardsInterval() external otherRewardsOngoing isNotPaused { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Check if the current block has exceeded the interval bounds, // allowing for a new other rewards interval to be checkpointed require( block.number >= dsInsuranceFund.otherRewardsCheckpointBlock.add(dsInsuranceFund.interval), "IFund: advance too soon." ); // Maintain the USD-denominated sum of all Compound-flavor // assets. This needs to be stored separately than the rest // due to the way COMP tokens are rewarded to the contract in // order to properly disseminate to the user. uint96 normalizedCapCheckpointSumCompound; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, set the exchange // rate at this point in time. We do this so later on, // when claiming rewards, we know the exchange rate // checkpointed balances should be converted to // determine the USD-denominated value of holdings // needed to compute fair share of DDX rewards. stakeCollateral.exchangeRate = ICToken(stakeCollateral.collateralToken).exchangeRateStored().safe96( "IFund: amount exceeds 96 bits" ); // Set checkpoint cap for this Compound flavor // collateral to handle COMP distribution lookbacks stakeCollateral.checkpointCap = stakeCollateral.cap; // Increment the normalized Compound checkpoint cap // with the USD-denominated value normalizedCapCheckpointSumCompound = normalizedCapCheckpointSumCompound.add96( getUnderlyingTokenAmountForCompound(stakeCollateral.cap, stakeCollateral.exchangeRate) ); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // If collateral is of type Aave, we need to do some // custom Aave aToken reward distribution. We first // determine the contract's aToken balance for this // collateral type and subtract the underlying // aToken capitalization that are due to users. This // leaves us with the excess that has been rewarded // to the contract due to Aave's mechanisms, but // belong to the users. uint96 myATokenBalance = uint96(IAToken(stakeCollateral.collateralToken).balanceOf(address(this)).sub(stakeCollateral.cap)); // Store the aToken yield information dsInsuranceFund.aTokenYields[dsInsuranceFund.collateralNames[i]] = InsuranceFundDefs .ExternalYieldCheckpoint({ accrued: myATokenBalance, totalNormalizedCap: 0 }); } } // Ensure that the normalized cap sum is non-zero if (normalizedCapCheckpointSumCompound > 0) { // If there's Compound-type asset capitalization in the // system, claim COMP accrued to this contract. This COMP is // a result of holding all the cToken deposits from users. // We claim COMP via Compound's Comptroller contract. COMPTROLLER.claimComp(address(this)); // Obtain contract's balance of COMP uint96 myCompBalance = COMP_TOKEN.balanceOf(address(this)).safe96("IFund: amount exceeds 96 bits."); // Store the updated value as the checkpointed COMP yield owed // for this interval dsInsuranceFund.compYields = InsuranceFundDefs.ExternalYieldCheckpoint({ accrued: myCompBalance, totalNormalizedCap: normalizedCapCheckpointSumCompound }); } // Set other rewards checkpoint block to current block dsInsuranceFund.otherRewardsCheckpointBlock = block.number; // Issue DDX reward to trader's on-chain DDX wallet as an // incentive to users calling this function LibTraderInternal.issueDDXReward(dsInsuranceFund.advanceIntervalReward, msg.sender); emit AdvancedOtherRewards(msg.sender, dsInsuranceFund.advanceIntervalReward); } /** * @notice This function gets some high level insurance mining * details. * @return The interval length (blocks) for other rewards * claiming checkpoints (i.e. COMP and extra aTokens). * @return Current insurance mine withdrawal factor. * @return DDX reward for advancing interval. * @return Total global insurance mined amount in DDX. * @return Current insurance mine rate per block. * @return Insurance mining final block number. * @return DDX market state used for continuous DDX payouts. * @return Supported collateral names supported. */ function getInsuranceMineInfo() external view returns ( uint32, uint32, uint96, uint96, uint96, uint256, InsuranceFundDefs.DDXMarketState memory, bytes32[] memory ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return ( dsInsuranceFund.interval, dsInsuranceFund.withdrawalFactor, dsInsuranceFund.advanceIntervalReward, dsInsuranceFund.minedAmount, dsInsuranceFund.mineRatePerBlock, dsInsuranceFund.miningFinalBlockNumber, dsInsuranceFund.ddxMarketState, dsInsuranceFund.collateralNames ); } /** * @notice This function gets the current claimant state for a user. * @param _claimant Claimant address. * @return Claimant state. */ function getDDXClaimantState(address _claimant) external view returns (InsuranceFundDefs.DDXClaimantState memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.ddxClaimantState[_claimant]; } /** * @notice This function gets a supported collateral type's data, * including collateral's token addresses, collateral * flavor/type, current cap and withdrawal amounts, the * latest checkpointed cap, and exchange rate (for cTokens). * An interface for the DerivaDEX Insurance Fund token * corresponding to this collateral is also maintained. * @param _collateralName Name of collateral. * @return Stake collateral. */ function getStakeCollateralByCollateralName(bytes32 _collateralName) external view returns (InsuranceFundDefs.StakeCollateral memory) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); return dsInsuranceFund.stakeCollaterals[_collateralName]; } /** * @notice This function gets unclaimed DDX rewards for a claimant. * @param _claimant Claimant address. * @return Unclaimed DDX rewards. */ function getUnclaimedDDXRewards(address _claimant) external view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 deltaBlocks = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber).sub(dsInsuranceFund.ddxMarketState.block); // Save off last index value uint256 index = dsInsuranceFund.ddxMarketState.index; // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index index = index.add(ratio); } // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (index > 0)) { ddxClaimantIndex = 1e36; } // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the unclaimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above return claimantTokens.mul(index.sub(ddxClaimantIndex)).div(1e36).safe96("IFund: exceeds 96 bits"); } /** * @notice Calculate DDX accrued by a claimant and possibly transfer * it to them. * @param _claimant The address of the claimant. */ function claimDDXFromInsuranceMining(address _claimant) public { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Update the DDX Market State in order to determine the amount of // rewards that should be paid to the claimant. updateDDXMarketState(dsInsuranceFund); // Obtain the most recent claimant index uint256 ddxClaimantIndex = dsInsuranceFund.ddxClaimantState[_claimant].index; dsInsuranceFund.ddxClaimantState[_claimant].index = dsInsuranceFund.ddxMarketState.index; // If the claimant index is 0, i.e. it's the user's first time // interacting with the protocol, initialize it to this starting // value if ((ddxClaimantIndex == 0) && (dsInsuranceFund.ddxMarketState.index > 0)) { ddxClaimantIndex = 1e36; } // Compute the difference between the latest DDX market state // index and the claimant's index uint256 deltaIndex = uint256(dsInsuranceFund.ddxMarketState.index).sub(ddxClaimantIndex); // Maintain a running total of USDT-normalized claimant tokens // (i.e. 1e6 multiplier) uint256 claimantTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claimant tokens count with // the current balance claimantTokens = claimantTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.balanceOf(_claimant).safe96("IFund: exceeds 96 bits") ) ); } // Compute the claimed DDX based on the number of claimant // tokens and the difference between the user's index and the // claimant index computed above uint96 claimantDelta = claimantTokens.mul(deltaIndex).div(1e36).safe96("IFund: exceeds 96 bits"); if (claimantDelta != 0) { // Adjust insurance mined amount dsInsuranceFund.minedAmount = dsInsuranceFund.minedAmount.add96(claimantDelta); // Increment the insurance mined claimed DDX for claimant dsInsuranceFund.ddxClaimantState[_claimant].claimedDDX = dsInsuranceFund.ddxClaimantState[_claimant] .claimedDDX .add96(claimantDelta); // Mint the DDX governance/operational token claimed reward // from the proxy contract to the participant LibTraderInternal.issueDDXReward(claimantDelta, _claimant); } // Check if COMP or aTokens have not already been claimed if (dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] < dsInsuranceFund.otherRewardsCheckpointBlock) { // Record the current block number preventing a user from // reclaiming the COMP reward unfairly dsInsuranceFund.stakerToOtherRewardsClaims[_claimant] = block.number; // Claim COMP and extra aTokens claimOtherRewardsFromInsuranceMining(_claimant); } emit InsuranceMineRewardsClaimed(_claimant, claimantDelta); } /** * @notice Get USDT-normalized collateral token amount. * @param _collateralName The collateral name. * @param _value The number of tokens. */ function getNormalizedCollateralValue(bytes32 _collateralName, uint96 _value) public view returns (uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; return (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(_value, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( _value, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); } /** * @notice This function gets a participant's current * USD-normalized/denominated stake and global * USD-normalized/denominated stake across all supported * collateral types. * @param _staker Participant's address. * @return Current USD redemption value of DIFund tokens staked. * @return Current USD global cap. */ function getCurrentTotalStakes(address _staker) public view returns (uint96, uint96) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain running totals uint96 normalizedStakerStakeSum; uint96 normalizedGlobalCapSum; // Loop through each supported collateral for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { (, , uint96 normalizedStakerStake, uint96 normalizedGlobalCap) = getCurrentStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _staker); normalizedStakerStakeSum = normalizedStakerStakeSum.add96(normalizedStakerStake); normalizedGlobalCapSum = normalizedGlobalCapSum.add96(normalizedGlobalCap); } return (normalizedStakerStakeSum, normalizedGlobalCapSum); } /** * @notice This function gets a participant's current DIFund token * holdings and global DIFund token holdings for a * collateral type and staker, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getCurrentStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker uint96 stakerStake = stakeCollateral.diFundToken.balanceOf(_staker).safe96("IFund: exceeds 96 bits."); // Get DIFund tokens globally uint96 globalCap = stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits."); // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = (stakeCollateral.flavor != InsuranceFundDefs.Flavor.Compound) ? getUnderlyingTokenAmountForVanilla(stakeCollateral.cap, stakeCollateral.collateralToken) : getUnderlyingTokenAmountForCompound( stakeCollateral.cap, ICToken(stakeCollateral.collateralToken).exchangeRateStored() ); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice This function gets a participant's DIFund token * holdings and global DIFund token holdings for Compound * and Aave tokens for a collateral type and staker as of * the checkpointed block, in addition to the * USD-normalized collateral in the system and the * redemption value for the staker. * @param _collateralName Name of collateral. * @param _staker Participant's address. * @return DIFund tokens for staker. * @return DIFund tokens globally. * @return Redemption value for staker (USD-denominated). * @return Underlying collateral (USD-denominated) in staking system. */ function getOtherRewardsStakeByCollateralNameAndStaker(bytes32 _collateralName, address _staker) public view returns ( uint96, uint96, uint96, uint96 ) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; // Get DIFund tokens for staker as of the checkpointed block uint96 stakerStake = stakeCollateral.diFundToken.getPriorValues(_staker, dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // Get DIFund tokens globally as of the checkpointed block uint96 globalCap = stakeCollateral.diFundToken.getTotalPriorValues(dsInsuranceFund.otherRewardsCheckpointBlock.sub(1)); // If Aave, don't worry about the normalized values since 1-1 if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { return (stakerStake, globalCap, 0, 0); } // Compute global USD-denominated stake capitalization. This is // is straightforward for non-Compound assets, but requires // exchange rate conversion for Compound assets. uint96 normalizedGlobalCap = getUnderlyingTokenAmountForCompound(stakeCollateral.checkpointCap, stakeCollateral.exchangeRate); // Compute the redemption value (USD-normalized) for staker // given DIFund token holdings uint96 normalizedStakerStake = globalCap > 0 ? normalizedGlobalCap.proportion96(stakerStake, globalCap) : 0; return (stakerStake, globalCap, normalizedStakerStake, normalizedGlobalCap); } /** * @notice Claim other rewards (COMP and aTokens) for a claimant. * @param _claimant The address for the claimant. */ function claimOtherRewardsFromInsuranceMining(address _claimant) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Maintain a running total of COMP to be claimed from // insurance mining contract as a by product of cToken deposits uint96 compClaimedAmountSum; // Loop through collateral names that are supported for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Vanilla) { // If collateral is of Vanilla flavor, we just // continue... continue; } // Compute the DIFund token holdings and the normalized, // USDT-normalized collateral value for the user (uint96 collateralStaker, uint96 collateralTotal, uint96 normalizedCollateralStaker, ) = getOtherRewardsStakeByCollateralNameAndStaker(dsInsuranceFund.collateralNames[i], _claimant); if ((collateralTotal == 0) || (collateralStaker == 0)) { // If there are no DIFund tokens, there is no reason to // claim rewards, so we continue... continue; } if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Aave) { // Aave has a special circumstance, where every // aToken results in additional aTokens accruing // to the holder's wallet. In this case, this is // the DerivaDEX contract. Therefore, we must // appropriately distribute the extra aTokens to // users claiming DDX for their aToken deposits. transferTokensAave(_claimant, dsInsuranceFund.collateralNames[i], collateralStaker, collateralTotal); } else if (stakeCollateral.flavor == InsuranceFundDefs.Flavor.Compound) { // If collateral is of type Compound, determine the // COMP claimant is entitled to based on the COMP // yield for this interval, the claimant's // DIFundToken share, and the USD-denominated // share for this market. uint96 compClaimedAmount = dsInsuranceFund.compYields.accrued.proportion96( normalizedCollateralStaker, dsInsuranceFund.compYields.totalNormalizedCap ); // Increment the COMP claimed sum to be paid out // later compClaimedAmountSum = compClaimedAmountSum.add96(compClaimedAmount); } } // Distribute any COMP to be shared with the user if (compClaimedAmountSum > 0) { transferTokensCompound(_claimant, compClaimedAmountSum); } } /** * @notice This function transfers extra Aave aTokens to claimant. */ function transferTokensAave( address _claimant, bytes32 _collateralName, uint96 _aaveStaker, uint96 _aaveTotal ) internal { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); // Obtain collateral struct under consideration InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[_collateralName]; uint96 aTokenClaimedAmount = dsInsuranceFund.aTokenYields[_collateralName].accrued.proportion96(_aaveStaker, _aaveTotal); // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try IAToken(stakeCollateral.collateralToken).transfer(_claimant, aTokenClaimedAmount) {} catch {} } /** * @notice This function transfers COMP tokens from the contract to * a recipient. * @param _amount Amount of COMP to receive. */ function transferTokensCompound(address _claimant, uint96 _amount) internal { // Continues in scenarios token transfer fails (such as // transferring 0 tokens) try COMP_TOKEN.transfer(_claimant, _amount) {} catch {} } /** * @notice Updates the DDX market state to ensure that claimants can receive * their earned DDX rewards. */ function updateDDXMarketState(LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund) internal { // Number of blocks that have elapsed from the last protocol // interaction resulting in DDX accrual. If insurance mining // has ended, we use this as the reference point, so deltaBlocks // will be 0 from the second time onwards. uint256 endBlock = Math.min(block.number, dsInsuranceFund.miningFinalBlockNumber); uint256 deltaBlocks = endBlock.sub(dsInsuranceFund.ddxMarketState.block); // If number of blocks elapsed and mine rate per block are // non-zero if (deltaBlocks > 0 && dsInsuranceFund.mineRatePerBlock > 0) { // Maintain a running total of USDT-normalized claim tokens // (i.e. 1e6 multiplier) uint256 claimTokens; // Loop through each of the supported collateral types for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Obtain the collateral struct for the collateral type // participant is staking InsuranceFundDefs.StakeCollateral storage stakeCollateral = dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]]; // Increment the USDT-normalized claim tokens count with // the current total supply claimTokens = claimTokens.add( getNormalizedCollateralValue( dsInsuranceFund.collateralNames[i], stakeCollateral.diFundToken.totalSupply().safe96("IFund: exceeds 96 bits") ) ); } // Compute DDX accrued during the time elapsed and the // number of tokens accrued per claim token outstanding uint256 ddxAccrued = deltaBlocks.mul(dsInsuranceFund.mineRatePerBlock); uint256 ratio = claimTokens > 0 ? ddxAccrued.mul(1e36).div(claimTokens) : 0; // Increment the index uint256 index = uint256(dsInsuranceFund.ddxMarketState.index).add(ratio); // Update the claim ddx market state with the new index // and block dsInsuranceFund.ddxMarketState.index = index.safe224("IFund: exceeds 224 bits"); dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } else if (deltaBlocks > 0) { dsInsuranceFund.ddxMarketState.block = endBlock.safe32("IFund: exceeds 32 bits"); } } /** * @notice This function checks if a collateral token is present. * @param _collateralToken Collateral token address. * @return Whether collateral token is present or not. */ function isCollateralTokenPresent(address _collateralToken) internal view returns (bool) { LibDiamondStorageInsuranceFund.DiamondStorageInsuranceFund storage dsInsuranceFund = LibDiamondStorageInsuranceFund.diamondStorageInsuranceFund(); for (uint256 i = 0; i < dsInsuranceFund.collateralNames.length; i++) { // Return true if collateral token has been added if ( dsInsuranceFund.stakeCollaterals[dsInsuranceFund.collateralNames[i]].collateralToken == _collateralToken ) { return true; } } // Collateral token has not been added, return false return false; } /** * @notice This function computes the underlying token amount for a * vanilla token. * @param _vanillaAmount Number of vanilla tokens. * @param _collateral Address of vanilla collateral. * @return Underlying token amount. */ function getUnderlyingTokenAmountForVanilla(uint96 _vanillaAmount, address _collateral) internal view returns (uint96) { uint256 vanillaDecimals = uint256(IERCCustom(_collateral).decimals()); if (vanillaDecimals >= 6) { return uint256(_vanillaAmount).div(10**(vanillaDecimals.sub(6))).safe96("IFund: amount exceeds 96 bits"); } return uint256(_vanillaAmount).mul(10**(uint256(6).sub(vanillaDecimals))).safe96("IFund: amount exceeds 96 bits"); } /** * @notice This function computes the underlying token amount for a * cToken amount by computing the current exchange rate. * @param _cTokenAmount Number of cTokens. * @param _exchangeRate Exchange rate derived from Compound. * @return Underlying token amount. */ function getUnderlyingTokenAmountForCompound(uint96 _cTokenAmount, uint256 _exchangeRate) internal pure returns (uint96) { return _exchangeRate.mul(_cTokenAmount).div(1e18).safe96("IFund: amount exceeds 96 bits."); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add32(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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 sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(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 sub32( uint32 a, uint32 b, string memory errorMessage ) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { SafeMath96 } from "./SafeMath96.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library MathHelpers { using SafeMath96 for uint96; using SafeMath for uint256; function proportion96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(uint256(a).mul(b).div(c), "Amount exceeds 96 bits"); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } /** * @dev Returns the largest of two numbers. */ function clamp96( uint96 a, uint256 b, uint256 c ) internal pure returns (uint96) { return safe96(Math.min(Math.max(a, b), c), "Amount exceeds 96 bits"); } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { IDIFundToken } from "../../tokens/interfaces/IDIFundToken.sol"; /** * @title InsuranceFundDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the insurance fund. */ library InsuranceFundDefs { // DDX market state maintaining claim index and last updated block struct DDXMarketState { uint224 index; uint32 block; } // DDX claimant state maintaining claim index and claimed DDX struct DDXClaimantState { uint256 index; uint96 claimedDDX; } // Supported collateral struct consisting of the collateral's token // addresses, collateral flavor/type, current cap and withdrawal // amounts, the latest checkpointed cap, and exchange rate (for // cTokens). An interface for the DerivaDEX Insurance Fund token // corresponding to this collateral is also maintained. struct StakeCollateral { address underlyingToken; address collateralToken; IDIFundToken diFundToken; uint96 cap; uint96 withdrawalFeeCap; uint96 checkpointCap; uint96 exchangeRate; Flavor flavor; } // Contains the yield accrued and the total normalized cap. // Total normalized cap is maintained for Compound flavors so COMP // distribution can be paid out properly struct ExternalYieldCheckpoint { uint96 accrued; uint96 totalNormalizedCap; } // Type of collateral enum Flavor { Vanilla, Compound, Aave } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { InsuranceFundDefs } from "../libs/defs/InsuranceFundDefs.sol"; import { IDIFundTokenFactory } from "../tokens/interfaces/IDIFundTokenFactory.sol"; library LibDiamondStorageInsuranceFund { struct DiamondStorageInsuranceFund { // List of supported collateral names bytes32[] collateralNames; // Collateral name to stake collateral struct mapping(bytes32 => InsuranceFundDefs.StakeCollateral) stakeCollaterals; mapping(address => InsuranceFundDefs.DDXClaimantState) ddxClaimantState; // aToken name to yield checkpoints mapping(bytes32 => InsuranceFundDefs.ExternalYieldCheckpoint) aTokenYields; mapping(address => uint256) stakerToOtherRewardsClaims; // Interval to COMP yield checkpoint InsuranceFundDefs.ExternalYieldCheckpoint compYields; // Set the interval for other rewards claiming checkpoints // (i.e. COMP and aTokens that accrue to the contract) // (e.g. 40320 ~ 1 week = 7 * 24 * 60 * 60 / 15 blocks) uint32 interval; // Current insurance mining withdrawal factor uint32 withdrawalFactor; // DDX to be issued per block as insurance mining reward uint96 mineRatePerBlock; // Incentive to advance the insurance mining interval // (e.g. 100e18 = 100 DDX) uint96 advanceIntervalReward; // Total DDX insurance mined uint96 minedAmount; // Insurance fund capitalization due to liquidations and fees uint96 liqAndFeeCapitalization; // Checkpoint block for other rewards uint256 otherRewardsCheckpointBlock; // Insurance mining final block number uint256 miningFinalBlockNumber; InsuranceFundDefs.DDXMarketState ddxMarketState; IDIFundTokenFactory diFundTokenFactory; } bytes32 constant DIAMOND_STORAGE_POSITION_INSURANCE_FUND = keccak256("diamond.standard.diamond.storage.DerivaDEX.InsuranceFund"); function diamondStorageInsuranceFund() internal pure returns (DiamondStorageInsuranceFund storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_INSURANCE_FUND; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; library LibDiamondStoragePause { struct DiamondStoragePause { bool isPaused; } bytes32 constant DIAMOND_STORAGE_POSITION_PAUSE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Pause"); function diamondStoragePause() internal pure returns (DiamondStoragePause storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_PAUSE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAToken { function decimals() external returns (uint256); function transfer(address _recipient, uint256 _amount) external; function balanceOf(address _user) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; abstract contract IComptroller { struct CompMarketState { uint224 index; uint32 block; } /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; // solhint-disable-line const-name-snakecase // @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The portion of compRate that each market currently receives mapping(address => uint256) public compSpeeds; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint256) public compAccrued; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external virtual returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external virtual; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external virtual returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external virtual; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external virtual returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external virtual; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external virtual returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external virtual; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external virtual returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external virtual; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external virtual; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external virtual returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external virtual; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external virtual returns (uint256, uint256); function claimComp(address holder) public virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICToken { function accrueInterest() external returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOfUnderlying(address owner) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrowsCurrent() external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function decimals() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function getCash() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title IDIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ interface IDIFundToken { function transfer(address _recipient, uint256 _amount) external returns (bool); function mint(address _recipient, uint256 _amount) external; function burnFrom(address _account, uint256 _amount) external; function delegate(address _delegatee) external; function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function getPriorValues(address account, uint256 blockNumber) external view returns (uint96); function getTotalPriorValues(uint256 blockNumber) external view returns (uint96); function balanceOf(address _account) external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { DIFundToken } from "../DIFundToken.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ interface IDIFundTokenFactory { function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address); function diFundTokens(uint256 index) external returns (DIFundToken); function issuer() external view returns (address); function getDIFundTokens() external view returns (DIFundToken[] memory); function getDIFundTokensLength() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { IInsuranceFund } from "../facets/interfaces/IInsuranceFund.sol"; /** * @title DIFundToken * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the token contract for tokenized DerivaDEX insurance * fund positions. It implements the ERC-20 standard, with * additional functionality around snapshotting user and global * balances. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DIFundToken makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances and allowances, this * allows us to more efficiently pack data together, thereby * resulting in cheaper transactions. */ contract DIFundToken { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; uint256 internal _totalSupply; string private _name; string private _symbol; string private _version; uint8 private _decimals; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 values; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; mapping(uint256 => Checkpoint) totalCheckpoints; uint256 numTotalCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when a user account's balance changes event ValuesChanged(address indexed user, uint96 previousValue, uint96 newValue); /// @notice Emitted when a user account's balance changes event TotalValuesChanged(uint96 previousValue, uint96 newValue); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DIFundToken token */ constructor( string memory name, string memory symbol, uint8 decimals, address _issuer ) public { _name = name; _symbol = symbol; _decimals = decimals; _version = "1"; // Set issuer to deploying address issuer = _issuer; } /** * @notice Returns the name of the token. * @return Name of the token. */ function name() public view returns (string memory) { return _name; } /** * @notice Returns the symbol of the token. * @return Symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. * @return Number of decimals. */ function decimals() public view returns (uint8) { return _decimals; } /** * @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 (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, _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) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DIFT: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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) external returns (bool) { require(_spender != address(0), "DIFT: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DIFT: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DIFT: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @notice Get the number of tokens held by the `account` * @param _account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address _account) external view returns (uint256) { return balances[_account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(msg.sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _sender The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _sender, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_sender][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _sender && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_sender][msg.sender] = newAllowance; emit Approval(_sender, msg.sender, newAllowance); } // Claim DDX rewards on behalf of the sender IInsuranceFund(issuer).claimDDXFromInsuranceMining(_sender); // Claim DDX rewards on behalf of the recipient IInsuranceFund(issuer).claimDDXFromInsuranceMining(_recipient); // Transfer tokens from sender to recipient _transferTokens(_sender, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DIFT: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DIFT: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1) && msg.sender != issuer) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DIFT: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(_name, _version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DIFT: invalid signature."); require(_nonce == nonces[recovered]++, "DIFT: invalid nonce."); require(block.timestamp <= _expiry, "DIFT: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DIFT: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param _account The address of the account holding the funds * @param _spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address _account, address _spender) external view returns (uint256) { return allowances[_account][_spender]; } /** * @notice Get the total max supply of DDX tokens * @return The total max supply of DDX */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @notice Determine the prior number of values 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 values the account had as of the given block */ function getPriorValues(address _account, uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].values; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].values; } /** * @notice Determine the prior number of values 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 _blockNumber The block number to get the vote balance at * @return The number of values the account had as of the given block */ function getTotalPriorValues(uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DIFT: block not yet determined."); if (numTotalCheckpoints == 0) { return 0; } // First check most recent balance if (totalCheckpoints[numTotalCheckpoints - 1].id <= _blockNumber) { return totalCheckpoints[numTotalCheckpoints - 1].values; } // Next check implicit zero balance if (totalCheckpoints[0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numTotalCheckpoints - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = totalCheckpoints[center]; if (cp.id == _blockNumber) { return cp.values; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return totalCheckpoints[lower].values; } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move values from spender to recipient _moveTokens(_spender, _recipient, _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DIFT: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); _totalSupply = _totalSupply.add(_amount); emit Transfer(address(0), _recipient, _amount); // Add value to recipient's checkpoint _moveTokens(address(0), _recipient, _amount); _writeTotalCheckpoint(_amount, true); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DIFT: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DIFT: not enough balance to burn."); // Reduce the circulating supply _totalSupply = _totalSupply.sub(_amount); emit Transfer(_spender, address(0), _amount); // Reduce value from spender's checkpoint _moveTokens(_spender, address(0), _amount); _writeTotalCheckpoint(_amount, false); } function _moveTokens( address _initUser, address _finUser, uint96 _amount ) internal { if (_initUser != _finUser && _amount > 0) { // Initial user address is different than final // user address and nonzero number of values moved if (_initUser != address(0)) { uint256 initUserNum = numCheckpoints[_initUser]; // Retrieve and compute the old and new initial user // address' values uint96 initUserOld = initUserNum > 0 ? checkpoints[_initUser][initUserNum - 1].values : 0; uint96 initUserNew = initUserOld.sub96(_amount); _writeCheckpoint(_initUser, initUserOld, initUserNew); } if (_finUser != address(0)) { uint256 finUserNum = numCheckpoints[_finUser]; // Retrieve and compute the old and new final user // address' values uint96 finUserOld = finUserNum > 0 ? checkpoints[_finUser][finUserNum - 1].values : 0; uint96 finUserNew = finUserOld.add96(_amount); _writeCheckpoint(_finUser, finUserOld, finUserNew); } } } function _writeCheckpoint( address _user, uint96 _oldValues, uint96 _newValues ) internal { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint256 userNum = numCheckpoints[_user]; if (userNum > 0 && checkpoints[_user][userNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_user][userNum - 1].values = _newValues; } else { // Create a new id, value pair checkpoints[_user][userNum] = Checkpoint({ id: blockNumber, values: _newValues }); numCheckpoints[_user] = userNum.add(1); } emit ValuesChanged(_user, _oldValues, _newValues); } function _writeTotalCheckpoint(uint96 _amount, bool increase) internal { if (_amount > 0) { uint32 blockNumber = safe32(block.number, "DIFT: exceeds 32 bits."); uint96 oldValues = numTotalCheckpoints > 0 ? totalCheckpoints[numTotalCheckpoints - 1].values : 0; uint96 newValues = increase ? oldValues.add96(_amount) : oldValues.sub96(_amount); if (numTotalCheckpoints > 0 && totalCheckpoints[numTotalCheckpoints - 1].id == block.number) { // If latest checkpoint is current block, edit in place totalCheckpoints[numTotalCheckpoints - 1].values = newValues; } else { // Create a new id, value pair totalCheckpoints[numTotalCheckpoints].id = blockNumber; totalCheckpoints[numTotalCheckpoints].values = newValues; numTotalCheckpoints = numTotalCheckpoints.add(1); } emit TotalValuesChanged(oldValues, newValues); } } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } lt(source, sEnd) { } { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for { } slt(dest, dEnd) { } { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy(result.contentAddress(), b.contentAddress() + from, result.length); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { require(from <= to, "FROM_LESS_THAN_TO_REQUIRED"); require(to <= b.length, "TO_LESS_THAN_LENGTH_REQUIRED"); // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require(b.length > 0, "GREATER_THAN_ZERO_LENGTH_REQUIRED"); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Pops the last 20 bytes off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return result The 20 byte address that was popped off. function popLast20Bytes(bytes memory b) internal pure returns (address result) { require(b.length >= 20, "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"); // Store last 20 bytes. result = readAddress(b, b.length - 20); assembly { // Subtract 20 from byte array length. let newLen := sub(mload(b), 20) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return equal True if arrays are the same. False otherwise. function equals(bytes memory lhs, bytes memory rhs) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { require( b.length >= index + 20, // 20 is length of address "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return result bytes32 value from byte array. function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { require(b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return result bytes4 value from byte array. function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { require(b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Reads nested bytes from a specific position. /// @dev NOTE: the returned value overlaps with the input value. /// Both should be treated as immutable. /// @param b Byte array containing nested bytes. /// @param index Index of nested bytes. /// @return result Nested bytes. function readBytesWithLength(bytes memory b, uint256 index) internal pure returns (bytes memory result) { // Read length of nested bytes uint256 nestedBytesLength = readUint256(b, index); index += 32; // Assert length of <b> is valid, given // length of nested bytes require(b.length >= index + nestedBytesLength, "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"); // Return a pointer to the byte array as it exists inside `b` assembly { result := add(b, index) } return result; } /// @dev Inserts bytes at a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes to insert. function writeBytesWithLength( bytes memory b, uint256 index, bytes memory input ) internal pure { // Assert length of <b> is valid, given // length of input require( b.length >= index + 32 + input.length, // 32 bytes to store length "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED" ); // Copy <input> into <b> memCopy( b.contentAddress() + index, input.rawAddress(), // includes length of <input> input.length + 32 // +32 bytes to store <input> length ); } /// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length. /// @param dest Byte array that will be overwritten with source bytes. /// @param source Byte array to copy onto dest bytes. function deepCopyBytes(bytes memory dest, bytes memory source) internal pure { uint256 sourceLen = source.length; // Dest length must be >= source length, or some bytes would not be copied. require(dest.length >= sourceLen, "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"); memCopy(dest.contentAddress(), source.contentAddress(), sourceLen); } } // SPDX-License-Identifier: MIT /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 internal constant _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return result EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return result EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibPermit { struct Permit { address spender; // Spender uint256 value; // Value uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 LibPermit Schema // bytes32 constant internal EIP712_PERMIT_SCHEMA_HASH = keccak256(abi.encodePacked( // "Permit(", // "address spender,", // "uint256 value,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_PERMIT_SCHEMA_HASH = 0x58e19c95adc541dea238d3211d11e11e7def7d0c7fda4e10e0c45eb224ef2fb7; /// @dev Calculates Keccak-256 hash of the permit. /// @param permit The permit structure. /// @return permitHash Keccak-256 EIP712 hash of the permit. function getPermitHash(Permit memory permit, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 permitHash) { permitHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashPermit(permit)); return permitHash; } /// @dev Calculates EIP712 hash of the permit. /// @param permit The permit structure. /// @return result EIP712 hash of the permit. function hashPermit(Permit memory permit) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_PERMIT_SCHEMA_HASH; assembly { // Assert permit offset (this is an internal error that should never be triggered) if lt(permit, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(permit, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 160) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IInsuranceFund { function claimDDXFromInsuranceMining(address _claimant) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; import { DIFundToken } from "./DIFundToken.sol"; /** * @title DIFundTokenFactory * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DIFundTokenFactory { DIFundToken[] public diFundTokens; address public issuer; /** * @notice Construct a new DDX token */ constructor(address _issuer) public { // Set issuer to deploying address issuer = _issuer; } function createNewDIFundToken( string calldata _name, string calldata _symbol, uint8 _decimals ) external returns (address) { require(msg.sender == issuer, "DIFTF: unauthorized."); DIFundToken diFundToken = new DIFundToken(_name, _symbol, _decimals, issuer); diFundTokens.push(diFundToken); return address(diFundToken); } function getDIFundTokens() external view returns (DIFundToken[] memory) { return diFundTokens; } function getDIFundTokensLength() external view returns (uint256) { return diFundTokens.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../libs/LibBytes.sol"; import { LibEIP712 } from "../libs/LibEIP712.sol"; import { LibDelegation } from "../libs/LibDelegation.sol"; import { LibPermit } from "../libs/LibPermit.sol"; import { SafeMath96 } from "../libs/SafeMath96.sol"; /** * @title DDX * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is the native token contract for DerivaDEX. It * implements the ERC-20 standard, with additional * functionality to efficiently handle the governance aspect of * the DerivaDEX ecosystem. * @dev The contract makes use of some nonstandard types not seen in * the ERC-20 standard. The DDX token makes frequent use of the * uint96 data type, as opposed to the more standard uint256 type. * Given the maintenance of arrays of balances, allowances, and * voting checkpoints, this allows us to more efficiently pack * data together, thereby resulting in cheaper transactions. */ contract DDX { using SafeMath96 for uint96; using SafeMath for uint256; using LibBytes for bytes; /// @notice ERC20 token name for this token string public constant name = "DerivaDAO"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token symbol for this token string public constant symbol = "DDX"; // solhint-disable-line const-name-snakecase /// @notice ERC20 token decimals for this token uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase /// @notice Version number for this token. Used for EIP712 hashing. string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Max number of tokens to be issued (100 million DDX) uint96 public constant MAX_SUPPLY = 100000000e18; /// @notice Total number of tokens in circulation (50 million DDX) uint96 public constant PRE_MINE_SUPPLY = 50000000e18; /// @notice Issued supply of tokens uint96 public issuedSupply; /// @notice Current total/circulating supply of tokens uint96 public totalSupply; /// @notice Whether ownership has been transferred to the DAO bool public ownershipTransferred; /// @notice Address authorized to issue/mint DDX tokens address public issuer; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking vote count from given block struct Checkpoint { uint32 id; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice Emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice Emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint96 previousBalance, uint96 newBalance); /// @notice Emitted when transfer takes place event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when approval takes place event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new DDX token */ constructor() public { // Set issuer to deploying address issuer = msg.sender; // Issue pre-mine token supply to deploying address and // set the issued and circulating supplies to pre-mine amount _transferTokensMint(msg.sender, PRE_MINE_SUPPLY); } /** * @notice Transfer ownership of DDX token from the deploying * address to the DerivaDEX Proxy/DAO * @param _derivaDEXProxy DerivaDEX Proxy address */ function transferOwnershipToDerivaDEXProxy(address _derivaDEXProxy) external { // Ensure deploying address is calling this, destination is not // the zero address, and that ownership has never been // transferred thus far require(msg.sender == issuer, "DDX: unauthorized transfer of ownership."); require(_derivaDEXProxy != address(0), "DDX: transferring to zero address."); require(!ownershipTransferred, "DDX: ownership already transferred."); // Set ownership transferred boolean flag and the new authorized // issuer ownershipTransferred = true; issuer = _derivaDEXProxy; } /** * @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 (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address _spender, uint256 _amount) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, _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) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_addedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_addedValue, "DDX: amount exceeds 96 bits."); } // Increase allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].add96(amount); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); 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) external returns (bool) { require(_spender != address(0), "DDX: approve to the zero address."); // Convert amount to uint96 uint96 amount; if (_subtractedValue == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_subtractedValue, "DDX: amount exceeds 96 bits."); } // Decrease allowance allowances[msg.sender][_spender] = allowances[msg.sender][_spender].sub96( amount, "DDX: decreased allowance below zero." ); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } /** * @notice Get the number of tokens held by the `account` * @param _account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address _account) external view returns (uint256) { return balances[_account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address _recipient, uint256 _amount) external returns (bool) { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Transfer tokens from sender to recipient _transferTokens(msg.sender, _recipient, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param _from The address of the source account * @param _recipient The address of the destination account * @param _amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address _from, address _recipient, uint256 _amount ) external returns (bool) { uint96 spenderAllowance = allowances[_from][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _from && spenderAllowance != uint96(-1)) { // Tx sender is not the same as transfer sender and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount); allowances[_from][msg.sender] = newAllowance; emit Approval(_from, msg.sender, newAllowance); } // Transfer tokens from sender to recipient _transferTokens(_from, _recipient, amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function mint(address _recipient, uint256 _amount) external { require(msg.sender == issuer, "DDX: unauthorized mint."); // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Ensure the mint doesn't cause the issued supply to exceed // the total supply that could ever be issued require(issuedSupply.add96(amount) <= MAX_SUPPLY, "DDX: cap exceeded."); // Mint tokens to recipient _transferTokensMint(_recipient, amount); } /** * @dev Creates `amount` tokens and assigns them to `account`, decreasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function burn(uint256 _amount) external { // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } // Burn tokens from sender _transferTokensBurn(msg.sender, 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 burnFrom(address _account, uint256 _amount) external { uint96 spenderAllowance = allowances[_account][msg.sender]; // Convert amount to uint96 uint96 amount; if (_amount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_amount, "DDX: amount exceeds 96 bits."); } if (msg.sender != _account && spenderAllowance != uint96(-1)) { // Tx sender is not the same as burn account and doesn't // have unlimited allowance. // Reduce allowance by amount being transferred uint96 newAllowance = spenderAllowance.sub96(amount, "DDX: burn amount exceeds allowance."); allowances[_account][msg.sender] = newAllowance; emit Approval(_account, msg.sender, newAllowance); } // Burn tokens from account _transferTokensBurn(_account, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param _delegatee The address to delegate votes to */ function delegate(address _delegatee) external { _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 _signature Signature */ function delegateBySig( address _delegatee, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 delegationHash = LibDelegation.getDelegationHash( LibDelegation.Delegation({ delegatee: _delegatee, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(delegationHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Delegate votes from recovered address to delegatee _delegate(recovered, _delegatee); } /** * @notice Permits allowance from signatory to `spender` * @param _spender The spender being approved * @param _value The value being approved * @param _nonce The contract state required to match the signature * @param _expiry The time at which to expire the signature * @param _signature Signature */ function permit( address _spender, uint256 _value, uint256 _nonce, uint256 _expiry, bytes memory _signature ) external { // Perform EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 permitHash = LibPermit.getPermitHash( LibPermit.Permit({ spender: _spender, value: _value, nonce: _nonce, expiry: _expiry }), eip712OrderParamsDomainHash ); // Perform sig recovery uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } address recovered = ecrecover(permitHash, v, r, s); require(recovered != address(0), "DDX: invalid signature."); require(_nonce == nonces[recovered]++, "DDX: invalid nonce."); require(block.timestamp <= _expiry, "DDX: signature expired."); // Convert amount to uint96 uint96 amount; if (_value == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(_value, "DDX: amount exceeds 96 bits."); } // Set allowance allowances[recovered][_spender] = amount; emit Approval(recovered, _spender, _value); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param _account The address of the account holding the funds * @param _spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address _account, address _spender) external view returns (uint256) { return allowances[_account][_spender]; } /** * @notice Gets the current votes balance. * @param _account The address to get votes balance. * @return The number of current votes. */ function getCurrentVotes(address _account) external view returns (uint96) { uint256 numCheckpointsAccount = numCheckpoints[_account]; return numCheckpointsAccount > 0 ? checkpoints[_account][numCheckpointsAccount - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param _account The address of the account to check * @param _blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address _account, uint256 _blockNumber) external view returns (uint96) { require(_blockNumber < block.number, "DDX: block not yet determined."); uint256 numCheckpointsAccount = numCheckpoints[_account]; if (numCheckpointsAccount == 0) { return 0; } // First check most recent balance if (checkpoints[_account][numCheckpointsAccount - 1].id <= _blockNumber) { return checkpoints[_account][numCheckpointsAccount - 1].votes; } // Next check implicit zero balance if (checkpoints[_account][0].id > _blockNumber) { return 0; } // Perform binary search to find the most recent token holdings // leading to a measure of voting power uint256 lower = 0; uint256 upper = numCheckpointsAccount - 1; while (upper > lower) { // ceil, avoiding overflow uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[_account][center]; if (cp.id == _blockNumber) { return cp.votes; } else if (cp.id < _blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[_account][lower].votes; } function _delegate(address _delegator, address _delegatee) internal { // Get the current address delegator has delegated address currentDelegate = _getDelegatee(_delegator); // Get delegator's DDX balance uint96 delegatorBalance = balances[_delegator]; // Set delegator's new delegatee address delegates[_delegator] = _delegatee; emit DelegateChanged(_delegator, currentDelegate, _delegatee); // Move votes from currently-delegated address to // new address _moveDelegates(currentDelegate, _delegatee, delegatorBalance); } function _transferTokens( address _spender, address _recipient, uint96 _amount ) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Reduce spender's balance and increase recipient balance balances[_spender] = balances[_spender].sub96(_amount); balances[_recipient] = balances[_recipient].add96(_amount); emit Transfer(_spender, _recipient, _amount); // Move votes from currently-delegated address to // recipient's delegated address _moveDelegates(_getDelegatee(_spender), _getDelegatee(_recipient), _amount); } function _transferTokensMint(address _recipient, uint96 _amount) internal { require(_recipient != address(0), "DDX: cannot transfer to the zero address."); // Add to recipient's balance balances[_recipient] = balances[_recipient].add96(_amount); // Increase the issued supply and circulating supply issuedSupply = issuedSupply.add96(_amount); totalSupply = totalSupply.add96(_amount); emit Transfer(address(0), _recipient, _amount); // Add delegates to recipient's delegated address _moveDelegates(address(0), _getDelegatee(_recipient), _amount); } function _transferTokensBurn(address _spender, uint96 _amount) internal { require(_spender != address(0), "DDX: cannot transfer from the zero address."); // Reduce the spender/burner's balance balances[_spender] = balances[_spender].sub96(_amount, "DDX: not enough balance to burn."); // Reduce the total supply totalSupply = totalSupply.sub96(_amount); emit Transfer(_spender, address(0), _amount); // MRedduce delegates from spender's delegated address _moveDelegates(_getDelegatee(_spender), address(0), _amount); } function _moveDelegates( address _initDel, address _finDel, uint96 _amount ) internal { if (_initDel != _finDel && _amount > 0) { // Initial delegated address is different than final // delegated address and nonzero number of votes moved if (_initDel != address(0)) { uint256 initDelNum = numCheckpoints[_initDel]; // Retrieve and compute the old and new initial delegate // address' votes uint96 initDelOld = initDelNum > 0 ? checkpoints[_initDel][initDelNum - 1].votes : 0; uint96 initDelNew = initDelOld.sub96(_amount); _writeCheckpoint(_initDel, initDelOld, initDelNew); } if (_finDel != address(0)) { uint256 finDelNum = numCheckpoints[_finDel]; // Retrieve and compute the old and new final delegate // address' votes uint96 finDelOld = finDelNum > 0 ? checkpoints[_finDel][finDelNum - 1].votes : 0; uint96 finDelNew = finDelOld.add96(_amount); _writeCheckpoint(_finDel, finDelOld, finDelNew); } } } function _writeCheckpoint( address _delegatee, uint96 _oldVotes, uint96 _newVotes ) internal { uint32 blockNumber = safe32(block.number, "DDX: exceeds 32 bits."); uint256 delNum = numCheckpoints[_delegatee]; if (delNum > 0 && checkpoints[_delegatee][delNum - 1].id == blockNumber) { // If latest checkpoint is current block, edit in place checkpoints[_delegatee][delNum - 1].votes = _newVotes; } else { // Create a new id, vote pair checkpoints[_delegatee][delNum] = Checkpoint({ id: blockNumber, votes: _newVotes }); numCheckpoints[_delegatee] = delNum.add(1); } emit DelegateVotesChanged(_delegatee, _oldVotes, _newVotes); } function _getDelegatee(address _delegator) internal view returns (address) { if (delegates[_delegator] == address(0)) { return _delegator; } return delegates[_delegator]; } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibDelegation { struct Delegation { address delegatee; // Delegatee uint256 nonce; // Nonce uint256 expiry; // Expiry } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_DELEGATION_SCHEMA_HASH = keccak256(abi.encodePacked( // "Delegation(", // "address delegatee,", // "uint256 nonce,", // "uint256 expiry", // ")" // )); bytes32 internal constant EIP712_DELEGATION_SCHEMA_HASH = 0xe48329057bfd03d55e49b547132e39cffd9c1820ad7b9d4c5307691425d15adf; /// @dev Calculates Keccak-256 hash of the delegation. /// @param delegation The delegation structure. /// @return delegationHash Keccak-256 EIP712 hash of the delegation. function getDelegationHash(Delegation memory delegation, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 delegationHash) { delegationHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashDelegation(delegation)); return delegationHash; } /// @dev Calculates EIP712 hash of the delegation. /// @param delegation The delegation structure. /// @return result EIP712 hash of the delegation. function hashDelegation(Delegation memory delegation) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_DELEGATION_SCHEMA_HASH; assembly { // Assert delegation offset (this is an internal error that should never be triggered) if lt(delegation, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(delegation, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 128) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.12; import { LibEIP712 } from "./LibEIP712.sol"; library LibVoteCast { struct VoteCast { uint128 proposalId; // Proposal ID bool support; // Support } // Hash for the EIP712 OrderParams Schema // bytes32 constant internal EIP712_VOTE_CAST_SCHEMA_HASH = keccak256(abi.encodePacked( // "VoteCast(", // "uint128 proposalId,", // "bool support", // ")" // )); bytes32 internal constant EIP712_VOTE_CAST_SCHEMA_HASH = 0x4abb8ae9facc09d5584ac64f616551bfc03c3ac63e5c431132305bd9bc8f8246; /// @dev Calculates Keccak-256 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return voteCastHash Keccak-256 EIP712 hash of the vote cast. function getVoteCastHash(VoteCast memory voteCast, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 voteCastHash) { voteCastHash = LibEIP712.hashEIP712Message(eip712ExchangeDomainHash, hashVoteCast(voteCast)); return voteCastHash; } /// @dev Calculates EIP712 hash of the vote cast. /// @param voteCast The vote cast structure. /// @return result EIP712 hash of the vote cast. function hashVoteCast(VoteCast memory voteCast) internal pure returns (bytes32 result) { // Assembly for more efficiently computing: bytes32 schemaHash = EIP712_VOTE_CAST_SCHEMA_HASH; assembly { // Assert vote cast offset (this is an internal error that should never be triggered) if lt(voteCast, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(voteCast, 32) // Backup let temp1 := mload(pos1) // Hash in place mstore(pos1, schemaHash) result := keccak256(pos1, 96) // Restore mstore(pos1, temp1) } return result; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { GovernanceDefs } from "../../libs/defs/GovernanceDefs.sol"; import { LibEIP712 } from "../../libs/LibEIP712.sol"; import { LibVoteCast } from "../../libs/LibVoteCast.sol"; import { LibBytes } from "../../libs/LibBytes.sol"; import { SafeMath32 } from "../../libs/SafeMath32.sol"; import { SafeMath96 } from "../../libs/SafeMath96.sol"; import { SafeMath128 } from "../../libs/SafeMath128.sol"; import { MathHelpers } from "../../libs/MathHelpers.sol"; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStorageGovernance } from "../../storage/LibDiamondStorageGovernance.sol"; /** * @title Governance * @author DerivaDEX (Borrowed/inspired from Compound) * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to governance. The Diamond storage * will only be affected when facet functions are called via * the proxy contract, no checks are necessary. * @dev The Diamond storage will only be affected when facet functions * are called via the proxy contract, no checks are necessary. */ contract Governance { using SafeMath32 for uint32; using SafeMath96 for uint96; using SafeMath128 for uint128; using SafeMath for uint256; using MathHelpers for uint96; using MathHelpers for uint256; using LibBytes for bytes; /// @notice name for this Governance contract string public constant name = "DDX Governance"; // solhint-disable-line const-name-snakecase /// @notice version for this Governance contract string public constant version = "1"; // solhint-disable-line const-name-snakecase /// @notice Emitted when a new proposal is created event ProposalCreated( uint128 indexed id, address indexed proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /// @notice Emitted when a vote has been cast on a proposal event VoteCast(address indexed voter, uint128 indexed proposalId, bool support, uint96 votes); /// @notice Emitted when a proposal has been canceled event ProposalCanceled(uint128 indexed id); /// @notice Emitted when a proposal has been queued event ProposalQueued(uint128 indexed id, uint256 eta); /// @notice Emitted when a proposal has been executed event ProposalExecuted(uint128 indexed id); /// @notice Emitted when a proposal action has been canceled event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been executed event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /// @notice Emitted when a proposal action has been queued event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Governance: must be called by Governance admin."); _; } /** * @notice This function initializes the state with some critical * information. This can only be called once and must be * done via governance. * @dev This function is best called as a parameter to the * diamond cut function. This is removed prior to the selectors * being added to the diamond, meaning it cannot be called * again. * @param _quorumVotes Minimum number of for votes required, even * if there's a majority in favor. * @param _proposalThreshold Minimum DDX token holdings required * to create a proposal * @param _proposalMaxOperations Max number of operations/actions a * proposal can have * @param _votingDelay Number of blocks after a proposal is made * that voting begins. * @param _votingPeriod Number of blocks voting will be held. * @param _skipRemainingVotingThreshold Number of for or against * votes that are necessary to skip the remainder of the * voting period. * @param _gracePeriod Period in which a successful proposal must be * executed, otherwise will be expired. * @param _timelockDelay Time (s) in which a successful proposal * must be in the queue before it can be executed. */ function initialize( uint32 _proposalMaxOperations, uint32 _votingDelay, uint32 _votingPeriod, uint32 _gracePeriod, uint32 _timelockDelay, uint32 _quorumVotes, uint32 _proposalThreshold, uint32 _skipRemainingVotingThreshold ) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure state variable comparisons are valid requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, _quorumVotes); // Set initial variable values dsGovernance.proposalMaxOperations = _proposalMaxOperations; dsGovernance.votingDelay = _votingDelay; dsGovernance.votingPeriod = _votingPeriod; dsGovernance.gracePeriod = _gracePeriod; dsGovernance.timelockDelay = _timelockDelay; dsGovernance.quorumVotes = _quorumVotes; dsGovernance.proposalThreshold = _proposalThreshold; dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; dsGovernance.fastPathFunctionSignatures["setIsPaused(bool)"] = true; } /** * @notice This function allows participants who have sufficient * DDX holdings to create new proposals up for vote. The * proposals contain the ordered lists of on-chain * executable calldata. * @param _targets Addresses of contracts involved. * @param _values Values to be passed along with the calls. * @param _signatures Function signatures. * @param _calldatas Calldata passed to the function. * @param _description Text description of proposal. */ function propose( address[] memory _targets, uint256[] memory _values, string[] memory _signatures, bytes[] memory _calldatas, string memory _description ) external returns (uint128) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposer has sufficient token holdings to propose require( dsDerivaDEX.ddxToken.getPriorVotes(msg.sender, block.number.sub(1)) >= getProposerThresholdCount(), "Governance: proposer votes below proposal threshold." ); require( _targets.length == _values.length && _targets.length == _signatures.length && _targets.length == _calldatas.length, "Governance: proposal function information parity mismatch." ); require(_targets.length != 0, "Governance: must provide actions."); require(_targets.length <= dsGovernance.proposalMaxOperations, "Governance: too many actions."); if (dsGovernance.latestProposalIds[msg.sender] != 0) { // Ensure proposer doesn't already have one active/pending GovernanceDefs.ProposalState proposersLatestProposalState = state(dsGovernance.latestProposalIds[msg.sender]); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Active, "Governance: one live proposal per proposer, found an already active proposal." ); require( proposersLatestProposalState != GovernanceDefs.ProposalState.Pending, "Governance: one live proposal per proposer, found an already pending proposal." ); } // Proposal voting starts votingDelay after proposal is made uint256 startBlock = block.number.add(dsGovernance.votingDelay); // Increment count of proposals dsGovernance.proposalCount++; // Create new proposal struct and add to mapping GovernanceDefs.Proposal memory newProposal = GovernanceDefs.Proposal({ id: dsGovernance.proposalCount, proposer: msg.sender, delay: getTimelockDelayForSignatures(_signatures), eta: 0, targets: _targets, values: _values, signatures: _signatures, calldatas: _calldatas, startBlock: startBlock, endBlock: startBlock.add(dsGovernance.votingPeriod), forVotes: 0, againstVotes: 0, canceled: false, executed: false }); dsGovernance.proposals[newProposal.id] = newProposal; // Update proposer's latest proposal dsGovernance.latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, _targets, _values, _signatures, _calldatas, startBlock, startBlock.add(dsGovernance.votingPeriod), _description ); return newProposal.id; } /** * @notice This function allows any participant to queue a * successful proposal for execution. Proposals are deemed * successful if at any point the number of for votes has * exceeded the skip remaining voting threshold or if there * is a simple majority (and more for votes than the * minimum quorum) at the end of voting. * @param _proposalId Proposal id. */ function queue(uint128 _proposalId) external { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal has succeeded (i.e. it has either enough for // votes to skip the remainder of the voting period or the // voting period has ended and there is a simple majority in // favor and also above the quorum require( state(_proposalId) == GovernanceDefs.ProposalState.Succeeded, "Governance: proposal can only be queued if it is succeeded." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Establish eta of execution, which is a number of seconds // after queuing at which point proposal can actually execute uint256 eta = block.timestamp.add(proposal.delay); for (uint256 i = 0; i < proposal.targets.length; i++) { // Ensure proposal action is not already in the queue bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ) ); require(!dsGovernance.queuedTransactions[txHash], "Governance: proposal action already queued at eta."); dsGovernance.queuedTransactions[txHash] = true; emit QueueTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ); } // Set proposal eta timestamp after which it can be executed proposal.eta = eta; emit ProposalQueued(_proposalId, eta); } /** * @notice This function allows any participant to execute a * queued proposal. A proposal in the queue must be in the * queue for the delay period it was proposed with prior to * executing, allowing the community to position itself * accordingly. * @param _proposalId Proposal id. */ function execute(uint128 _proposalId) external payable { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); // Ensure proposal is queued require( state(_proposalId) == GovernanceDefs.ProposalState.Queued, "Governance: proposal can only be executed if it is queued." ); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposal has been in the queue long enough require(block.timestamp >= proposal.eta, "Governance: proposal hasn't finished queue time length."); // Ensure proposal hasn't been in the queue for too long require(block.timestamp <= proposal.eta.add(dsGovernance.gracePeriod), "Governance: transaction is stale."); proposal.executed = true; // Loop through each of the actions in the proposal for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); require(dsGovernance.queuedTransactions[txHash], "Governance: transaction hasn't been queued."); dsGovernance.queuedTransactions[txHash] = false; // Execute action bytes memory callData; require(bytes(proposal.signatures[i]).length != 0, "Governance: Invalid function signature."); callData = abi.encodePacked(bytes4(keccak256(bytes(proposal.signatures[i]))), proposal.calldatas[i]); // solium-disable-next-line security/no-call-value (bool success, ) = proposal.targets[i].call{ value: proposal.values[i] }(callData); require(success, "Governance: transaction execution reverted."); emit ExecuteTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalExecuted(_proposalId); } /** * @notice This function allows any participant to cancel any non- * executed proposal. It can be canceled if the proposer's * token holdings has dipped below the proposal threshold * at the time of cancellation. * @param _proposalId Proposal id. */ function cancel(uint128 _proposalId) external { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.ProposalState state = state(_proposalId); // Ensure proposal hasn't executed require(state != GovernanceDefs.ProposalState.Executed, "Governance: cannot cancel executed proposal."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Ensure proposer's token holdings has dipped below the // proposer threshold, leaving their proposal subject to // cancellation require( dsDerivaDEX.ddxToken.getPriorVotes(proposal.proposer, block.number.sub(1)) < getProposerThresholdCount(), "Governance: proposer above threshold." ); proposal.canceled = true; // Loop through each of the proposal's actions for (uint256 i = 0; i < proposal.targets.length; i++) { bytes32 txHash = keccak256( abi.encode( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ) ); dsGovernance.queuedTransactions[txHash] = false; emit CancelTransaction( txHash, proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalCanceled(_proposalId); } /** * @notice This function allows participants to cast either in * favor or against a particular proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). */ function castVote(uint128 _proposalId, bool _support) external { return _castVote(msg.sender, _proposalId, _support); } /** * @notice This function allows participants to cast votes with * offline signatures in favor or against a particular * proposal. * @param _proposalId Proposal id. * @param _support In favor (true) or against (false). * @param _signature Signature */ function castVoteBySig( uint128 _proposalId, bool _support, bytes memory _signature ) external { // EIP712 hashing logic bytes32 eip712OrderParamsDomainHash = LibEIP712.hashEIP712Domain(name, version, getChainId(), address(this)); bytes32 voteCastHash = LibVoteCast.getVoteCastHash( LibVoteCast.VoteCast({ proposalId: _proposalId, support: _support }), eip712OrderParamsDomainHash ); // Recover the signature and EIP712 hash uint8 v = uint8(_signature[0]); bytes32 r = _signature.readBytes32(1); bytes32 s = _signature.readBytes32(33); address recovered = ecrecover(voteCastHash, v, r, s); require(recovered != address(0), "Governance: invalid signature."); return _castVote(recovered, _proposalId, _support); } /** * @notice This function sets the quorum votes required for a * proposal to pass. It must be called via * governance. * @param _quorumVotes Quorum votes threshold. */ function setQuorumVotes(uint32 _quorumVotes) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireSkipRemainingVotingThresholdGtQuorumVotes(dsGovernance.skipRemainingVotingThreshold, _quorumVotes); dsGovernance.quorumVotes = _quorumVotes; } /** * @notice This function sets the token holdings threshold required * to propose something. It must be called via * governance. * @param _proposalThreshold Proposal threshold. */ function setProposalThreshold(uint32 _proposalThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalThreshold = _proposalThreshold; } /** * @notice This function sets the max operations a proposal can * carry out. It must be called via governance. * @param _proposalMaxOperations Proposal's max operations. */ function setProposalMaxOperations(uint32 _proposalMaxOperations) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.proposalMaxOperations = _proposalMaxOperations; } /** * @notice This function sets the voting delay in blocks from when * a proposal is made and voting begins. It must be called * via governance. * @param _votingDelay Voting delay (blocks). */ function setVotingDelay(uint32 _votingDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingDelay = _votingDelay; } /** * @notice This function sets the voting period in blocks that a * vote will last. It must be called via * governance. * @param _votingPeriod Voting period (blocks). */ function setVotingPeriod(uint32 _votingPeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.votingPeriod = _votingPeriod; } /** * @notice This function sets the threshold at which a proposal can * immediately be deemed successful or rejected if the for * or against votes exceeds this threshold, even if the * voting period is still ongoing. It must be called * governance. * @param _skipRemainingVotingThreshold Threshold for or against * votes must reach to skip remainder of voting period. */ function setSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); requireValidSkipRemainingVotingThreshold(_skipRemainingVotingThreshold); requireSkipRemainingVotingThresholdGtQuorumVotes(_skipRemainingVotingThreshold, dsGovernance.quorumVotes); dsGovernance.skipRemainingVotingThreshold = _skipRemainingVotingThreshold; } /** * @notice This function sets the grace period in seconds that a * queued proposal can last before expiring. It must be * called via governance. * @param _gracePeriod Grace period (seconds). */ function setGracePeriod(uint32 _gracePeriod) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.gracePeriod = _gracePeriod; } /** * @notice This function sets the timelock delay (s) a proposal * must be queued before execution. * @param _timelockDelay Timelock delay (seconds). */ function setTimelockDelay(uint32 _timelockDelay) external onlyAdmin { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); dsGovernance.timelockDelay = _timelockDelay; } /** * @notice This function allows any participant to retrieve * the actions involved in a given proposal. * @param _proposalId Proposal id. * @return targets Addresses of contracts involved. * @return values Values to be passed along with the calls. * @return signatures Function signatures. * @return calldatas Calldata passed to the function. */ function getActions(uint128 _proposalId) external view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal storage p = dsGovernance.proposals[_proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice This function allows any participant to retrieve * the receipt for a given proposal and voter. * @param _proposalId Proposal id. * @param _voter Voter address. * @return Voter receipt. */ function getReceipt(uint128 _proposalId, address _voter) external view returns (GovernanceDefs.Receipt memory) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposals[_proposalId].receipts[_voter]; } /** * @notice This function gets a proposal from an ID. * @param _proposalId Proposal id. * @return Proposal attributes. */ function getProposal(uint128 _proposalId) external view returns ( bool, bool, address, uint32, uint96, uint96, uint128, uint256, uint256, uint256 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); GovernanceDefs.Proposal memory proposal = dsGovernance.proposals[_proposalId]; return ( proposal.canceled, proposal.executed, proposal.proposer, proposal.delay, proposal.forVotes, proposal.againstVotes, proposal.id, proposal.eta, proposal.startBlock, proposal.endBlock ); } /** * @notice This function gets whether a proposal action transaction * hash is queued or not. * @param _txHash Proposal action tx hash. * @return Is proposal action transaction hash queued or not. */ function getIsQueuedTransaction(bytes32 _txHash) external view returns (bool) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.queuedTransactions[_txHash]; } /** * @notice This function gets the Governance facet's current * parameters. * @return Proposal max operations. * @return Voting delay. * @return Voting period. * @return Grace period. * @return Timelock delay. * @return Quorum votes threshold. * @return Proposal threshold. * @return Skip remaining voting threshold. */ function getGovernanceParameters() external view returns ( uint32, uint32, uint32, uint32, uint32, uint32, uint32, uint32 ) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return ( dsGovernance.proposalMaxOperations, dsGovernance.votingDelay, dsGovernance.votingPeriod, dsGovernance.gracePeriod, dsGovernance.timelockDelay, dsGovernance.quorumVotes, dsGovernance.proposalThreshold, dsGovernance.skipRemainingVotingThreshold ); } /** * @notice This function gets the proposal count. * @return Proposal count. */ function getProposalCount() external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.proposalCount; } /** * @notice This function gets the latest proposal ID for a user. * @param _proposer Proposer's address. * @return Proposal ID. */ function getLatestProposalId(address _proposer) external view returns (uint128) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); return dsGovernance.latestProposalIds[_proposer]; } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getQuorumVoteCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.quorumVotes, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getProposerThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.proposalThreshold, 100); } /** * @notice This function gets the quorum vote count given the * quorum vote percentage relative to the total DDX supply. * @return Quorum vote count. */ function getSkipRemainingVotingThresholdCount() public view returns (uint96) { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); uint96 totalSupply = dsDerivaDEX.ddxToken.totalSupply().safe96("Governance: amount exceeds 96 bits"); return totalSupply.proportion96(dsGovernance.skipRemainingVotingThreshold, 100); } /** * @notice This function retrieves the status for any given * proposal. * @param _proposalId Proposal id. * @return Status of proposal. */ function state(uint128 _proposalId) public view returns (GovernanceDefs.ProposalState) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(dsGovernance.proposalCount >= _proposalId && _proposalId > 0, "Governance: invalid proposal id."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; // Note the 3rd conditional where we can escape out of the vote // phase if the for or against votes exceeds the skip remaining // voting threshold if (proposal.canceled) { return GovernanceDefs.ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return GovernanceDefs.ProposalState.Pending; } else if ( (block.number <= proposal.endBlock) && (proposal.forVotes < getSkipRemainingVotingThresholdCount()) && (proposal.againstVotes < getSkipRemainingVotingThresholdCount()) ) { return GovernanceDefs.ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < getQuorumVoteCount()) { return GovernanceDefs.ProposalState.Defeated; } else if (proposal.eta == 0) { return GovernanceDefs.ProposalState.Succeeded; } else if (proposal.executed) { return GovernanceDefs.ProposalState.Executed; } else if (block.timestamp >= proposal.eta.add(dsGovernance.gracePeriod)) { return GovernanceDefs.ProposalState.Expired; } else { return GovernanceDefs.ProposalState.Queued; } } function _castVote( address _voter, uint128 _proposalId, bool _support ) internal { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); require(state(_proposalId) == GovernanceDefs.ProposalState.Active, "Governance: voting is closed."); GovernanceDefs.Proposal storage proposal = dsGovernance.proposals[_proposalId]; GovernanceDefs.Receipt storage receipt = proposal.receipts[_voter]; // Ensure voter has not already voted require(!receipt.hasVoted, "Governance: voter already voted."); // Obtain the token holdings (voting power) for participant at // the time voting started. They may have gained or lost tokens // since then, doesn't matter. uint96 votes = dsDerivaDEX.ddxToken.getPriorVotes(_voter, proposal.startBlock); // Ensure voter has nonzero voting power require(votes > 0, "Governance: voter has no voting power."); if (_support) { // Increment the for votes in favor proposal.forVotes = proposal.forVotes.add96(votes); } else { // Increment the against votes proposal.againstVotes = proposal.againstVotes.add96(votes); } // Set receipt attributes based on cast vote parameters receipt.hasVoted = true; receipt.support = _support; receipt.votes = votes; emit VoteCast(_voter, _proposalId, _support, votes); } function getTimelockDelayForSignatures(string[] memory _signatures) internal view returns (uint32) { LibDiamondStorageGovernance.DiamondStorageGovernance storage dsGovernance = LibDiamondStorageGovernance.diamondStorageGovernance(); for (uint256 i = 0; i < _signatures.length; i++) { if (!dsGovernance.fastPathFunctionSignatures[_signatures[i]]) { return dsGovernance.timelockDelay; } } return 1; } function requireSkipRemainingVotingThresholdGtQuorumVotes(uint32 _skipRemainingVotingThreshold, uint32 _quorumVotes) internal pure { require(_skipRemainingVotingThreshold > _quorumVotes, "Governance: skip rem votes must be higher than quorum."); } function requireValidSkipRemainingVotingThreshold(uint32 _skipRemainingVotingThreshold) internal pure { require(_skipRemainingVotingThreshold >= 50, "Governance: skip rem votes must be higher than 50pct."); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title GovernanceDefs * @author DerivaDEX * * This library contains the common structs and enums pertaining to * the governance. */ library GovernanceDefs { struct Proposal { bool canceled; bool executed; address proposer; uint32 delay; uint96 forVotes; uint96 againstVotes; uint128 id; uint256 eta; address[] targets; string[] signatures; bytes[] calldatas; uint256[] values; uint256 startBlock; uint256 endBlock; mapping(address => Receipt) receipts; } struct Receipt { bool hasVoted; bool support; uint96 votes; } enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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( uint128 a, uint128 b, string memory errorMessage ) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { GovernanceDefs } from "../libs/defs/GovernanceDefs.sol"; library LibDiamondStorageGovernance { struct DiamondStorageGovernance { // Proposal struct by ID mapping(uint256 => GovernanceDefs.Proposal) proposals; // Latest proposal IDs by proposer address mapping(address => uint128) latestProposalIds; // Whether transaction hash is currently queued mapping(bytes32 => bool) queuedTransactions; // Fast path for governance mapping(string => bool) fastPathFunctionSignatures; // Max number of operations/actions a proposal can have uint32 proposalMaxOperations; // Number of blocks after a proposal is made that voting begins // (e.g. 1 block) uint32 votingDelay; // Number of blocks voting will be held // (e.g. 17280 blocks ~ 3 days of blocks) uint32 votingPeriod; // Time window (s) a successful proposal must be executed, // otherwise will be expired, measured in seconds // (e.g. 1209600 seconds) uint32 gracePeriod; // Minimum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 0 seconds) uint32 minimumDelay; // Maximum time (s) in which a successful proposal must be // in the queue before it can be executed // (e.g. 2592000 seconds ~ 30 days) uint32 maximumDelay; // Minimum number of for votes required, even if there's a // majority in favor // (e.g. 2000000e18 ~ 4% of pre-mine DDX supply) uint32 quorumVotes; // Minimum DDX token holdings required to create a proposal // (e.g. 500000e18 ~ 1% of pre-mine DDX supply) uint32 proposalThreshold; // Number of for or against votes that are necessary to skip // the remainder of the voting period // (e.g. 25000000e18 tokens/votes) uint32 skipRemainingVotingThreshold; // Time (s) proposals must be queued before executing uint32 timelockDelay; // Total number of proposals uint128 proposalCount; } bytes32 constant DIAMOND_STORAGE_POSITION_GOVERNANCE = keccak256("diamond.standard.diamond.storage.DerivaDEX.Governance"); function diamondStorageGovernance() internal pure returns (DiamondStorageGovernance storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION_GOVERNANCE; assembly { ds_slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { LibDiamondStorageDerivaDEX } from "../../storage/LibDiamondStorageDerivaDEX.sol"; import { LibDiamondStoragePause } from "../../storage/LibDiamondStoragePause.sol"; /** * @title Pause * @author DerivaDEX * @notice This is a facet to the DerivaDEX proxy contract that handles * the logic pertaining to pausing functionality. The purpose * of this is to ensure the system can pause in the unlikely * scenario of a bug or issue materially jeopardizing users' * funds or experience. This facet will be removed entirely * as the system stabilizes shortly. It's important to note that * unlike the vast majority of projects, even during this * short-lived period of time in which the system can be paused, * no single admin address can wield this power, but rather * pausing must be carried out via governance. */ contract Pause { event PauseInitialized(); event IsPausedSet(bool isPaused); /** * @notice Limits functions to only be called via governance. */ modifier onlyAdmin { LibDiamondStorageDerivaDEX.DiamondStorageDerivaDEX storage dsDerivaDEX = LibDiamondStorageDerivaDEX.diamondStorageDerivaDEX(); require(msg.sender == dsDerivaDEX.admin, "Pause: must be called by Gov."); _; } /** * @notice This function initializes the facet. */ function initialize() external onlyAdmin { emit PauseInitialized(); } /** * @notice This function sets the paused status. * @param _isPaused Whether contracts are paused or not. */ function setIsPaused(bool _isPaused) external onlyAdmin { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); dsPause.isPaused = _isPaused; emit IsPausedSet(_isPaused); } /** * @notice This function gets whether the contract ecosystem is * currently paused. * @return Whether contracts are paused or not. */ function getIsPaused() public view returns (bool) { LibDiamondStoragePause.DiamondStoragePause storage dsPause = LibDiamondStoragePause.diamondStoragePause(); return dsPause.isPaused; } } // SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2019-07-18 */ pragma solidity 0.6.12; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Ownable } from "openzeppelin-solidity/contracts/access/Ownable.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; library Roles { struct Role { mapping(address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract PauserRole is Ownable { using Roles for Roles.Role; Roles.Role private _pausers; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyOwner { _addPauser(account); } function removePauser(address account) public onlyOwner { _removePauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract Pausable is PauserRole { bool private _paused; event Paused(address account); event Unpaused(address account); constructor() internal { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } contract ERC20 is IERC20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; event Issue(address indexed account, uint256 amount); event Redeem(address indexed account, uint256 value); function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public virtual override returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 value ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _issue(address account, uint256 amount) internal { require(account != address(0), "CoinFactory: issue to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); emit Issue(account, amount); } function _redeem(address account, uint256 value) internal { require(account != address(0), "CoinFactory: redeem from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); emit Redeem(account, value); } } contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public virtual override whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public virtual override whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } contract CoinFactoryAdminRole is Ownable { using Roles for Roles.Role; event CoinFactoryAdminRoleAdded(address indexed account); event CoinFactoryAdminRoleRemoved(address indexed account); Roles.Role private _coinFactoryAdmins; constructor() internal { _addCoinFactoryAdmin(msg.sender); } modifier onlyCoinFactoryAdmin() { require(isCoinFactoryAdmin(msg.sender), "CoinFactoryAdminRole: caller does not have the CoinFactoryAdmin role"); _; } function isCoinFactoryAdmin(address account) public view returns (bool) { return _coinFactoryAdmins.has(account); } function addCoinFactoryAdmin(address account) public onlyOwner { _addCoinFactoryAdmin(account); } function removeCoinFactoryAdmin(address account) public onlyOwner { _removeCoinFactoryAdmin(account); } function renounceCoinFactoryAdmin() public { _removeCoinFactoryAdmin(msg.sender); } function _addCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.add(account); emit CoinFactoryAdminRoleAdded(account); } function _removeCoinFactoryAdmin(address account) internal { _coinFactoryAdmins.remove(account); emit CoinFactoryAdminRoleRemoved(account); } } contract CoinFactory is ERC20, CoinFactoryAdminRole { function issue(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _issue(account, amount); return true; } function redeem(address account, uint256 amount) public onlyCoinFactoryAdmin returns (bool) { _redeem(account, amount); return true; } } contract BlacklistAdminRole is Ownable { using Roles for Roles.Role; event BlacklistAdminAdded(address indexed account); event BlacklistAdminRemoved(address indexed account); Roles.Role private _blacklistAdmins; constructor() internal { _addBlacklistAdmin(msg.sender); } modifier onlyBlacklistAdmin() { require(isBlacklistAdmin(msg.sender), "BlacklistAdminRole: caller does not have the BlacklistAdmin role"); _; } function isBlacklistAdmin(address account) public view returns (bool) { return _blacklistAdmins.has(account); } function addBlacklistAdmin(address account) public onlyOwner { _addBlacklistAdmin(account); } function removeBlacklistAdmin(address account) public onlyOwner { _removeBlacklistAdmin(account); } function renounceBlacklistAdmin() public { _removeBlacklistAdmin(msg.sender); } function _addBlacklistAdmin(address account) internal { _blacklistAdmins.add(account); emit BlacklistAdminAdded(account); } function _removeBlacklistAdmin(address account) internal { _blacklistAdmins.remove(account); emit BlacklistAdminRemoved(account); } } contract Blacklist is ERC20, BlacklistAdminRole { mapping(address => bool) private _blacklist; event BlacklistAdded(address indexed account); event BlacklistRemoved(address indexed account); function addBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _addBlacklist(accounts[i]); } } function removeBlacklist(address[] memory accounts) public onlyBlacklistAdmin returns (bool) { for (uint256 i = 0; i < accounts.length; i++) { _removeBlacklist(accounts[i]); } } function isBlacklist(address account) public view returns (bool) { return _blacklist[account]; } function _addBlacklist(address account) internal { _blacklist[account] = true; emit BlacklistAdded(account); } function _removeBlacklist(address account) internal { _blacklist[account] = false; emit BlacklistRemoved(account); } } contract HDUMToken is ERC20, ERC20Pausable, CoinFactory, Blacklist { string public name; string public symbol; uint8 public decimals; uint256 private _totalSupply; constructor( string memory _name, string memory _symbol, uint8 _decimals ) public { _totalSupply = 0; name = _name; symbol = _symbol; decimals = _decimals; } function transfer(address to, uint256 value) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public override(ERC20, ERC20Pausable) whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "HDUMToken: caller in blacklist can't transferFrom"); require(!isBlacklist(from), "HDUMToken: from in blacklist can't transfer"); require(!isBlacklist(to), "HDUMToken: not allow to transfer to recipient address in blacklist"); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override(ERC20, ERC20Pausable) returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import { Context } from "openzeppelin-solidity/contracts/GSN/Context.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; contract SafeERC20Wrapper is Context { using SafeERC20 for IERC20; IERC20 private _token; constructor(IERC20 token) public { _token = token; } function transfer(address recipient, uint256 amount) public { _token.safeTransfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public { _token.safeTransferFrom(sender, recipient, amount); } function approve(address spender, uint256 amount) public { _token.safeApprove(spender, amount); } function increaseAllowance(address spender, uint256 amount) public { _token.safeIncreaseAllowance(spender, amount); } function decreaseAllowance(address spender, uint256 amount) public { _token.safeDecreaseAllowance(spender, amount); } function allowance(address owner, address spender) public view returns (uint256) { return _token.allowance(owner, spender); } function balanceOf(address account) public view returns (uint256) { return _token.balanceOf(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; // mock class using ERC20 contract DummyToken is ERC20 { uint256 public constant INITIAL_SUPPLY = 100000000 * (10**18); constructor(string memory name, string memory symbol) public payable ERC20(name, symbol) { _mint(msg.sender, INITIAL_SUPPLY); } function mint(address account, uint256 amount) public { _mint(account, amount); } function burn(address account, uint256 amount) public { _burn(account, amount); } function transferInternal( address from, address to, uint256 value ) public { _transfer(from, to, value); } function approveInternal( address owner, address spender, uint256 value ) public { _approve(owner, spender, value); } }
Writes a uint256 into a specific position in a byte array. b Byte array to insert <input> into. index Index in byte array of <input>. input uint256 to put into byte array.
function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); }
1,813,778
// File: contracts/interface/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * * * ,,,,,,,, * ,,,,,,,,,,, * ,,,,,,,,,,,, * ,,,,,,,,,,,,, * ,,,,,,,,,,,,,, * ,,,,,,,,,,,,,,, * ,,,,,,,,,,,,,,,, * ,,,,,,,,,,,,,,,, * ,,,,,,,,,,,,,,,,,, * ,,,,,,,,,,,,,,,,,, * ,,,,,,,,,,,,,,,,,, * ,,,,,,,,,,,,,,,,,,, * &/////////,,,,,,,,,,,,,,,,,,,, * &////////////,,,,,,,,,,,,,,,,,,,,, * %//&%**************,,,,,,,,,,,,,,,, * &************************,,,,,,,,,,,,* * (*****************************%,,,,,,,,,***& * &**********************************(,,,,,,******** * &************************((&//////////(//&&,&********** * &*******************((#////////////////(/////&(&********** * &***************&((,#//////////////////(//////#((((********** * ***********%((# (//////////////////(///////& %((&*********& * #%&(## &///////////////////(//////// (((********** * &///////////////////(/////////& ((**********% * /////////////////////(////////// &(&********** * &/twitter: [at]alexandraparfen // ((********** * ///////opeansea: [at]parfene /////// &(********& * &//////alexandraparfene[at]me.com///// &(******** * %%%&/////////////////////////////& &(((((& * %%%&///////////////////////& * &/////////%&% * * * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: contracts/interface/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: contracts/interface/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: contracts/interface/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/util/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } // File: contracts/util/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } } // File: contracts/standard/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/core/ERC721.sol /** * @dev Implementation of Non-Fungible Token. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { // The artist associated with the collection. string private _creator; address public immutable _owner; // Token name. string private _name; // Minting process state. bool public _finalized; // Token symbol. string private _symbol; string private _baseURI; uint256 public immutable _operand; uint256 public immutable _typeCount; // Mapping from type to name of token. mapping(uint256 => string) private _typeName; // Mapping from type to IPFS hash of canonical artifcat file. mapping(uint256 => string) private _typeIPFSHashes; // Mapping from type to token artifact location. mapping(uint256 => string) private _typeURI; // Mapping from token ID to owner address. mapping (uint256 => address) internal _owners; // Mapping owner address to token count, by aggregating all _typeCount NFTs in the contact. mapping (address => uint256) internal _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 token collection. */ constructor() { _name = "The Boring Bucket Hat"; _symbol = "BORING"; _creator = "Alexandra Parfene"; _owner = msg.sender; _typeCount = 5; _operand = 10000; _baseURI = "https://gist.githubusercontent.com/parfene/"; _typeName[1] = "Unit P4"; _typeIPFSHashes[1] = "QmSFdYSXWSczFqTuwjjvbjzb9kDME1xXWHHopZoXDJDb4B"; _typeURI[1] = "b98d6ff7b0cc6c0e911d3954e29dd090/raw/258e588039400689dc4901e28c04563b392ecd6e/unit_p4.json"; _typeName[2] = "Unit P3"; _typeIPFSHashes[2] = "QmQaGqyUxW8WzbGm77ehm9pp8iSz5af18BPoJb6hji3WX4"; _typeURI[2] = "f0247e710fa364f2e7c43d5844068bbf/raw/9ca1d517ccbe85820eac5a6203fc7bc295a25bff/unit_p3.json"; _typeName[3] = "Unit R3"; _typeIPFSHashes[3] = "QmfTAZyyv7HYecKmBEvPbPsP6uKkgZsRbdH8bz7xq6N5W1"; _typeURI[3] = "faa5e1a3915979fd8cb43c41fdc43a30/raw/fbdc8275312761c1c78d1433560ec2dab0b2a60b/unit_r3.json"; _typeName[4] = "Unit W3"; _typeIPFSHashes[4] = "QmdAYsrnuWL1NdvpaMvZnWU7TVpWQoqsfhZobWANMBFJZ8"; _typeURI[4] = "2d59ea3e82d6c1475acbf98ad0395a18/raw/d96129be81c79b88277d121ced88a88b3c491247/unit_w3.json"; _typeName[5] = "Unit B3"; _typeIPFSHashes[5] = "Qme6U9zacbpCfgyGwwyFiyUFYWD9ZHMMMdEnBMwrETrwxR"; _typeURI[5] = "081c2f2e29a459f46d04731e9e02bee7/raw/caefd2620d5d7feb7492417ff2e92bc47ccd2a1b/unit_b3.json"; } modifier onlyOwner() { require(msg.sender == _owner); _; } /** * @dev Prevent the minting of additional NFTs. */ function setFinalized() public onlyOwner { require(_finalized == false, "ERC721: only finalizable once"); _finalized = true; } /** * @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 The artist of this collection. */ function creator() public view virtual returns (string memory) { return _creator; } /** * @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 Returns an IPFS hash for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query. * @return IPFS hash for this (_typeCount) NFT. */ function tokenIPFSHash(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: IPFS hash query for nonexistent token"); uint256 countType = _getTypeId(tokenId); return _typeIPFSHashes[countType]; } /** * @dev Returns the link to artificat location for a given token by 'tokenId'. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query. * @return The location where the artifact assets are stored. */ function tokenURI(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); uint256 countType = _getTypeId(tokenId); return string(abi.encodePacked(_baseURI, _typeURI[countType])); } /** * @dev Determine which NFT in the contract (_typeCount) is associated * with this 'tokenId'. */ function _getTypeId(uint256 tokenId) private view returns (uint256) { return uint256(tokenId / _operand); } /** * @dev Returns the Name for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenName(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: Name query for nonexistent token"); uint256 countType = _getTypeId(tokenId); return _typeName[countType]; } /** * @dev Base URI for computing {tokenURI}. */ function setBaseURI(string memory baseURI_) external onlyOwner { _baseURI = baseURI_; } /** * @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 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); // 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"); // 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 (isContract(to)) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 Start with 10000, or 10001 * */ function mint(address[] memory owners, uint256 typeCount) public onlyOwner { require(!_finalized, "ERC721: minting concluded"); for(uint8 index = 0; index < owners.length; index++) { uint256 token_0001 = typeCount + index; address owner_0001 = owners[index]; _owners[token_0001] = owner_0001; _balances[owner_0001] = 1; emit Transfer(address(0), owner_0001, token_0001); } } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } }
Start with 10000, or 10001/
function mint(address[] memory owners, uint256 typeCount) public onlyOwner { require(!_finalized, "ERC721: minting concluded"); for(uint8 index = 0; index < owners.length; index++) { uint256 token_0001 = typeCount + index; address owner_0001 = owners[index]; _owners[token_0001] = owner_0001; _balances[owner_0001] = 1; emit Transfer(address(0), owner_0001, token_0001); } }
4,812,122
pragma solidity >=0.4.24; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { FlightSuretyData dataContract; // Filght Surety Data contract address payable private dataContractAddress; using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) using SafeMath for uint8; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint8 private CONSENSUS_START = 4; // the consensus algorithm starts aftre 4 airlin registration uint256 private CONSENSUS_ACHIEVEMENT = 50; // 50% vote are needed to validate a new airline registration uint256 private REGISTRATION_FEE_AIRLINES = 10 ether; uint256 private INSURANCE_PRICE = 1 ether; uint256 private INSURANCE_PAYBACK_MULTIPLIER = 150; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => address[]) voteMultiCaller; //mapping airlineAddress to add => address[] voters /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AirLineRegistrated(address _airlineAddress); event ContractFunded(uint256 _fundAmount, address _airlineAddress); event NewFlightAdded(address _airlineAddress, bytes32 _flightNumber, uint256 _timestamp, uint8 _status); event InsurancePurchased(bytes32 _flightNumber, address _passengerAddress, uint256 _amount); event PassengerPaid(address _passenger, uint256 _amount); event AirlineVoted(address _airlineAddress, uint256 voteNumber); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireMinimumAmount(){ require(msg.value >= REGISTRATION_FEE_AIRLINES, 'Minimum registration fee is required'); _; } modifier requireIsRegistered { bool isRegistered; (isRegistered,,,) = dataContract.fetchAirlineDetails(msg.sender); require(isRegistered == true, 'Caller is not registred'); _; } modifier requireIsAuthorized { bool isAuthorized; (,isAuthorized,,) = dataContract.fetchAirlineDetails(msg.sender); require(isAuthorized == true, 'Caller is not autorised, you have to fund first'); _; } /** * @dev Modifier that requires the flight does not exist to be added */ modifier requireFlightNotExists(address _airlineAddress, bytes32 _flightNumber, uint256 _timestamp) { address airline; (airline,,,,) = dataContract.fetchFlightDetails(_flightNumber); require(airline != _airlineAddress, 'Flight already registered'); _; } /** * @dev Modifier that requires the flight exists */ modifier requireFlightExists(bytes32 _flightNumber) { address airline; (airline,,,,) = dataContract.fetchFlightDetails(_flightNumber); require(airline != address(0), 'Flight does not exist'); _; } /** * @dev Modifier that requires the insurance does not exist to be purshaced. */ modifier requireNotInsured(address _passengerAddress, bytes32 _flightNumber) { bytes32 flightKey; address passenger = address(0); (,,,,flightKey) = dataContract.fetchFlightDetails(_flightNumber); (passenger,,) = dataContract.fetchInsuranceDetails(flightKey, _passengerAddress); require(!(passenger == _passengerAddress), 'Insurrance already exists for this flight'); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address payable _dataContractAddress) public { contractOwner = msg.sender; dataContract = FlightSuretyData(_dataContractAddress); dataContractAddress = _dataContractAddress; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus (bool _mode) external requireContractOwner { operational = _mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue */ function registerAirline(address _airlineAddress, bytes32 _airLineName) external requireIsOperational requireIsRegistered { // Get the number of registred airline from the contract data uint256 airlinesNumber = dataContract.getAirlinesNumber(); // Register a new airline if the number of airlines already registred is under 4 if (CONSENSUS_START > airlinesNumber) { dataContract.registerAirline(_airlineAddress, _airLineName); emit AirLineRegistrated(_airlineAddress); } // Multi-party consensus : 50% of the airlines regitered have to accept a new registration else { // duplicate vote verification bool duplicateVote = false; for (uint i = 0; i < voteMultiCaller[_airlineAddress].length; i++) { if (voteMultiCaller[_airlineAddress][i] == msg.sender){ duplicateVote = true; break; } } if(!duplicateVote){ voteMultiCaller[_airlineAddress].push(msg.sender); //emit AirlineVoted(msg.sender, voteMultiCaller[_airlineAddress].length); } // Verify consensus achievement : 50% vote needed to register a new airline if ( (voteMultiCaller[_airlineAddress].length.mul(100)).div(airlinesNumber) >= CONSENSUS_ACHIEVEMENT) { dataContract.registerAirline(_airlineAddress, _airLineName); emit AirLineRegistrated(_airlineAddress); } } } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fundAirline() public payable requireIsOperational requireIsRegistered requireMinimumAmount { //address payable dataContractAddress = address(uint160(dataContract)); dataContractAddress.transfer(msg.value); dataContract.fund(msg.value, msg.sender); emit ContractFunded(msg.value, msg.sender); } /** * @dev Register a new flight. */ function addNewFlight(bytes32 _flightNumber, uint256 _timestamp) external requireIsOperational requireIsRegistered requireIsAuthorized requireFlightNotExists(msg.sender, _flightNumber, _timestamp) { dataContract.addNewFlight(msg.sender, _flightNumber, _timestamp, STATUS_CODE_UNKNOWN); emit NewFlightAdded(msg.sender, _flightNumber, _timestamp, STATUS_CODE_UNKNOWN); } /** * @dev passenger buy insurance function */ function buyInsurance(bytes32 _flightNumber) external payable requireIsOperational requireFlightExists(_flightNumber) requireNotInsured(msg.sender, _flightNumber) { //send the money and buy insurance and top up the airline balance require(msg.value <= INSURANCE_PRICE, 'Exceeded insurance price allowed'); bytes32 flightKey; (,,,,flightKey) = dataContract.fetchFlightDetails(_flightNumber); //address payable dataContractAddress = address(uint160(address(dataContract))); dataContractAddress.transfer(msg.value); dataContract.buy(flightKey, msg.sender, msg.value); emit InsurancePurchased(_flightNumber, msg.sender, msg.value); } function withdraw(uint256 amount) external requireIsOperational { dataContract.pay(msg.sender, amount); } /** * @dev returns the number of the airlines registred to the contract * */ function getAirlinesNumber() external view requireIsOperational returns(uint256) { return dataContract.getAirlinesNumber(); } /** * @dev returns all the airlines registred to the contract * */ function getAllFlights() external view requireIsOperational returns(bytes32[] memory) { return dataContract.getAllFlights(); } /** * @dev returns all the airlines registred to the contract * */ function getPassengerBalance() external view requireIsOperational returns(uint256){ return dataContract.getPassengerBalance(msg.sender); } /** * @dev fetch Airline details * @param _airlineAddress the airline address to fetch * */ function fetchAirlineDetails(address _airlineAddress) external view requireIsOperational returns ( bool isRegistered, bool isAutorised, bytes32 name, uint256 balance ) { (isRegistered, isAutorised, name, balance) = dataContract.fetchAirlineDetails(_airlineAddress); return (isRegistered, isAutorised, name, balance); } /** * @dev fetch Flight details * @param _flightNumber the flught number to fetch * */ function fetchFlightDetails(bytes32 _flightNumber) external view requireIsOperational returns ( address airline, bytes32 flightNumber, uint256 timestamp, uint8 statusCode ) { (airline, flightNumber, timestamp, statusCode,) = dataContract.fetchFlightDetails(_flightNumber); return (airline, flightNumber, timestamp, statusCode); } function generateKey(address _airlineAddress, bytes32 _flight, uint256 _timestamp) internal pure returns(bytes32) { return keccak256(abi.encodePacked(_airlineAddress, _flight, _timestamp)); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus(bytes32 oracleRequestKey, address _airline, bytes32 _flightNumber, uint256 _timestamp, uint8 _statusCode) private requireIsOperational { if(_statusCode == STATUS_CODE_LATE_AIRLINE){ bytes32 flightKey = generateKey(_airline, _flightNumber, _timestamp); dataContract.creditInsurees(flightKey, INSURANCE_PAYBACK_MULTIPLIER); dataContract.setFlightStatus(flightKey, STATUS_CODE_LATE_AIRLINE); oracleResponses[oracleRequestKey].isOpen = false; } } /** * @dev Called after oracle has updated flight status * */ // Generate a request for oracles to fetch flight information function fetchFlightStatus(address _airline, bytes32 _flightNumber, uint256 _timestamp) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, _airline, _flightNumber, _timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, _airline, _flightNumber, _timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, bytes32 flight, uint256 timestamp, uint8 status); event OracleReport(address airline, bytes32 flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, bytes32 flight, uint256 timestamp); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes ( ) view external returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, bytes32 flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(key, airline, flight, timestamp, statusCode); } } function getFlightKey ( address airline, bytes32 flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) internal returns(uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion } contract FlightSuretyData { function getAirlinesNumber() external view returns(uint256); function registerAirline(address _airLineAddress, bytes32 _airLineName) external; function fund(uint256 _fundAmount, address _airlineAddress) public payable; function addNewFlight(address _airlineAddress, bytes32 _flightNumber, uint256 _timestamp, uint8 _status) external; function buy(bytes32 _flightKey, address _passengerAddress, uint256 _amount) external payable; function fetchFlightDetails(bytes32 _flightNumber) external view returns ( address airline, bytes32 flightNumber, uint256 timestamp, uint8 statusCode, bytes32 flightKey ); //function generateKey(address _airlineAddress, bytes32 _flight, uint256 _timestamp) internal pure returns(bytes32); function creditInsurees(bytes32 _flightKey, uint256 _multiplier) external; function setFlightStatus(bytes32 _flightKey, uint8 _statusCode) external; function fetchAirlineDetails(address _airlineAddress) external view returns ( bool isRegistered, bool isAutorised, bytes32 name, uint256 balance ); function fetchInsuranceDetails(bytes32 _flightKey, address _passengerAddress) external view returns ( address passenger, uint256 value, bool paid ); function pay(address _passenger, uint256 _amount) external payable; function getAllFlights() external view returns(bytes32[] memory); function getPassengerBalance(address _passengerAddress) external view returns(uint256); }
Initial funding for the insurance. Unless there are too many delayed flights resulting in insurance payouts, the contract should be self-sustaining/address payable dataContractAddress = address(uint160(dataContract));
function fundAirline() public payable requireIsOperational requireIsRegistered requireMinimumAmount { dataContractAddress.transfer(msg.value); dataContract.fund(msg.value, msg.sender); emit ContractFunded(msg.value, msg.sender); }
1,823,503
./full_match/5/0xBD5cDdc0937443B182892aB7EF678Eb7419cd09a/sources/src/contracts/core/InvestmentManager.sol
If the `depositor` has no existing shares, then they can `undelegate` themselves. This allows people a "hard reset" in their relationship with EigenLayer after withdrawing all of their stake./
function _undelegate(address depositor) internal { require(investorStrats[depositor].length == 0, "InvestmentManager._undelegate: depositor has active deposits"); delegation.undelegate(depositor); }
1,923,714
./full_match/5/0xC0f19dFa8e2dF07dC9F8BF918d13cEBe1e433fd1/sources/contracts/Gigble.sol
Create a function to accept a gig and release 10% of escrowed money to platform as fee and rest amount to the publisher Send 10% of the escrowed money to the platform as a fee Send the rest of the money to the publisher
function acceptGig(uint _gigId) public { require( gigs[_gigId].seller == msg.sender, "Only seller can accept gig" ); require(gigs[_gigId].confirmed, "Gig not yet confirmed"); require(!gigs[_gigId].accepted, "Gig already accepted"); require(!gigs[_gigId].refunded, "Gig already refunded"); gigs[_gigId].accepted = true; uint platformFee = gigs[_gigId].price / 10; payable(platformAddress).transfer(platformFee); payable(gigs[_gigId].seller).transfer(gigs[_gigId].price - platformFee); emit GigAccepted(_gigId); }
1,852,665
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import "./BasicAuth.sol"; import "./VoteComputer.sol"; contract ProposalManager is BasicAuth { struct ProposalInfo { // unique address address resourceId; // creator external address address proposer; // proposal type: 1X-committee;2X-deploy contract auth;3X-admin auth uint8 proposalType; // block number interval uint256 blockNumberInterval; //0-not exist 1-created 2-passed 3-denied 4-revoked 5-outdated uint8 status; // approve voters list address[] agreeVoters; // against voters List address[] againstVoters; } // Committee handler VoteComputer public _voteComputer; // auto generated proposal id uint256 public _proposalCount; // (id, proposal) mapping(uint256 => ProposalInfo) public _proposals; // (type, (resource id, proposal id)) mapping(uint8 => mapping(address => uint256)) public _proposalIndex; modifier proposalExist(uint256 proposalId) { require(_proposals[proposalId].status != 0, "Proposal not exist"); _; } modifier proposalVotable(uint256 proposalId) { require(_proposals[proposalId].status == 1, "Proposal is not votable"); _; } constructor(address committeeMgrAddress, address committeeAddress) public { _voteComputer = new VoteComputer(committeeMgrAddress, committeeAddress); } function setVoteComputer(address addr) public { _voteComputer = VoteComputer(addr); } /* * predicate proposal outdated * @param proposal id */ function refreshProposalStatus(uint256 proposalId) public proposalExist(proposalId) returns (uint8) { ProposalInfo storage proposal = _proposals[proposalId]; if (proposal.status == 1) { if (block.number > proposal.blockNumberInterval) { proposal.status = 5; return 5; } } return proposal.status; } /* * create proposal * @param create address * @param proposal type : 1X-committee;2X-deploy contract auth;3X-admin auth * @param resource id * @param after the block number interval, the proposal would be outdated. */ function create( address proposer, uint8 proposalType, address resourceId, uint256 blockNumberInterval ) public onlyOwner returns (uint256) { uint256 alreadExistProposalId = _proposalIndex[proposalType][ resourceId ]; if (_proposals[alreadExistProposalId].status == 1) { refreshProposalStatus(alreadExistProposalId); } require( _proposals[alreadExistProposalId].status != 1, "Current proposal not end" ); _proposalCount++; uint256 proposalId = _proposalCount; address[] memory agreeVoters; address[] memory againstVoters; ProposalInfo memory proposal = ProposalInfo( resourceId, proposer, proposalType, block.number + blockNumberInterval, 1, agreeVoters, againstVoters ); _proposals[proposalId] = proposal; _proposalIndex[proposalType][resourceId] = proposalId; return proposalId; } /* * unified vote * @param proposal id * @param true or false * @param voter address */ function vote( uint256 proposalId, bool agree, address voterAddress ) public onlyOwner proposalExist(proposalId) proposalVotable(proposalId) returns (uint8) { ProposalInfo storage proposal = _proposals[proposalId]; require(!hasVoted(proposal, voterAddress), "Already voted"); if (agree) { proposal.agreeVoters.push(voterAddress); } else { proposal.againstVoters.push(voterAddress); } uint8 status = _voteComputer.determineVoteResult( proposal.agreeVoters, proposal.againstVoters ); proposal.status = status; return status; } /* * revoke proposal * @param proposal id * @param voter address */ function revoke(uint256 proposalId, address voterAddress) public onlyOwner { ProposalInfo storage proposal = _proposals[proposalId]; require( refreshProposalStatus(proposalId) == 1, "Only newly created proposal can be revoked" ); require(proposal.proposer == voterAddress, "Only proposer can revoke"); proposal.status = 4; } /* * get proposal info * @param proposal id */ function getProposalInfo(uint256 proposalId) public view returns ( address resourceId, address proposer, uint8 proposalType, uint256 blockNumberInterval, uint8 status, address[] memory agreeVoters, address[] memory againstVoters ) { ProposalInfo storage proposal = _proposals[proposalId]; resourceId = proposal.resourceId; proposer = proposal.proposer; proposalType = proposal.proposalType; blockNumberInterval = proposal.blockNumberInterval; status = proposal.status; agreeVoters = proposal.agreeVoters; againstVoters = proposal.againstVoters; } /* * get proposal status by proposal id * @param proposal id */ function getProposalStatus(uint256 proposalId) public view returns (uint8) { return _proposals[proposalId].status; } /* * get info by proposal type and resource id * @param create address * @param proposal type : 1X-committee;2X-deploy contract auth;3X-admin auth * @param resource id * @param after the block number interval, the proposal would be outdated. */ function getIdByTypeAndResourceId(uint8 proposalType, address resourceId) public view returns (uint256) { return _proposalIndex[proposalType][resourceId]; } /** * judge account if voted for the proposal */ function hasVoted(ProposalInfo memory proposal, address account) internal pure returns (bool) { if ( contains(proposal.agreeVoters, account) || contains(proposal.againstVoters, account) ) { return true; } return false; } function contains(address[] memory array, address value) internal pure returns (bool) { for (uint256 i = 0; i < array.length; i++) { if (value == array[i]) { return true; } } return false; } }
revoke proposal proposal id voter address/
function revoke(uint256 proposalId, address voterAddress) public onlyOwner { ProposalInfo storage proposal = _proposals[proposalId]; require( refreshProposalStatus(proposalId) == 1, "Only newly created proposal can be revoked" ); require(proposal.proposer == voterAddress, "Only proposer can revoke"); proposal.status = 4; }
7,295,081
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // for WETH import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // for WETH import "@openzeppelin/contracts/access/Ownable.sol"; import './UsingLiquidityProtectionService.sol'; //token owner will be a time lock contract after farming started contract DTOToken is Context, Ownable, ERC20, UsingLiquidityProtectionService(0xd48368d1b7f97cb67cEb93Cc30B5828dd3523F56) { uint256 public constant MAX_SUPPLY = 100000000e18; constructor() public ERC20("DotOracle", "DTO") { _mint(owner(), MAX_SUPPLY); } function token_transfer(address _from, address _to, uint _amount) internal override { _transfer(_from, _to, _amount); // Expose low-level token transfer function. } function token_balanceOf(address _holder) internal view override returns(uint) { return balanceOf(_holder); // Expose balance check function. } function protectionAdminCheck() internal view override onlyOwner {} // Must revert to deny access. function uniswapVariety() internal pure override returns(bytes32) { return SUSHISWAP; // UNISWAP / PANCAKESWAP / QUICKSWAP / SUSHISWAP. } function uniswapVersion() internal pure override returns(UniswapVersion) { return UniswapVersion.V2; // V2 or V3. } function uniswapFactory() internal pure override returns(address) { return 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // Replace with the correct address. } function _beforeTokenTransfer(address _from, address _to, uint _amount) internal override { super._beforeTokenTransfer(_from, _to, _amount); LiquidityProtection_beforeTokenTransfer(_from, _to, _amount); } // All the following overrides are optional, if you want to modify default behavior. // How the protection gets disabled. function protectionChecker() internal view override returns(bool) { return ProtectionSwitch_timestamp(1637452799); // Switch off protection on Saturday, November 20, 2021 11:59:59 PM GMT. // return ProtectionSwitch_block(13000000); // Switch off protection on block 13000000. // return ProtectionSwitch_manual(); // Switch off protection by calling disableProtection(); from owner. Default. } // This token will be pooled in pair with: function counterToken() internal pure override returns(address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 "../../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; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import './external/UniswapV2Library.sol'; import './external/UniswapV3Library.sol'; import './IPLPS.sol'; abstract contract UsingLiquidityProtectionService { bool private unProtected = false; IPLPS private plps; uint64 internal constant HUNDRED_PERCENT = 1e18; bytes32 internal constant UNISWAP = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f; bytes32 internal constant PANCAKESWAP = 0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5; bytes32 internal constant QUICKSWAP = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f; bytes32 internal constant SUSHISWAP = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; enum UniswapVersion { V2, V3 } enum UniswapV3Fees { _005, // 0.05% _03, // 0.3% _1 // 1% } modifier onlyProtectionAdmin() { protectionAdminCheck(); _; } constructor (address _plps) { plps = IPLPS(_plps); } function LiquidityProtection_setLiquidityProtectionService(IPLPS _plps) external onlyProtectionAdmin() { plps = _plps; } function token_transfer(address from, address to, uint amount) internal virtual; function token_balanceOf(address holder) internal view virtual returns(uint); function protectionAdminCheck() internal view virtual; function uniswapVariety() internal pure virtual returns(bytes32); function uniswapVersion() internal pure virtual returns(UniswapVersion); function uniswapFactory() internal pure virtual returns(address); function counterToken() internal pure virtual returns(address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH } function uniswapV3Fee() internal pure virtual returns(UniswapV3Fees) { return UniswapV3Fees._03; } function protectionChecker() internal view virtual returns(bool) { return ProtectionSwitch_manual(); } function lps() private view returns(IPLPS) { return plps; } function LiquidityProtection_beforeTokenTransfer(address _from, address _to, uint _amount) internal virtual { if (protectionChecker()) { if (unProtected) { return; } lps().LiquidityProtection_beforeTokenTransfer(getLiquidityPool(), _from, _to, _amount); } } function revokeBlocked(address[] calldata _holders, address _revokeTo) external onlyProtectionAdmin() { require(isProtected(), 'UsingLiquidityProtectionService: protection removed'); bool unProtectedOld = unProtected; unProtected = true; address pool = getLiquidityPool(); for (uint i = 0; i < _holders.length; i++) { address holder = _holders[i]; if (lps().isBlocked(pool, holder)) { token_transfer(holder, _revokeTo, token_balanceOf(holder)); } } unProtected = unProtectedOld; } function LiquidityProtection_unblock(address[] calldata _holders) external onlyProtectionAdmin() { require(protectionChecker(), 'UsingLiquidityProtectionService: protection removed'); address pool = getLiquidityPool(); lps().unblock(pool, _holders); } function disableProtection() external onlyProtectionAdmin() { unProtected = true; } function isProtected() public view returns(bool) { return not(unProtected); } function ProtectionSwitch_manual() internal view returns(bool) { return isProtected(); } function ProtectionSwitch_timestamp(uint _timestamp) internal view returns(bool) { return not(passed(_timestamp)); } function ProtectionSwitch_block(uint _block) internal view returns(bool) { return not(blockPassed(_block)); } function blockPassed(uint _block) internal view returns(bool) { return _block < block.number; } function passed(uint _timestamp) internal view returns(bool) { return _timestamp < block.timestamp; } function not(bool _condition) internal pure returns(bool) { return !_condition; } function feeToUint24(UniswapV3Fees _fee) internal pure returns(uint24) { if (_fee == UniswapV3Fees._03) return 3000; if (_fee == UniswapV3Fees._005) return 500; return 10000; } function getLiquidityPool() public view returns(address) { if (uniswapVersion() == UniswapVersion.V2) { return UniswapV2Library.pairFor(uniswapVariety(), uniswapFactory(), address(this), counterToken()); } require(uniswapVariety() == UNISWAP, 'LiquidityProtection: uniswapVariety() can only be UNISWAP for V3.'); return UniswapV3Library.computeAddress(uniswapFactory(), UniswapV3Library.getPoolKey(address(this), counterToken(), feeToUint24(uniswapV3Fee()))); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.7.0; // Exempt from the original UniswapV2Library. library UniswapV2Library { // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(bytes32 initCodeHash, address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), initCodeHash // init code hash ))))); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.0; /// @notice based on https://github.com/Uniswap/uniswap-v3-periphery/blob/v1.0.0/contracts/libraries/PoolAddress.sol /// @notice changed compiler version and lib name. /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library UniswapV3Library { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint160( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface IPLPS { function LiquidityProtection_beforeTokenTransfer( address _pool, address _from, address _to, uint _amount) external; function isBlocked(address _pool, address _who) external view returns(bool); function unblock(address _pool, address[] calldata _whos) external; }
Must revert to deny access.
function protectionAdminCheck() internal view override onlyOwner {}
461,531
/** *Submitted for verification at Etherscan.io on 2021-06-24 */ pragma solidity >=0.7.2; pragma experimental ABIEncoderV2; 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); } 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; } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ // /** * @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. */ 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 { } } library SafeERC20 { 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 { if (_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value))) { return; } require(_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)) && _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)), "ERC20 approve failed"); } function _callOptionalReturn(IERC20 token, bytes memory data) private returns (bool) { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); if (!success) { return false; } if (returndata.length >= 32) { // Return data is optional return abi.decode(returndata, (bool)); } // In a wierd case when return data is 1-31 bytes long - return false. return returndata.length == 0; } } library ProtocolAdapterTypes { enum OptionType {Invalid, Put, Call} // We have 2 types of purchase methods so far - by contract and by 0x. // Contract is simple because it involves just specifying the option terms you want to buy. // ZeroEx involves an off-chain API call which prepares a ZeroExOrder object to be passed into the tx. enum PurchaseMethod {Invalid, Contract, ZeroEx} /** * @notice Terms of an options contract * @param underlying is the underlying asset of the options. E.g. For ETH $800 CALL, ETH is the underlying. * @param strikeAsset is the asset used to denote the asset paid out when exercising the option. * E.g. For ETH $800 CALL, USDC is the strikeAsset. * @param collateralAsset is the asset used to collateralize a short position for the option. * @param expiry is the expiry of the option contract. Users can only exercise after expiry in Europeans. * @param strikePrice is the strike price of an optio contract. * E.g. For ETH $800 CALL, 800*10**18 is the USDC. * @param optionType is the type of option, can only be OptionType.Call or OptionType.Put * @param paymentToken is the token used to purchase the option. * E.g. Buy UNI/USDC CALL with WETH as the paymentToken. */ struct OptionTerms { address underlying; address strikeAsset; address collateralAsset; uint256 expiry; uint256 strikePrice; ProtocolAdapterTypes.OptionType optionType; address paymentToken; } /** * @notice 0x order for purchasing otokens * @param exchangeAddress [deprecated] is the address we call to conduct a 0x trade. * Slither flagged this as a potential vulnerability so we hardcoded it. * @param buyTokenAddress is the otoken address * @param sellTokenAddress is the token used to purchase USDC. This is USDC most of the time. * @param allowanceTarget is the address the adapter needs to provide sellToken allowance to so the swap happens * @param protocolFee is the fee paid (in ETH) when conducting the trade * @param makerAssetAmount is the buyToken amount * @param takerAssetAmount is the sellToken amount * @param swapData is the encoded msg.data passed by the 0x api response */ struct ZeroExOrder { address exchangeAddress; address buyTokenAddress; address sellTokenAddress; address allowanceTarget; uint256 protocolFee; uint256 makerAssetAmount; uint256 takerAssetAmount; bytes swapData; } } interface IProtocolAdapter { /** * @notice Emitted when a new option contract is purchased */ event Purchased( address indexed caller, string indexed protocolName, address indexed underlying, uint256 amount, uint256 optionID ); /** * @notice Emitted when an option contract is exercised */ event Exercised( address indexed caller, address indexed options, uint256 indexed optionID, uint256 amount, uint256 exerciseProfit ); /** * @notice Name of the adapter. E.g. "HEGIC", "OPYN_V1". Used as index key for adapter addresses */ function protocolName() external pure returns (string memory); /** * @notice Boolean flag to indicate whether to use option IDs or not. * Fungible protocols normally use tokens to represent option contracts. */ function nonFungible() external pure returns (bool); /** * @notice Returns the purchase method used to purchase options */ function purchaseMethod() external pure returns (ProtocolAdapterTypes.PurchaseMethod); /** * @notice Check if an options contract exist based on the passed parameters. * @param optionTerms is the terms of the option contract */ function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms) external view returns (bool); /** * @notice Get the options contract's address based on the passed parameters * @param optionTerms is the terms of the option contract */ function getOptionsAddress( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address); /** * @notice Gets the premium to buy `purchaseAmount` of the option contract in ETH terms. * @param optionTerms is the terms of the option contract * @param purchaseAmount is the number of options purchased */ function premium( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256 cost); /** * @notice Amount of profit made from exercising an option contract (current price - strike price). * 0 if exercising out-the-money. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. */ function exerciseProfit( address options, uint256 optionID, uint256 amount ) external view returns (uint256 profit); function canExercise( address options, uint256 optionID, uint256 amount ) external view returns (bool); /** * @notice Purchases the options contract. * @param optionTerms is the terms of the option contract * @param amount is the purchase amount in Wad units (10**18) */ function purchase( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount, uint256 maxCost ) external payable returns (uint256 optionID); /** * @notice Exercises the options contract. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. * @param recipient is the account that receives the exercised profits. * This is needed since the adapter holds all the positions */ function exercise( address options, uint256 optionID, uint256 amount, address recipient ) external payable; /** * @notice Opens a short position for a given `optionTerms`. * @param optionTerms is the terms of the option contract * @param amount is the short position amount */ function createShort( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256); /** * @notice Closes an existing short position. In the future, * we may want to open this up to specifying a particular short position to close. */ function closeShort() external returns (uint256); } library ProtocolAdapter { function delegateOptionsExist( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (bool) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "optionsExist((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (bool)); } function delegateGetOptionsAddress( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "getOptionsAddress((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (address)); } function delegatePremium( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "premium((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, purchaseAmount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateExerciseProfit( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "exerciseProfit(address,uint256,uint256)", options, optionID, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchase( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount, uint256 maxCost ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "purchase((address,address,address,uint256,uint256,uint8,address),uint256,uint256)", optionTerms, purchaseAmount, maxCost ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchaseWithZeroEx( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, ProtocolAdapterTypes.ZeroExOrder calldata zeroExOrder ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( // solhint-disable-next-line "purchaseWithZeroEx((address,address,address,uint256,uint256,uint8,address),(address,address,address,address,uint256,uint256,uint256,bytes))", optionTerms, zeroExOrder ) ); revertWhenFail(success, result); } function delegateExercise( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount, address recipient ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "exercise(address,uint256,uint256,address)", options, optionID, amount, recipient ) ); revertWhenFail(success, result); } function delegateClaimRewards( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "claimRewards(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateRewardsClaimable( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "rewardsClaimable(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCreateShort( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "createShort((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCloseShort(IProtocolAdapter adapter) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature("closeShort()") ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function revertWhenFail(bool success, bytes memory returnData) private pure { if (success) return; revert(getRevertMsg(returnData)); } function getRevertMsg(bytes memory _returnData) private pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "ProtocolAdapter: reverted"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } } interface IRibbonFactory { function isInstrument(address instrument) external returns (bool); function getAdapter(string calldata protocolName) external view returns (address); function getAdapters() external view returns (address[] memory adaptersArray); function burnGasTokens() external; } interface IWETH { function deposit() external payable; function withdraw(uint256) external; 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); function decimals() external view returns (uint256); } interface IYearnVault { function pricePerShare() external view returns (uint256); function deposit(uint256 _amount, address _recipient) external returns (uint256); function withdraw( uint256 _maxShares, address _recipient, uint256 _maxLoss ) external returns (uint256); function approve(address _recipient, uint256 _amount) external returns (bool); 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 transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function decimals() external view returns (uint256); } interface IYearnRegistry { function latestVault(address token) external returns (address); } library Types { struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 amount; // Amount for ERC-20 or ERC-1155 uint256 id; // ID for ERC-721 or ERC-1155 } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } } interface ISwap { event Swap( uint256 indexed nonce, uint256 timestamp, address indexed signerWallet, uint256 signerAmount, uint256 signerId, address signerToken, address indexed senderWallet, uint256 senderAmount, uint256 senderId, address senderToken, address affiliateWallet, uint256 affiliateAmount, uint256 affiliateId, address affiliateToken ); event Cancel(uint256 indexed nonce, address indexed signerWallet); event CancelUpTo(uint256 indexed nonce, address indexed signerWallet); event AuthorizeSender( address indexed authorizerAddress, address indexed authorizedSender ); event AuthorizeSigner( address indexed authorizerAddress, address indexed authorizedSigner ); event RevokeSender( address indexed authorizerAddress, address indexed revokedSender ); event RevokeSigner( address indexed authorizerAddress, address indexed revokedSigner ); /** * @notice Atomic Token Swap * @param order Types.Order */ function swap(Types.Order calldata order) external; /** * @notice Cancel one or more open orders by nonce * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external; /** * @notice Cancels all orders below a nonce value * @dev These orders can be made active by reducing the minimum nonce * @param minimumNonce uint256 */ function cancelUpTo(uint256 minimumNonce) external; /** * @notice Authorize a delegated sender * @param authorizedSender address */ function authorizeSender(address authorizedSender) external; /** * @notice Authorize a delegated signer * @param authorizedSigner address */ function authorizeSigner(address authorizedSigner) external; /** * @notice Revoke an authorization * @param authorizedSender address */ function revokeSender(address authorizedSender) external; /** * @notice Revoke an authorization * @param authorizedSigner address */ function revokeSigner(address authorizedSigner) external; function senderAuthorizations(address, address) external view returns (bool); function signerAuthorizations(address, address) external view returns (bool); function signerNonceStatus(address, uint256) external view returns (bytes1); function signerMinimumNonce(address) external view returns (uint256); function registry() external view returns (address); } interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // /** * @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); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } contract OptionsVaultStorageV1 is ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC20Upgradeable { // DEPRECATED: This variable was originally used to store the asset address we are using as collateral // But due to gas optimization and upgradeability security concerns, // we removed it in favor of using immutable variables // This variable is left here to hold the storage slot for upgrades address private _oldAsset; // Privileged role that is able to select the option terms (strike price, expiry) to short address public manager; // Option that the vault is shorting in the next cycle address public nextOption; // The timestamp when the `nextOption` can be used by the vault uint256 public nextOptionReadyAt; // Option that the vault is currently shorting address public currentOption; // Amount that is currently locked for selling options uint256 public lockedAmount; // Cap for total amount deposited into vault uint256 public cap; // Fee incurred when withdrawing out of the vault, in the units of 10**18 // where 1 ether = 100%, so 0.005 means 0.5% fee uint256 public instantWithdrawalFee; // Recipient for withdrawal fees address public feeRecipient; } contract OptionsVaultStorageV2 { // Amount locked for scheduled withdrawals; uint256 public queuedWithdrawShares; // Mapping to store the scheduled withdrawals (address => withdrawAmount) mapping(address => uint256) public scheduledWithdrawals; } contract OptionsVaultStorage is OptionsVaultStorageV1, OptionsVaultStorageV2 { } // contract RibbonThetaVaultYearn is DSMath, OptionsVaultStorage { using ProtocolAdapter for IProtocolAdapter; using SafeERC20 for IERC20; using SafeMath for uint256; string private constant _adapterName = "OPYN_GAMMA"; IProtocolAdapter public immutable adapter; address public immutable asset; address public immutable underlying; address public immutable WETH; address public immutable USDC; bool public immutable isPut; uint8 private immutable _decimals; // Yearn vault contract IYearnVault public immutable collateralToken; // AirSwap Swap contract // https://github.com/airswap/airswap-protocols/blob/master/source/swap/contracts/interfaces/ISwap.sol ISwap public immutable SWAP_CONTRACT; // 90% locked in options protocol, 10% of the pool reserved for withdrawals uint256 public constant lockedRatio = 0.9 ether; uint256 public constant delay = 1 hours; uint256 public immutable MINIMUM_SUPPLY; uint256 public constant YEARN_WITHDRAWAL_BUFFER = 5; // 0.05% uint256 public constant YEARN_WITHDRAWAL_SLIPPAGE = 5; // 0.05% event ManagerChanged(address oldManager, address newManager); event Deposit(address indexed account, uint256 amount, uint256 share); event Withdraw( address indexed account, uint256 amount, uint256 share, uint256 fee ); event OpenShort( address indexed options, uint256 depositAmount, address manager ); event CloseShort( address indexed options, uint256 withdrawAmount, address manager ); event WithdrawalFeeSet(uint256 oldFee, uint256 newFee); event CapSet(uint256 oldCap, uint256 newCap, address manager); /** * @notice Initializes the contract with immutable variables * @param _asset is the asset used for collateral and premiums * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _yearnRegistry is the registry contract for all yearn vaults * @param _swapContract is the Airswap Swap contract * @param _tokenDecimals is the decimals for the vault shares. Must match the decimals for _asset. * @param _minimumSupply is the minimum supply for the asset balance and the share supply. * @param _isPut is whether this is a put strategy. * It's important to bake the _factory variable into the contract with the constructor * If we do it in the `initialize` function, users get to set the factory variable and * subsequently the adapter, which allows them to make a delegatecall, then selfdestruct the contract. */ constructor( address _asset, address _factory, address _weth, address _usdc, address _yearnRegistry, address _swapContract, uint8 _tokenDecimals, uint256 _minimumSupply, bool _isPut ) { require(_asset != address(0), "!_asset"); require(_factory != address(0), "!_factory"); require(_weth != address(0), "!_weth"); require(_usdc != address(0), "!_usdc"); require(_yearnRegistry != address(0), "!_yearnRegistry"); require(_swapContract != address(0), "!_swapContract"); require(_tokenDecimals > 0, "!_tokenDecimals"); require(_minimumSupply > 0, "!_minimumSupply"); IRibbonFactory factoryInstance = IRibbonFactory(_factory); address adapterAddr = factoryInstance.getAdapter(_adapterName); require(adapterAddr != address(0), "Adapter not set"); asset = _isPut ? _usdc : _asset; underlying = _asset; address collateralAddr = IYearnRegistry(_yearnRegistry).latestVault(_isPut ? _usdc : _asset); collateralToken = IYearnVault(collateralAddr); require(collateralAddr != address(0), "!_collateralToken"); adapter = IProtocolAdapter(adapterAddr); WETH = _weth; USDC = _usdc; SWAP_CONTRACT = ISwap(_swapContract); _decimals = _tokenDecimals; MINIMUM_SUPPLY = _minimumSupply; isPut = _isPut; } /** * @notice Initializes the OptionVault contract with storage variables. * @param _owner is the owner of the contract who can set the manager * @param _feeRecipient is the recipient address for withdrawal fees. * @param _initCap is the initial vault's cap on deposits, the manager can increase this as necessary. * @param _tokenName is the name of the vault share token * @param _tokenSymbol is the symbol of the vault share token */ function initialize( address _owner, address _feeRecipient, uint256 _initCap, string calldata _tokenName, string calldata _tokenSymbol ) external initializer { require(_owner != address(0), "!_owner"); require(_feeRecipient != address(0), "!_feeRecipient"); require(_initCap > 0, "_initCap > 0"); require(bytes(_tokenName).length > 0, "_tokenName != 0x"); require(bytes(_tokenSymbol).length > 0, "_tokenSymbol != 0x"); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); cap = _initCap; // hardcode the initial withdrawal fee instantWithdrawalFee = 0.005 ether; feeRecipient = _feeRecipient; } /** * @notice Sets the new manager of the vault. * @param newManager is the new manager of the vault */ function setManager(address newManager) external onlyOwner { require(newManager != address(0), "!newManager"); address oldManager = manager; manager = newManager; emit ManagerChanged(oldManager, newManager); } /** * @notice Sets the new fee recipient * @param newFeeRecipient is the address of the new fee recipient */ function setFeeRecipient(address newFeeRecipient) external onlyOwner { require(newFeeRecipient != address(0), "!newFeeRecipient"); feeRecipient = newFeeRecipient; } /** * @notice Sets the new withdrawal fee * @param newWithdrawalFee is the fee paid in tokens when withdrawing */ function setWithdrawalFee(uint256 newWithdrawalFee) external onlyManager { require(newWithdrawalFee > 0, "withdrawalFee != 0"); // cap max withdrawal fees to 30% of the withdrawal amount require(newWithdrawalFee < 0.3 ether, "withdrawalFee >= 30%"); uint256 oldFee = instantWithdrawalFee; emit WithdrawalFeeSet(oldFee, newWithdrawalFee); instantWithdrawalFee = newWithdrawalFee; } /** * @notice Deposits ETH into the contract and mint vault shares. Reverts if the underlying is not WETH. */ function depositETH() external payable nonReentrant { require(asset == WETH, "asset is not WETH"); require(msg.value > 0, "No value passed"); IWETH(WETH).deposit{value: msg.value}(); _deposit(msg.value); } /** * @notice Deposits the `asset` into the contract and mint vault shares. * @param amount is the amount of `asset` to deposit */ function deposit(uint256 amount) external nonReentrant { IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); _deposit(amount); } /** * @notice Deposits the `collateralToken` into the contract and mint vault shares. * @param amount is the amount of `collateralToken` to deposit */ function depositYieldToken(uint256 amount) external nonReentrant { IERC20(address(collateralToken)).safeTransferFrom( msg.sender, address(this), amount ); uint256 collateralToAssetBalance = wmul(amount, collateralToken.pricePerShare().mul(_decimalShift())); _deposit(collateralToAssetBalance); } /** * @notice Mints the vault shares to the msg.sender * @param amount is the amount of `asset` deposited */ function _deposit(uint256 amount) private { uint256 totalWithDepositedAmount = totalBalance(); require(totalWithDepositedAmount < cap, "Cap exceeded"); require( totalWithDepositedAmount >= MINIMUM_SUPPLY, "Insufficient asset balance" ); // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalWithDepositedAmount.sub(amount); uint256 shareSupply = totalSupply(); // Following the pool share calculation from Alpha Homora: // solhint-disable-next-line // https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104 uint256 share = shareSupply == 0 ? amount : amount.mul(shareSupply).div(total); require( shareSupply.add(share) >= MINIMUM_SUPPLY, "Insufficient share supply" ); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); } /** * @notice Withdraws ETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdrawETH(uint256 share) external nonReentrant { require(asset == WETH, "!WETH"); uint256 withdrawAmount = _withdraw(share, true); IWETH(WETH).withdraw(withdrawAmount); (bool success, ) = msg.sender.call{value: withdrawAmount}(""); require(success, "ETH transfer failed"); } /** * @notice Withdraws WETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdraw(uint256 share) external nonReentrant { uint256 withdrawAmount = _withdraw(share, true); IERC20(asset).safeTransfer(msg.sender, withdrawAmount); } /** * @notice Withdraws yvWETH + WETH (if necessary) from vault using vault shares * @param share is the number of vault shares to be burned */ function withdrawYieldToken(uint256 share) external nonReentrant { uint256 pricePerYearnShare = collateralToken.pricePerShare(); uint256 withdrawAmount = wdiv( _withdraw(share, false), pricePerYearnShare.mul(_decimalShift()) ); uint256 yieldTokenBalance = _withdrawYieldToken(withdrawAmount); // If there is not enough yvWETH in the vault, it withdraws as much as possible and // transfers the rest in `asset` if (withdrawAmount > yieldTokenBalance) { _withdrawSupplementaryAssetToken( withdrawAmount, yieldTokenBalance, pricePerYearnShare ); } } /** * @notice Withdraws yvWETH from vault * @param withdrawAmount is the withdraw amount in terms of yearn tokens */ function _withdrawYieldToken(uint256 withdrawAmount) private returns (uint256 yieldTokenBalance) { yieldTokenBalance = IERC20(address(collateralToken)).balanceOf( address(this) ); uint256 yieldTokensToWithdraw = min(yieldTokenBalance, withdrawAmount); if (yieldTokensToWithdraw > 0) { IERC20(address(collateralToken)).safeTransfer( msg.sender, yieldTokensToWithdraw ); } } /** * @notice Withdraws `asset` from vault * @param withdrawAmount is the withdraw amount in terms of yearn tokens * @param yieldTokenBalance is the collateral token (yvWETH) balance of the vault * @param pricePerYearnShare is the yvWETH<->WETH price ratio */ function _withdrawSupplementaryAssetToken( uint256 withdrawAmount, uint256 yieldTokenBalance, uint256 pricePerYearnShare ) private { uint256 underlyingTokensToWithdraw = wmul( withdrawAmount.sub(yieldTokenBalance), pricePerYearnShare.mul(_decimalShift()) ); require( IERC20(asset).balanceOf(address(this)) >= underlyingTokensToWithdraw, "Not enough of `asset` balance to withdraw!" ); if (asset == WETH) { IWETH(WETH).withdraw(underlyingTokensToWithdraw); (bool success, ) = msg.sender.call{value: underlyingTokensToWithdraw}(""); require(success, "ETH transfer failed"); } else { IERC20(asset).safeTransfer(msg.sender, underlyingTokensToWithdraw); } } /** * @notice Burns vault shares, checks if eligible for withdrawal, * and unwraps yvWETH if necessary * @param share is the number of vault shares to be burned * @param unwrap is whether we want to unwrap to underlying asset */ function _withdraw(uint256 share, bool unwrap) private returns (uint256) { (uint256 amountAfterFee, uint256 feeAmount) = withdrawAmountWithShares(share); emit Withdraw(msg.sender, amountAfterFee, share, feeAmount); _burn(msg.sender, share); _unwrapYieldToken(unwrap ? amountAfterFee.add(feeAmount) : feeAmount); IERC20(asset).safeTransfer(feeRecipient, feeAmount); return amountAfterFee; } /** * @notice Unwraps the necessary amount of the yield-bearing yearn token * and transfers amount to vault * @param amount is the amount of `asset` to withdraw */ function _unwrapYieldToken(uint256 amount) private { uint256 assetBalance = IERC20(asset).balanceOf(address(this)); uint256 amountToUnwrap = wdiv( max(assetBalance, amount).sub(assetBalance), collateralToken.pricePerShare().mul(_decimalShift()) ); amountToUnwrap = amountToUnwrap.add( amountToUnwrap.mul(YEARN_WITHDRAWAL_BUFFER).div(10000) ); if (amountToUnwrap > 0) { collateralToken.withdraw( amountToUnwrap, address(this), YEARN_WITHDRAWAL_SLIPPAGE ); } } /** * @notice Sets the next option the vault will be shorting, and closes the existing short. * This allows all the users to withdraw if the next option is malicious. */ function commitAndClose( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external onlyManager nonReentrant { _setNextOption(optionTerms); _closeShort(); } function closeShort() external nonReentrant { _closeShort(); } /** * @notice Sets the next option address and the timestamp at which the * admin can call `rollToNextOption` to open a short for the option. * @param optionTerms is the terms of the option contract */ function _setNextOption( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) private { if (isPut) { require( optionTerms.optionType == ProtocolAdapterTypes.OptionType.Put, "!put" ); } else { require( optionTerms.optionType == ProtocolAdapterTypes.OptionType.Call, "!call" ); } address option = adapter.getOptionsAddress(optionTerms); require(option != address(0), "!option"); OtokenInterface otoken = OtokenInterface(option); require(otoken.isPut() == isPut, "Option type does not match"); require( otoken.underlyingAsset() == underlying, "Wrong underlyingAsset" ); require( otoken.collateralAsset() == address(collateralToken), "Wrong collateralAsset" ); // we just assume all options use USDC as the strike require(otoken.strikeAsset() == USDC, "strikeAsset != USDC"); uint256 readyAt = block.timestamp.add(delay); require( otoken.expiryTimestamp() >= readyAt, "Option expiry cannot be before delay" ); nextOption = option; nextOptionReadyAt = readyAt; } /** * @notice Closes the existing short position for the vault. */ function _closeShort() private { address oldOption = currentOption; currentOption = address(0); lockedAmount = 0; if (oldOption != address(0)) { OtokenInterface otoken = OtokenInterface(oldOption); require( block.timestamp > otoken.expiryTimestamp(), "Cannot close short before expiry" ); uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } } /** * @notice Rolls the vault's funds into a new short position. */ function rollToNextOption() external onlyManager nonReentrant { require( block.timestamp >= nextOptionReadyAt, "Cannot roll before delay" ); address newOption = nextOption; require(newOption != address(0), "No found option"); currentOption = newOption; nextOption = address(0); uint256 amountToWrap = IERC20(asset).balanceOf(address(this)); IERC20(asset).safeApprove(address(collateralToken), amountToWrap); // there is a slight imprecision with regards to calculating back from yearn token -> underlying // that stems from miscoordination between ytoken .deposit() amount wrapped and pricePerShare // at that point in time. // ex: if I have 1 eth, deposit 1 eth into yearn vault and calculate value of yearn token balance // denominated in eth (via balance(yearn token) * pricePerShare) we will get 1 eth - 1 wei. collateralToken.deposit(amountToWrap, address(this)); uint256 currentBalance = assetBalance(); uint256 shortAmount = wdiv( wmul(currentBalance, lockedRatio), collateralToken.pricePerShare().mul(_decimalShift()) ); lockedAmount = shortAmount; OtokenInterface otoken = OtokenInterface(newOption); ProtocolAdapterTypes.OptionTerms memory optionTerms = ProtocolAdapterTypes.OptionTerms( underlying, USDC, address(collateralToken), otoken.expiryTimestamp(), otoken.strikePrice().mul(10**10), // scale back to 10**18 isPut ? ProtocolAdapterTypes.OptionType.Put : ProtocolAdapterTypes.OptionType.Call, // isPut address(0) ); uint256 shortBalance = adapter.delegateCreateShort(optionTerms, shortAmount); IERC20 optionToken = IERC20(newOption); optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance); emit OpenShort(newOption, shortAmount, msg.sender); } /** * @notice Withdraw from the options protocol by closing short in an event of a emergency */ function emergencyWithdrawFromShort() external onlyManager nonReentrant { address oldOption = currentOption; require(oldOption != address(0), "!currentOption"); currentOption = address(0); nextOption = address(0); lockedAmount = 0; uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } /** * @notice Performs a swap of `currentOption` token to `asset` token with a counterparty * @param order is an Airswap order */ function sellOptions(Types.Order calldata order) external onlyManager { require( order.sender.wallet == address(this), "Sender can only be vault" ); require( order.sender.token == currentOption, "Can only sell currentOption" ); require(order.signer.token == asset, "Can only buy with asset token"); SWAP_CONTRACT.swap(order); } /** * @notice Sets a new cap for deposits * @param newCap is the new cap for deposits */ function setCap(uint256 newCap) external onlyManager { uint256 oldCap = cap; cap = newCap; emit CapSet(oldCap, newCap, msg.sender); } /** * @notice Returns the expiry of the current option the vault is shorting */ function currentOptionExpiry() external view returns (uint256) { address _currentOption = currentOption; if (_currentOption == address(0)) { return 0; } OtokenInterface oToken = OtokenInterface(currentOption); return oToken.expiryTimestamp(); } /** * @notice Returns the amount withdrawable (in `asset` tokens) using the `share` amount * @param share is the number of shares burned to withdraw asset from the vault * @return amountAfterFee is the amount of asset tokens withdrawable from the vault * @return feeAmount is the fee amount (in asset tokens) sent to the feeRecipient */ function withdrawAmountWithShares(uint256 share) public view returns (uint256 amountAfterFee, uint256 feeAmount) { uint256 currentAssetBalance = assetBalance(); ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) = _withdrawAmountWithShares(share, currentAssetBalance); require( withdrawAmount <= currentAssetBalance, "Cannot withdraw more than available" ); require(newShareSupply >= MINIMUM_SUPPLY, "Insufficient share supply"); require( newAssetBalance >= MINIMUM_SUPPLY, "Insufficient asset balance" ); feeAmount = wmul(withdrawAmount, instantWithdrawalFee); amountAfterFee = withdrawAmount.sub(feeAmount); } /** * @notice Helper function to return the `asset` amount returned using the `share` amount * @param share is the number of shares used to withdraw * @param currentAssetBalance is the value returned by totalBalance(). This is passed in to save gas. */ function _withdrawAmountWithShares( uint256 share, uint256 currentAssetBalance ) private view returns ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) { uint256 total = wmul( lockedAmount, collateralToken.pricePerShare().mul(_decimalShift()) ) .add(currentAssetBalance); uint256 shareSupply = totalSupply(); // solhint-disable-next-line // Following the pool share calculation from Alpha Homora: https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L111 withdrawAmount = share.mul(total).div(shareSupply); newAssetBalance = total.sub(withdrawAmount); newShareSupply = shareSupply.sub(share); } /** * @notice Returns the max withdrawable shares for all users in the vault */ function maxWithdrawableShares() public view returns (uint256) { uint256 withdrawableBalance = assetBalance(); uint256 total = wmul( lockedAmount, collateralToken.pricePerShare().mul(_decimalShift()) ) .add(withdrawableBalance); return withdrawableBalance.mul(totalSupply()).div(total).sub( MINIMUM_SUPPLY ); } /** * @notice Returns the max amount withdrawable by an account using the account's vault share balance * @param account is the address of the vault share holder * @return amount of `asset` withdrawable from vault, with fees accounted */ function maxWithdrawAmount(address account) external view returns (uint256) { uint256 maxShares = maxWithdrawableShares(); uint256 share = balanceOf(account); uint256 numShares = min(maxShares, share); (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(numShares, assetBalance()); return withdrawAmount; } /** * @notice Returns the number of shares for a given `assetAmount`. * Used by the frontend to calculate withdraw amounts. * @param assetAmount is the asset amount to be withdrawn * @return share amount */ function assetAmountToShares(uint256 assetAmount) external view returns (uint256) { uint256 total = wmul( lockedAmount, collateralToken.pricePerShare().mul(_decimalShift()) ) .add(assetBalance()); return assetAmount.mul(totalSupply()).div(total); } /** * @notice Returns an account's balance on the vault * @param account is the address of the user * @return vault balance of the user */ function accountVaultBalance(address account) external view returns (uint256) { (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(balanceOf(account), assetBalance()); return withdrawAmount; } /** * @notice Returns the vault's total balance, including the amounts locked into a short position * @return total balance of the vault, including the amounts locked in third party protocols */ function totalBalance() public view returns (uint256) { return wmul( lockedAmount, collateralToken.pricePerShare().mul(_decimalShift()) ) .add(assetBalance()); } /** * @notice Returns the asset balance on the vault. This balance is freely withdrawable by users. */ function assetBalance() public view returns (uint256) { return IERC20(asset).balanceOf(address(this)).add( wmul( IERC20(address(collateralToken)).balanceOf(address(this)), collateralToken.pricePerShare().mul(_decimalShift()) ) ); } /** * @notice Returns the collateral balance on the vault. */ function yearnTokenBalance() public view returns (uint256) { return IERC20(address(collateralToken)).balanceOf(address(this)).add( lockedAmount ); } /** * @notice Returns the token decimals */ function decimals() public view override returns (uint8) { return _decimals; } /** * @notice Returns the decimal shift between 18 decimals and asset tokens */ function _decimalShift() private view returns (uint256) { return 10**(uint256(18).sub(collateralToken.decimals())); } /** * @notice Only allows manager to execute a function */ modifier onlyManager { require(msg.sender == manager, "Only manager"); _; } }
Returns the max withdrawable shares for all users in the vault/
function maxWithdrawableShares() public view returns (uint256) { uint256 withdrawableBalance = assetBalance(); uint256 total = wmul( lockedAmount, collateralToken.pricePerShare().mul(_decimalShift()) ) .add(withdrawableBalance); return withdrawableBalance.mul(totalSupply()).div(total).sub( MINIMUM_SUPPLY ); }
2,187,487
/* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { AddressArrayUtils } from "set-protocol-contract-utils/contracts/lib/AddressArrayUtils.sol"; import { BoundsLibrary } from "set-protocol-contract-utils/contracts/lib/BoundsLibrary.sol"; import { CommonMath } from "set-protocol-contract-utils/contracts/lib/CommonMath.sol"; import { Auction } from "../impl/Auction.sol"; import { LinearAuction } from "../impl/LinearAuction.sol"; import { LiquidatorUtils } from "../utils/LiquidatorUtils.sol"; import { IOracleWhiteList } from "../../../core/interfaces/IOracleWhiteList.sol"; import { ISetToken } from "../../../core/interfaces/ISetToken.sol"; import { IRebalancingSetTokenV3 } from "../../../core/interfaces/IRebalancingSetTokenV3.sol"; import { TwoAssetPriceBoundedLinearAuction } from "../impl/TwoAssetPriceBoundedLinearAuction.sol"; /** * @title TWAPAuction * @author Set Protocol * * Contract for executing TWAP Auctions from initializing to moving to the next chunk auction. Inherits from * TwoAssetPriceBoundedLinearAuction */ contract TWAPAuction is TwoAssetPriceBoundedLinearAuction { using SafeMath for uint256; using CommonMath for uint256; using AddressArrayUtils for address[]; using BoundsLibrary for BoundsLibrary.Bounds; /* ============ Structs ============ */ struct TWAPState { LinearAuction.State chunkAuction; // Current chunk auction state uint256 orderSize; // Beginning amount of currentSets uint256 orderRemaining; // Amount of current Sets not auctioned or being auctioned uint256 lastChunkAuctionEnd; // Time of last chunk auction end uint256 chunkAuctionPeriod; // Time between chunk auctions uint256 chunkSize; // Amount of current Sets in a full chunk auction } struct TWAPLiquidatorData { uint256 chunkSizeValue; // Currency value of rebalance volume in each chunk (18 decimal) uint256 chunkAuctionPeriod; // Time between chunk auctions } struct AssetPairVolumeBounds { address assetOne; // Address of first asset in pair address assetTwo; // Address of second asset in pair BoundsLibrary.Bounds bounds; // Chunk size volume bounds for asset pair } /* ============ Constants ============ */ // Auction completion buffer assumes completion potentially 2% after fair value when auction started uint256 constant public AUCTION_COMPLETION_BUFFER = 2e16; /* ============ State Variables ============ */ // Mapping between an address pair's addresses and the min/max USD-chunk size, each asset pair will // have two entries, one for each ordering of the addresses mapping(address => mapping(address => BoundsLibrary.Bounds)) public chunkSizeWhiteList; //Estimated length in seconds of a chunk auction uint256 public expectedChunkAuctionLength; /* ============ Constructor ============ */ /** * TWAPAuction constructor * * @param _oracleWhiteList OracleWhiteList used by liquidator * @param _auctionPeriod Length of auction in seconds * @param _rangeStart Percentage below FairValue to begin auction at in 18 decimal value * @param _rangeEnd Percentage above FairValue to end auction at in 18 decimal value * @param _assetPairVolumeBounds List of chunk size bounds for each asset pair */ constructor( IOracleWhiteList _oracleWhiteList, uint256 _auctionPeriod, uint256 _rangeStart, uint256 _rangeEnd, AssetPairVolumeBounds[] memory _assetPairVolumeBounds ) public TwoAssetPriceBoundedLinearAuction( _oracleWhiteList, _auctionPeriod, _rangeStart, _rangeEnd ) { require( _rangeEnd >= AUCTION_COMPLETION_BUFFER, "TWAPAuction.constructor: Passed range end must exceed completion buffer." ); // Not using CommonMath.scaleFactoor() due to compilation issues related to constructor size require( _rangeEnd <= 1e18 && _rangeStart <= 1e18, "TWAPAuction.constructor: Range bounds must be less than 100%." ); for (uint256 i = 0; i < _assetPairVolumeBounds.length; i++) { BoundsLibrary.Bounds memory bounds = _assetPairVolumeBounds[i].bounds; // Not using native library due to compilation issues related to constructor size require( bounds.lower <= bounds.upper, "TWAPAuction.constructor: Passed asset pair bounds are invalid." ); address assetOne = _assetPairVolumeBounds[i].assetOne; address assetTwo = _assetPairVolumeBounds[i].assetTwo; require( chunkSizeWhiteList[assetOne][assetTwo].upper == 0, "TWAPAuction.constructor: Asset pair volume bounds must be unique." ); chunkSizeWhiteList[assetOne][assetTwo] = bounds; chunkSizeWhiteList[assetTwo][assetOne] = bounds; } // Expected length of a chunk auction, assuming the auction goes 2% beyond initial fair // value. Used to validate TWAP Auction length won't exceed Set's rebalanceFailPeriod. // Not using SafeMath due to compilation issues related to constructor size require( _auctionPeriod < -uint256(1) / (_rangeStart + AUCTION_COMPLETION_BUFFER), "TWAPAuction.constructor: Auction period too long." ); expectedChunkAuctionLength = _auctionPeriod * (_rangeStart + AUCTION_COMPLETION_BUFFER) / (_rangeStart + _rangeEnd); require( expectedChunkAuctionLength > 0, "TWAPAuction.constructor: Expected auction length must exceed 0." ); } /* ============ Internal Functions ============ */ /** * Populates the TWAPState struct and initiates first chunk auction. * * @param _twapAuction TWAPAuction State object * @param _currentSet The Set to rebalance from * @param _nextSet The Set to rebalance to * @param _startingCurrentSetQuantity Quantity of currentSet to rebalance * @param _chunkSizeValue Value of chunk size in terms of currency represented by * the oracleWhiteList * @param _chunkAuctionPeriod Time between chunk auctions */ function initializeTWAPAuction( TWAPState storage _twapAuction, ISetToken _currentSet, ISetToken _nextSet, uint256 _startingCurrentSetQuantity, uint256 _chunkSizeValue, uint256 _chunkAuctionPeriod ) internal { // Initialize first chunk auction with the currentSetQuantity to populate LinearAuction struct // This will be overwritten by the initial chunk auction quantity LinearAuction.initializeLinearAuction( _twapAuction.chunkAuction, _currentSet, _nextSet, _startingCurrentSetQuantity ); // Calculate currency value of rebalance volume uint256 rebalanceVolume = LiquidatorUtils.calculateRebalanceVolume( _currentSet, _nextSet, oracleWhiteList, _startingCurrentSetQuantity ); // Calculate the size of each chunk auction in currentSet terms uint256 chunkSize = calculateChunkSize( _startingCurrentSetQuantity, rebalanceVolume, _chunkSizeValue ); // Normalize the chunkSize and orderSize to ensure all values are a multiple of // the minimum bid uint256 minBid = _twapAuction.chunkAuction.auction.minimumBid; uint256 normalizedChunkSize = chunkSize.div(minBid).mul(minBid); uint256 totalOrderSize = _startingCurrentSetQuantity.div(minBid).mul(minBid); // Initialize the first chunkAuction to the normalized chunk size _twapAuction.chunkAuction.auction.startingCurrentSets = normalizedChunkSize; _twapAuction.chunkAuction.auction.remainingCurrentSets = normalizedChunkSize; // Set TWAPState _twapAuction.orderSize = totalOrderSize; _twapAuction.orderRemaining = totalOrderSize.sub(normalizedChunkSize); _twapAuction.chunkSize = normalizedChunkSize; _twapAuction.lastChunkAuctionEnd = 0; _twapAuction.chunkAuctionPeriod = _chunkAuctionPeriod; } /** * Calculates size of next chunk auction and then starts then parameterizes the auction and overwrites * the previous auction state. The orderRemaining is updated to take into account the currentSets included * in the new chunk auction. Function can only be called provided the following conditions have been met: * - Last chunk auction is finished (remainingCurrentSets < minimumBid) * - There is still more collateral to auction off * - The chunkAuctionPeriod has elapsed * * @param _twapAuction TWAPAuction State object */ function auctionNextChunk( TWAPState storage _twapAuction ) internal { // Add leftover current Sets from previous chunk auction to orderRemaining uint256 totalRemainingSets = _twapAuction.orderRemaining.add( _twapAuction.chunkAuction.auction.remainingCurrentSets ); // Calculate next chunk auction size as min of chunkSize or orderRemaining uint256 nextChunkAuctionSize = Math.min(_twapAuction.chunkSize, totalRemainingSets); // Start new chunk auction by over writing previous auction state and decrementing orderRemaining overwriteChunkAuctionState(_twapAuction, nextChunkAuctionSize); _twapAuction.orderRemaining = totalRemainingSets.sub(nextChunkAuctionSize); } /* ============ Internal Helper Functions ============ */ /** * Resets state for next chunk auction (except minimumBid and token flow arrays) * * @param _twapAuction TWAPAuction State object * @param _chunkAuctionSize Size of next chunk auction */ function overwriteChunkAuctionState( TWAPState storage _twapAuction, uint256 _chunkAuctionSize ) internal { _twapAuction.chunkAuction.auction.startingCurrentSets = _chunkAuctionSize; _twapAuction.chunkAuction.auction.remainingCurrentSets = _chunkAuctionSize; _twapAuction.chunkAuction.auction.startTime = block.timestamp; _twapAuction.chunkAuction.endTime = block.timestamp.add(auctionPeriod); // Since currentSet and nextSet param is not used in calculating start and end price on // TwoAssetPriceBoundedLinearAuction we can pass in zero addresses _twapAuction.chunkAuction.startPrice = calculateStartPrice( _twapAuction.chunkAuction.auction, ISetToken(address(0)), ISetToken(address(0)) ); _twapAuction.chunkAuction.endPrice = calculateEndPrice( _twapAuction.chunkAuction.auction, ISetToken(address(0)), ISetToken(address(0)) ); } /** * Validates that chunk size is within asset bounds and passed chunkAuctionLength * is unlikely to push TWAPAuction beyond rebalanceFailPeriod. * * @param _currentSet The Set to rebalance from * @param _nextSet The Set to rebalance to * @param _startingCurrentSetQuantity Quantity of currentSet to rebalance * @param _chunkSizeValue Value of chunk size in terms of currency represented by * the oracleWhiteList * @param _chunkAuctionPeriod Time between chunk auctions */ function validateLiquidatorData( ISetToken _currentSet, ISetToken _nextSet, uint256 _startingCurrentSetQuantity, uint256 _chunkSizeValue, uint256 _chunkAuctionPeriod ) internal view { // Calculate currency value of rebalance volume uint256 rebalanceVolume = LiquidatorUtils.calculateRebalanceVolume( _currentSet, _nextSet, oracleWhiteList, _startingCurrentSetQuantity ); BoundsLibrary.Bounds memory volumeBounds = getVolumeBoundsFromCollateral(_currentSet, _nextSet); validateTWAPParameters( _chunkSizeValue, _chunkAuctionPeriod, rebalanceVolume, volumeBounds ); } /** * Validates passed in parameters for TWAP auction * * @param _chunkSizeValue Value of chunk size in terms of currency represented by * the oracleWhiteList * @param _chunkAuctionPeriod Time between chunk auctions * @param _rebalanceVolume Value of collateral being rebalanced * @param _assetPairVolumeBounds Volume bounds of asset pair */ function validateTWAPParameters( uint256 _chunkSizeValue, uint256 _chunkAuctionPeriod, uint256 _rebalanceVolume, BoundsLibrary.Bounds memory _assetPairVolumeBounds ) internal view { // Bounds and chunkSizeValue denominated in currency value require( _assetPairVolumeBounds.isWithin(_chunkSizeValue), "TWAPAuction.validateTWAPParameters: Passed chunk size must be between bounds." ); // Want to make sure that the expected length of the auction is less than the rebalanceFailPeriod // or else a legitimate auction could be failed. Calculated as such: // expectedTWAPTime = numChunkAuctions * expectedChunkAuctionLength + (numChunkAuctions - 1) * // chunkAuctionPeriod uint256 numChunkAuctions = _rebalanceVolume.divCeil(_chunkSizeValue); uint256 expectedTWAPAuctionTime = numChunkAuctions.mul(expectedChunkAuctionLength) .add(numChunkAuctions.sub(1).mul(_chunkAuctionPeriod)); uint256 rebalanceFailPeriod = IRebalancingSetTokenV3(msg.sender).rebalanceFailPeriod(); require( expectedTWAPAuctionTime < rebalanceFailPeriod, "TWAPAuction.validateTWAPParameters: Expected auction duration exceeds allowed length." ); } /** * The next chunk auction can begin when the previous auction has completed, there are still currentSets to * rebalance, and the auction period has elapsed. * * @param _twapAuction TWAPAuction State object */ function validateNextChunkAuction( TWAPState storage _twapAuction ) internal view { Auction.validateAuctionCompletion(_twapAuction.chunkAuction.auction); require( isRebalanceActive(_twapAuction), "TWAPState.validateNextChunkAuction: TWAPAuction is finished." ); require( _twapAuction.lastChunkAuctionEnd.add(_twapAuction.chunkAuctionPeriod) <= block.timestamp, "TWAPState.validateNextChunkAuction: Not enough time elapsed from last chunk auction end." ); } /** * Checks if the amount of Sets still to be auctioned (in aggregate) is greater than the minimumBid * * @param _twapAuction TWAPAuction State object */ function isRebalanceActive( TWAPState storage _twapAuction ) internal view returns (bool) { // Sum of remaining Sets in current chunk auction and order remaining uint256 totalRemainingSets = calculateTotalSetsRemaining(_twapAuction); // Check that total remaining sets is greater than minimumBid return totalRemainingSets >= _twapAuction.chunkAuction.auction.minimumBid; } /** * Calculates chunkSize of auction in current Set terms * * @param _totalSetAmount Total amount of Sets being auctioned * @param _rebalanceVolume The total currency value being auctioned * @param _chunkSizeValue Value of chunk size in currency terms */ function calculateChunkSize( uint256 _totalSetAmount, uint256 _rebalanceVolume, uint256 _chunkSizeValue ) internal view returns (uint256) { // Since solidity rounds down anything equal to 1 will require at least one auction // equal to the chunkSizeValue if (_rebalanceVolume.div(_chunkSizeValue) >= 1) { return _totalSetAmount.mul(_chunkSizeValue).div(_rebalanceVolume); } else { return _totalSetAmount; } } /** * Calculates the total remaining sets in the auction between the currently underway chunk auction and * the Sets that have yet to be included in a chunk auction. * * @param _twapAuction TWAPAuction State object */ function calculateTotalSetsRemaining(TWAPAuction.TWAPState storage _twapAuction) internal view returns (uint256) { return _twapAuction.orderRemaining.add(_twapAuction.chunkAuction.auction.remainingCurrentSets); } /** * Returns asset pair volume bounds based on passed in collateral Sets. * * @param _currentSet The Set to rebalance from * @param _nextSet The Set to rebalance to */ function getVolumeBoundsFromCollateral( ISetToken _currentSet, ISetToken _nextSet ) internal view returns (BoundsLibrary.Bounds memory) { // Get set components address[] memory currentSetComponents = _currentSet.getComponents(); address[] memory nextSetComponents = _nextSet.getComponents(); address firstComponent = currentSetComponents [0]; address secondComponent = currentSetComponents.length > 1 ? currentSetComponents [1] : nextSetComponents [0] != firstComponent ? nextSetComponents [0] : nextSetComponents [1]; return chunkSizeWhiteList[firstComponent][secondComponent]; } function parseLiquidatorData( bytes memory _liquidatorData ) internal pure returns (uint256, uint256) { return abi.decode(_liquidatorData, (uint256, uint256)); } }
Populates the TWAPState struct and initiates first chunk auction. _twapAuction TWAPAuction State object _currentSet The Set to rebalance from _nextSet The Set to rebalance to _startingCurrentSetQuantity Quantity of currentSet to rebalance _chunkSizeValue Value of chunk size in terms of currency represented by the oracleWhiteList _chunkAuctionPeriod Time between chunk auctions/ Initialize first chunk auction with the currentSetQuantity to populate LinearAuction struct This will be overwritten by the initial chunk auction quantity Calculate currency value of rebalance volume Calculate the size of each chunk auction in currentSet terms Normalize the chunkSize and orderSize to ensure all values are a multiple of the minimum bid Initialize the first chunkAuction to the normalized chunk size Set TWAPState
function initializeTWAPAuction( TWAPState storage _twapAuction, ISetToken _currentSet, ISetToken _nextSet, uint256 _startingCurrentSetQuantity, uint256 _chunkSizeValue, uint256 _chunkAuctionPeriod ) internal { LinearAuction.initializeLinearAuction( _twapAuction.chunkAuction, _currentSet, _nextSet, _startingCurrentSetQuantity ); uint256 rebalanceVolume = LiquidatorUtils.calculateRebalanceVolume( _currentSet, _nextSet, oracleWhiteList, _startingCurrentSetQuantity ); uint256 chunkSize = calculateChunkSize( _startingCurrentSetQuantity, rebalanceVolume, _chunkSizeValue ); uint256 minBid = _twapAuction.chunkAuction.auction.minimumBid; uint256 normalizedChunkSize = chunkSize.div(minBid).mul(minBid); uint256 totalOrderSize = _startingCurrentSetQuantity.div(minBid).mul(minBid); _twapAuction.chunkAuction.auction.startingCurrentSets = normalizedChunkSize; _twapAuction.chunkAuction.auction.remainingCurrentSets = normalizedChunkSize; _twapAuction.orderSize = totalOrderSize; _twapAuction.orderRemaining = totalOrderSize.sub(normalizedChunkSize); _twapAuction.chunkSize = normalizedChunkSize; _twapAuction.lastChunkAuctionEnd = 0; _twapAuction.chunkAuctionPeriod = _chunkAuctionPeriod; }
12,726,504
pragma solidity ^0.6; import "../../../lib/SafeMath.sol"; import {Ownable} from "../ownership/Ownable.sol"; /** * Stores information for added training data and corresponding meta-data. */ interface DataHandler { function updateClaimableAmount(bytes32 dataKey, uint rewardAmount) external; } /** * Stores information for added training data and corresponding meta-data. */ contract DataHandler64 is Ownable, DataHandler { using SafeMath for uint256; struct StoredData { /** * The data stored. */ // Don't store the data because it's not really needed since we emit events when data is added. // The main reason for storing the data in here is to ensure equality on future interactions like when refunding. // This extra equality check is only necessary if you're worried about hash collisions. // int64[] d; /** * The classification for the data. */ uint64 c; /** * The time it was added. */ uint t; /** * The address that added the data. */ address sender; /** * The amount that was initially given to deposit this data. */ uint initialDeposit; /** * The amount of the deposit that can still be claimed. */ uint claimableAmount; /** * The number of claims that have been made for refunds or reports. * This should be the size of `claimedBy`. */ uint numClaims; /** * The set of addresses that claimed a refund or reward on this data. */ mapping(address => bool) claimedBy; } /** * Meta-data for data that has been added. */ mapping(bytes32 => StoredData) public addedData; function getClaimableAmount(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor) public view returns (uint) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; // Validate found value. // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.claimableAmount; } function getInitialDeposit(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor) public view returns (uint) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; // Validate found value. // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.initialDeposit; } function getNumClaims(int64[] memory data, uint64 classification, uint addedTime, address originalAuthor) public view returns (uint) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; // Validate found value. // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.numClaims; } /** * Check if two arrays of training data are equal. */ function isDataEqual(int64[] memory d1, int64[] memory d2) public pure returns (bool) { if (d1.length != d2.length) { return false; } for (uint i = 0; i < d1.length; ++i) { if (d1[i] != d2[i]) { return false; } } return true; } /** * Log an attempt to add data. * * @param msgSender The address of the one attempting to add data. * @param cost The cost required to add new data. * @param data A single sample of training data for the model. * @param classification The label for `data`. * @return time The time which the data was added, i.e. the current time in seconds. */ function handleAddData(address msgSender, uint cost, int64[] memory data, uint64 classification) public onlyOwner returns (uint time) { time = now; // solium-disable-line security/no-block-members bytes32 key = keccak256(abi.encodePacked(data, classification, time, msgSender)); StoredData storage existingData = addedData[key]; bool okayToOverwrite = existingData.sender == address(0) || existingData.claimableAmount == 0; require(okayToOverwrite, "Conflicting data key. The data may have already been added."); // Maybe we do want to allow duplicate data to be added but just not from the same address. // Of course that is not sybil-proof. // Store data. addedData[key] = StoredData({ // not necessary: d: data, c: classification, t: time, sender: msgSender, initialDeposit: cost, claimableAmount: cost, numClaims: 0 }); } /** * Log a refund attempt. * * @param submitter The address of the one attempting a refund. * @param data The data for which to attempt a refund. * @param classification The label originally submitted for `data`. * @param addedTime The time in seconds for which the data was added. * @return claimableAmount The amount that can be claimed for the refund. * @return claimedBySubmitter `true` if the data has already been claimed by `submitter`, otherwise `false`. * @return numClaims The number of claims that have been made for the contribution before this request. */ function handleRefund(address submitter, int64[] memory data, uint64 classification, uint addedTime) public onlyOwner returns (uint claimableAmount, bool claimedBySubmitter, uint numClaims) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, submitter)); StoredData storage existingData = addedData[key]; // Validate found value. require(existingData.sender != address(0), "Data not found."); // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == submitter, "Data is not from the sender."); claimableAmount = existingData.claimableAmount; claimedBySubmitter = existingData.claimedBy[submitter]; numClaims = existingData.numClaims; // Upon successful completion of the refund the values will be claimed. existingData.claimableAmount = 0; existingData.claimedBy[submitter] = true; existingData.numClaims = numClaims.add(1); } /** * Retrieve information about the data to report. * * @param reporter The address of the one reporting the data. * @param data The data to report. * @param classification The label submitted for `data`. * @param addedTime The time in seconds for which the data was added. * @param originalAuthor The address that originally added the data. * @return initialDeposit The amount that was initially deposited when the data contribution was submitted. * @return claimableAmount The amount remainining that can be claimed. * @return claimedByReporter `true` if the data has already been claimed by `reporter`, otherwise `false`. * @return numClaims The number of claims that have been made for the contribution before this request. * @return dataKey The key to the stored data. */ function handleReport( address reporter, int64[] memory data, uint64 classification, uint addedTime, address originalAuthor) public onlyOwner returns (uint initialDeposit, uint claimableAmount, bool claimedByReporter, uint numClaims, bytes32 dataKey) { dataKey = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[dataKey]; // Validate found value. require(existingData.sender != address(0), "Data not found."); // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Sender is not equal."); initialDeposit = existingData.initialDeposit; claimableAmount = existingData.claimableAmount; claimedByReporter = existingData.claimedBy[reporter]; numClaims = existingData.numClaims; existingData.claimedBy[reporter] = true; existingData.numClaims = numClaims.add(1); } /** * @return `true` if the contribution has already been claimed by `claimer`, otherwise `false`. */ function hasClaimed( int64[] memory data, uint64 classification, uint addedTime, address originalAuthor, address claimer) public view returns (bool) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; // Validate found value. // usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal."); require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.claimedBy[claimer]; } function updateClaimableAmount(bytes32 dataKey, uint rewardAmount) public override onlyOwner { StoredData storage existingData = addedData[dataKey]; // Already validated key lookup. existingData.claimableAmount = existingData.claimableAmount.sub(rewardAmount); } }
return `true` if the contribution has already been claimed by `claimer`, otherwise `false`./ Validate found value. usually unnecessary: require(isDataEqual(existingData.d, data), "Data is not equal.");
function hasClaimed( int64[] memory data, uint64 classification, uint addedTime, address originalAuthor, address claimer) public view returns (bool) { bytes32 key = keccak256(abi.encodePacked(data, classification, addedTime, originalAuthor)); StoredData storage existingData = addedData[key]; require(existingData.c == classification, "Classification is not equal."); require(existingData.t == addedTime, "Added time is not equal."); require(existingData.sender == originalAuthor, "Data isn't from the right author."); return existingData.claimedBy[claimer]; }
12,872,859
// Verified using https://dapp.tools // hevm: flattened sources of src/token.sol // SPDX-License-Identifier: MIT AND GPL-3.0-only pragma solidity >=0.8.0 <0.9.0 >=0.8.2 <0.9.0 >=0.8.7 <0.9.0; ////// lib/openzeppelin-contracts/contracts/utils/Context.sol /* pragma solidity ^0.8.0; */ /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } ////// lib/openzeppelin-contracts/contracts/access/Ownable.sol /* pragma solidity ^0.8.0; */ /* import "../utils/Context.sol"; */ /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } ////// lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol /* pragma solidity ^0.8.0; */ /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } ////// lib/openzeppelin-contracts/contracts/utils/Address.sol /* pragma solidity ^0.8.0; */ /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } ////// lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol /* pragma solidity ^0.8.0; */ /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } ////// lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Upgrade.sol /* pragma solidity ^0.8.2; */ /* import "../beacon/IBeacon.sol"; */ /* import "../../utils/Address.sol"; */ /* import "../../utils/StorageSlot.sol"; */ /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } ////// lib/openzeppelin-contracts/contracts/proxy/Proxy.sol /* pragma solidity ^0.8.0; */ /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } ////// lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Proxy.sol /* pragma solidity ^0.8.0; */ /* import "../Proxy.sol"; */ /* import "./ERC1967Upgrade.sol"; */ /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } ////// lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol /* pragma solidity ^0.8.0; */ /* import "../ERC1967/ERC1967Upgrade.sol"; */ /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is ERC1967Upgrade { /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; } ////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol /* pragma solidity ^0.8.0; */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } ////// lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol /* pragma solidity ^0.8.0; */ /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } ////// lib/openzeppelin-contracts/contracts/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; } ////// lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol /* pragma solidity ^0.8.0; */ /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } ////// lib/openzeppelin-contracts/contracts/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); } ////// lib/openzeppelin-contracts/contracts/utils/Strings.sol /* pragma solidity ^0.8.0; */ /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } ////// lib/openzeppelin-contracts/contracts/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; } } ////// lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol /* pragma solidity ^0.8.0; */ /* import "./IERC721.sol"; */ /* import "./IERC721Receiver.sol"; */ /* import "./extensions/IERC721Metadata.sol"; */ /* import "../../utils/Address.sol"; */ /* import "../../utils/Context.sol"; */ /* import "../../utils/Strings.sol"; */ /* import "../../utils/introspection/ERC165.sol"; */ /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } ////// lib/radicle-drips-hub/src/Dai.sol /* pragma solidity ^0.8.7; */ /* import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; */ interface IDai is IERC20 { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } ////// lib/radicle-drips-hub/src/ERC20Reserve.sol /* pragma solidity ^0.8.7; */ /* import {Ownable} from "openzeppelin-contracts/access/Ownable.sol"; */ /* import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; */ interface IERC20Reserve { function erc20() external view returns (IERC20); function withdraw(uint256 amt) external; function deposit(uint256 amt) external; } contract ERC20Reserve is IERC20Reserve, Ownable { IERC20 public immutable override erc20; address public user; uint256 public balance; event Withdrawn(address to, uint256 amt); event Deposited(address from, uint256 amt); event ForceWithdrawn(address to, uint256 amt); event UserSet(address oldUser, address newUser); constructor( IERC20 _erc20, address owner, address _user ) { erc20 = _erc20; setUser(_user); transferOwnership(owner); } modifier onlyUser() { require(_msgSender() == user, "Reserve: caller is not the user"); _; } function withdraw(uint256 amt) public override onlyUser { require(balance >= amt, "Reserve: withdrawal over balance"); balance -= amt; emit Withdrawn(_msgSender(), amt); require(erc20.transfer(_msgSender(), amt), "Reserve: transfer failed"); } function deposit(uint256 amt) public override onlyUser { balance += amt; emit Deposited(_msgSender(), amt); require(erc20.transferFrom(_msgSender(), address(this), amt), "Reserve: transfer failed"); } function forceWithdraw(uint256 amt) public onlyOwner { emit ForceWithdrawn(_msgSender(), amt); require(erc20.transfer(_msgSender(), amt), "Reserve: transfer failed"); } function setUser(address newUser) public onlyOwner { emit UserSet(user, newUser); user = newUser; } } ////// lib/radicle-drips-hub/src/DaiReserve.sol /* pragma solidity ^0.8.7; */ /* import {ERC20Reserve, IERC20Reserve} from "./ERC20Reserve.sol"; */ /* import {IDai} from "./Dai.sol"; */ interface IDaiReserve is IERC20Reserve { function dai() external view returns (IDai); } contract DaiReserve is ERC20Reserve, IDaiReserve { IDai public immutable override dai; constructor( IDai _dai, address owner, address user ) ERC20Reserve(_dai, owner, user) { dai = _dai; } } ////// lib/radicle-drips-hub/src/DripsHub.sol /* pragma solidity ^0.8.7; */ struct DripsReceiver { address receiver; uint128 amtPerSec; } struct SplitsReceiver { address receiver; uint32 weight; } /// @notice Drips hub contract. Automatically drips and splits funds between users. /// /// The user can transfer some funds to their drips balance in the contract /// and configure a list of receivers, to whom they want to drip these funds. /// As soon as the drips balance is enough to cover at least 1 second of dripping /// to the configured receivers, the funds start dripping automatically. /// Every second funds are deducted from the drips balance and moved to their receivers' accounts. /// The process stops automatically when the drips balance is not enough to cover another second. /// /// The user can have any number of independent configurations and drips balances by using accounts. /// An account is identified by the user address and an account identifier. /// Accounts of different users are separate entities, even if they have the same identifiers. /// An account can be used to drip or give, but not to receive funds. /// /// Every user has a receiver balance, in which they have funds received from other users. /// The dripped funds are added to the receiver balances in global cycles. /// Every `cycleSecs` seconds the drips hub adds dripped funds to the receivers' balances, /// so recently dripped funds may not be collectable immediately. /// `cycleSecs` is a constant configured when the drips hub is deployed. /// The receiver balance is independent from the drips balance, /// to drip received funds they need to be first collected and then added to the drips balance. /// /// The user can share collected funds with other users by using splits. /// When collecting, the user gives each of their splits receivers a fraction of the received funds. /// Funds received from splits are available for collection immediately regardless of the cycle. /// They aren't exempt from being split, so they too can be split when collected. /// Users can build chains and networks of splits between each other. /// Anybody can request collection of funds for any user, /// which can be used to enforce the flow of funds in the network of splits. /// /// The concept of something happening periodically, e.g. every second or every `cycleSecs` are /// only high-level abstractions for the user, Ethereum isn't really capable of scheduling work. /// The actual implementation emulates that behavior by calculating the results of the scheduled /// events based on how many seconds have passed and only when the user needs their outcomes. /// /// The contract assumes that all amounts in the system can be stored in signed 128-bit integers. /// It's guaranteed to be safe only when working with assets with supply lower than `2 ^ 127`. abstract contract DripsHub { /// @notice On every timestamp `T`, which is a multiple of `cycleSecs`, the receivers /// gain access to drips collected during `T - cycleSecs` to `T - 1`. uint64 public immutable cycleSecs; /// @notice Timestamp at which all drips must be finished uint64 internal constant MAX_TIMESTAMP = type(uint64).max - 2; /// @notice Maximum number of drips receivers of a single user. /// Limits cost of changes in drips configuration. uint32 public constant MAX_DRIPS_RECEIVERS = 100; /// @notice Maximum number of splits receivers of a single user. /// Limits cost of collecting. uint32 public constant MAX_SPLITS_RECEIVERS = 200; /// @notice The total splits weight of a user uint32 public constant TOTAL_SPLITS_WEIGHT = 1_000_000; /// @notice The ERC-1967 storage slot for the contract. /// It holds a single `DripsHubStorage` structure. bytes32 private constant SLOT_STORAGE = bytes32(uint256(keccak256("eip1967.dripsHub.storage")) - 1); /// @notice Emitted when drips from a user to a receiver are updated. /// Funds are being dripped on every second between the event block's timestamp (inclusively) /// and`endTime` (exclusively) or until the timestamp of the next drips update (exclusively). /// @param user The dripping user /// @param receiver The receiver of the updated drips /// @param amtPerSec The new amount per second dripped from the user /// to the receiver or 0 if the drips are stopped /// @param endTime The timestamp when dripping will stop, /// always larger than the block timestamp or equal to it if the drips are stopped event Dripping( address indexed user, address indexed receiver, uint128 amtPerSec, uint64 endTime ); /// @notice Emitted when drips from a user's account to a receiver are updated. /// Funds are being dripped on every second between the event block's timestamp (inclusively) /// and`endTime` (exclusively) or until the timestamp of the next drips update (exclusively). /// @param user The user /// @param account The dripping account /// @param receiver The receiver of the updated drips /// @param amtPerSec The new amount per second dripped from the user's account /// to the receiver or 0 if the drips are stopped /// @param endTime The timestamp when dripping will stop, /// always larger than the block timestamp or equal to it if the drips are stopped event Dripping( address indexed user, uint256 indexed account, address indexed receiver, uint128 amtPerSec, uint64 endTime ); /// @notice Emitted when the drips configuration of a user is updated. /// @param user The user /// @param balance The new drips balance. These funds will be dripped to the receivers. /// @param receivers The new list of the drips receivers. event DripsUpdated(address indexed user, uint128 balance, DripsReceiver[] receivers); /// @notice Emitted when the drips configuration of a user's account is updated. /// @param user The user /// @param account The account /// @param balance The new drips balance. These funds will be dripped to the receivers. /// @param receivers The new list of the drips receivers. event DripsUpdated( address indexed user, uint256 indexed account, uint128 balance, DripsReceiver[] receivers ); /// @notice Emitted when the user's splits are updated. /// @param user The user /// @param receivers The list of the user's splits receivers. event SplitsUpdated(address indexed user, SplitsReceiver[] receivers); /// @notice Emitted when a user collects funds /// @param user The user /// @param collected The collected amount /// @param split The amount split to the user's splits receivers event Collected(address indexed user, uint128 collected, uint128 split); /// @notice Emitted when funds are split from a user to a receiver. /// This is caused by the user collecting received funds. /// @param user The user /// @param receiver The splits receiver /// @param amt The amount split to the receiver event Split(address indexed user, address indexed receiver, uint128 amt); /// @notice Emitted when funds are given from the user to the receiver. /// @param user The address of the user /// @param receiver The receiver /// @param amt The given amount event Given(address indexed user, address indexed receiver, uint128 amt); /// @notice Emitted when funds are given from the user's account to the receiver. /// @param user The address of the user /// @param account The user's account /// @param receiver The receiver /// @param amt The given amount event Given( address indexed user, uint256 indexed account, address indexed receiver, uint128 amt ); struct ReceiverState { // The amount collectable independently from cycles uint128 collectable; // The next cycle to be collected uint64 nextCollectedCycle; // --- SLOT BOUNDARY // The changes of collected amounts on specific cycle. // The keys are cycles, each cycle `C` becomes collectable on timestamp `C * cycleSecs`. // Values for cycles before `nextCollectedCycle` are guaranteed to be zeroed. // This means that the value of `amtDeltas[nextCollectedCycle].thisCycle` is always // relative to 0 or in other words it's an absolute value independent from other cycles. mapping(uint64 => AmtDelta) amtDeltas; } struct AmtDelta { // Amount delta applied on this cycle int128 thisCycle; // Amount delta applied on the next cycle int128 nextCycle; } struct UserOrAccount { bool isAccount; address user; uint256 account; } struct DripsHubStorage { /// @notice Users' splits configuration hashes, see `hashSplits`. /// The key is the user address. mapping(address => bytes32) splitsHash; /// @notice Users' drips configuration hashes, see `hashDrips`. /// The key is the user address. mapping(address => bytes32) userDripsHashes; /// @notice Users' accounts' configuration hashes, see `hashDrips`. /// The key are the user address and the account. mapping(address => mapping(uint256 => bytes32)) accountDripsHashes; /// @notice Users' receiver states. /// The key is the user address. mapping(address => ReceiverState) receiverStates; } /// @param _cycleSecs The length of cycleSecs to be used in the contract instance. /// Low value makes funds more available by shortening the average time of funds being frozen /// between being taken from the users' drips balances and being collectable by their receivers. /// High value makes collecting cheaper by making it process less cycles for a given time range. constructor(uint64 _cycleSecs) { cycleSecs = _cycleSecs; } /// @notice Returns the contract storage. /// @return dripsHubStorage The storage. function _storage() internal pure returns (DripsHubStorage storage dripsHubStorage) { bytes32 slot = SLOT_STORAGE; // solhint-disable-next-line no-inline-assembly assembly { // Based on OpenZeppelin's StorageSlot dripsHubStorage.slot := slot } } /// @notice Returns amount of received funds available for collection for a user. /// @param user The user /// @param currReceivers The list of the user's current splits receivers. /// @return collected The collected amount /// @return split The amount split to the user's splits receivers function collectable(address user, SplitsReceiver[] memory currReceivers) public view returns (uint128 collected, uint128 split) { ReceiverState storage receiver = _storage().receiverStates[user]; _assertCurrSplits(user, currReceivers); // Collectable independently from cycles collected = receiver.collectable; // Collectable from cycles uint64 collectedCycle = receiver.nextCollectedCycle; uint64 currFinishedCycle = _currTimestamp() / cycleSecs; if (collectedCycle != 0 && collectedCycle <= currFinishedCycle) { int128 cycleAmt = 0; for (; collectedCycle <= currFinishedCycle; collectedCycle++) { cycleAmt += receiver.amtDeltas[collectedCycle].thisCycle; collected += uint128(cycleAmt); cycleAmt += receiver.amtDeltas[collectedCycle].nextCycle; } } // split when collected if (collected > 0 && currReceivers.length > 0) { uint32 splitsWeight = 0; for (uint256 i = 0; i < currReceivers.length; i++) { splitsWeight += currReceivers[i].weight; } split = uint128((uint160(collected) * splitsWeight) / TOTAL_SPLITS_WEIGHT); collected -= split; } } /// @notice Collects all received funds available for the user /// and transfers them out of the drips hub contract to that user's wallet. /// @param user The user /// @param currReceivers The list of the user's current splits receivers. /// @return collected The collected amount /// @return split The amount split to the user's splits receivers function collect(address user, SplitsReceiver[] memory currReceivers) public virtual returns (uint128 collected, uint128 split) { (collected, split) = _collectInternal(user, currReceivers); _transfer(user, int128(collected)); } /// @notice Counts cycles which will need to be analyzed when collecting or flushing. /// This function can be used to detect that there are too many cycles /// to analyze in a single transaction and flushing is needed. /// @param user The user /// @return flushable The number of cycles which can be flushed function flushableCycles(address user) public view returns (uint64 flushable) { uint64 nextCollectedCycle = _storage().receiverStates[user].nextCollectedCycle; if (nextCollectedCycle == 0) return 0; uint64 currFinishedCycle = _currTimestamp() / cycleSecs; return currFinishedCycle + 1 - nextCollectedCycle; } /// @notice Flushes uncollected cycles of the user. /// Flushed cycles won't need to be analyzed when the user collects from them. /// Calling this function does not collect and does not affect the collectable amount. /// /// This function is needed when collecting funds received over a period so long, that the gas /// needed for analyzing all the uncollected cycles can't fit in a single transaction. /// Calling this function allows spreading the analysis cost over multiple transactions. /// A cycle is never flushed more than once, even if this function is called many times. /// @param user The user /// @param maxCycles The maximum number of flushed cycles. /// If too low, flushing will be cheap, but will cut little gas from the next collection. /// If too high, flushing may become too expensive to fit in a single transaction. /// @return flushable The number of cycles which can be flushed function flushCycles(address user, uint64 maxCycles) public virtual returns (uint64 flushable) { flushable = flushableCycles(user); uint64 cycles = maxCycles < flushable ? maxCycles : flushable; flushable -= cycles; uint128 collected = _flushCyclesInternal(user, cycles); if (collected > 0) _storage().receiverStates[user].collectable += collected; } /// @notice Collects all received funds available for the user, /// but doesn't transfer them to the user's wallet. /// @param user The user /// @param currReceivers The list of the user's current splits receivers. /// @return collected The collected amount /// @return split The amount split to the user's splits receivers function _collectInternal(address user, SplitsReceiver[] memory currReceivers) internal returns (uint128 collected, uint128 split) { mapping(address => ReceiverState) storage receiverStates = _storage().receiverStates; ReceiverState storage receiver = receiverStates[user]; _assertCurrSplits(user, currReceivers); // Collectable independently from cycles collected = receiver.collectable; if (collected > 0) receiver.collectable = 0; // Collectable from cycles uint64 cycles = flushableCycles(user); collected += _flushCyclesInternal(user, cycles); // split when collected if (collected > 0 && currReceivers.length > 0) { uint32 splitsWeight = 0; for (uint256 i = 0; i < currReceivers.length; i++) { splitsWeight += currReceivers[i].weight; uint128 splitsAmt = uint128( (uint160(collected) * splitsWeight) / TOTAL_SPLITS_WEIGHT - split ); split += splitsAmt; address splitsReceiver = currReceivers[i].receiver; receiverStates[splitsReceiver].collectable += splitsAmt; emit Split(user, splitsReceiver, splitsAmt); } collected -= split; } emit Collected(user, collected, split); } /// @notice Collects and clears user's cycles /// @param user The user /// @param count The number of flushed cycles. /// @return collectedAmt The collected amount function _flushCyclesInternal(address user, uint64 count) internal returns (uint128 collectedAmt) { if (count == 0) return 0; ReceiverState storage receiver = _storage().receiverStates[user]; uint64 cycle = receiver.nextCollectedCycle; int128 cycleAmt = 0; for (uint256 i = 0; i < count; i++) { cycleAmt += receiver.amtDeltas[cycle].thisCycle; collectedAmt += uint128(cycleAmt); cycleAmt += receiver.amtDeltas[cycle].nextCycle; delete receiver.amtDeltas[cycle]; cycle++; } // The next cycle delta must be relative to the last collected cycle, which got zeroed. // In other words the next cycle delta must be an absolute value. if (cycleAmt != 0) receiver.amtDeltas[cycle].thisCycle += cycleAmt; receiver.nextCollectedCycle = cycle; } /// @notice Gives funds from the user or their account to the receiver. /// The receiver can collect them immediately. /// Transfers the funds to be given from the user's wallet to the drips hub contract. /// @param userOrAccount The user or their account /// @param receiver The receiver /// @param amt The given amount function _give( UserOrAccount memory userOrAccount, address receiver, uint128 amt ) internal { _storage().receiverStates[receiver].collectable += amt; if (userOrAccount.isAccount) { emit Given(userOrAccount.user, userOrAccount.account, receiver, amt); } else { emit Given(userOrAccount.user, receiver, amt); } _transfer(userOrAccount.user, -int128(amt)); } /// @notice Current user's drips hash, see `hashDrips`. /// @param user The user /// @return currDripsHash The current user's drips hash function dripsHash(address user) public view returns (bytes32 currDripsHash) { return _storage().userDripsHashes[user]; } /// @notice Current user account's drips hash, see `hashDrips`. /// @param user The user /// @param account The account /// @return currDripsHash The current user account's drips hash function dripsHash(address user, uint256 account) public view returns (bytes32 currDripsHash) { return _storage().accountDripsHashes[user][account]; } /// @notice Sets the user's or the account's drips configuration. /// Transfers funds between the user's wallet and the drips hub contract /// to fulfill the change of the drips balance. /// @param userOrAccount The user or their account /// @param lastUpdate The timestamp of the last drips update of the user or the account. /// If this is the first update, pass zero. /// @param lastBalance The drips balance after the last drips update of the user or the account. /// If this is the first update, pass zero. /// @param currReceivers The list of the drips receivers set in the last drips update /// of the user or the account. /// If this is the first update, pass an empty array. /// @param balanceDelta The drips balance change to be applied. /// Positive to add funds to the drips balance, negative to remove them. /// @param newReceivers The list of the drips receivers of the user or the account to be set. /// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs. /// @return newBalance The new drips balance of the user or the account. /// Pass it as `lastBalance` when updating that user or the account for the next time. /// @return realBalanceDelta The actually applied drips balance change. function _setDrips( UserOrAccount memory userOrAccount, uint64 lastUpdate, uint128 lastBalance, DripsReceiver[] memory currReceivers, int128 balanceDelta, DripsReceiver[] memory newReceivers ) internal returns (uint128 newBalance, int128 realBalanceDelta) { _assertCurrDrips(userOrAccount, lastUpdate, lastBalance, currReceivers); uint128 newAmtPerSec = _assertDripsReceiversValid(newReceivers); uint128 currAmtPerSec = _totalDripsAmtPerSec(currReceivers); uint64 currEndTime = _dripsEndTime(lastUpdate, lastBalance, currAmtPerSec); (newBalance, realBalanceDelta) = _updateDripsBalance( lastUpdate, lastBalance, currEndTime, currAmtPerSec, balanceDelta ); uint64 newEndTime = _dripsEndTime(_currTimestamp(), newBalance, newAmtPerSec); _updateDripsReceiversStates( userOrAccount, currReceivers, currEndTime, newReceivers, newEndTime ); _storeNewDrips(userOrAccount, newBalance, newReceivers); _emitDripsUpdated(userOrAccount, newBalance, newReceivers); _transfer(userOrAccount.user, -realBalanceDelta); } /// @notice Validates a list of drips receivers. /// @param receivers The list of drips receivers. /// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs. /// @return totalAmtPerSec The total amount per second of all drips receivers. function _assertDripsReceiversValid(DripsReceiver[] memory receivers) internal pure returns (uint128 totalAmtPerSec) { require(receivers.length <= MAX_DRIPS_RECEIVERS, "Too many drips receivers"); uint256 amtPerSec = 0; address prevReceiver; for (uint256 i = 0; i < receivers.length; i++) { uint128 amt = receivers[i].amtPerSec; require(amt != 0, "Drips receiver amtPerSec is zero"); amtPerSec += amt; address receiver = receivers[i].receiver; if (i > 0) { require(prevReceiver != receiver, "Duplicate drips receivers"); require(prevReceiver < receiver, "Drips receivers not sorted by address"); } prevReceiver = receiver; } require(amtPerSec <= type(uint128).max, "Total drips receivers amtPerSec too high"); return uint128(amtPerSec); } /// @notice Calculates the total amount per second of all the drips receivers. /// @param receivers The list of the receivers. /// It must have passed `_assertDripsReceiversValid` in the past. /// @return totalAmtPerSec The total amount per second of all the drips receivers function _totalDripsAmtPerSec(DripsReceiver[] memory receivers) internal pure returns (uint128 totalAmtPerSec) { uint256 length = receivers.length; uint256 i = 0; while (i < length) { // Safe, because `receivers` passed `_assertDripsReceiversValid` in the past unchecked { totalAmtPerSec += receivers[i++].amtPerSec; } } } /// @notice Updates drips balance. /// @param lastUpdate The timestamp of the last drips update. /// If this is the first update, pass zero. /// @param lastBalance The drips balance after the last drips update. /// If this is the first update, pass zero. /// @param currEndTime Time when drips were supposed to end according to the last drips update. /// @param currAmtPerSec The total amount per second of all drips receivers /// according to the last drips update. /// @param balanceDelta The drips balance change to be applied. /// Positive to add funds to the drips balance, negative to remove them. /// @return newBalance The new drips balance. /// Pass it as `lastBalance` when updating for the next time. /// @return realBalanceDelta The actually applied drips balance change. /// If positive, this is the amount which should be transferred from the user to the drips hub, /// or if negative, from the drips hub to the user. function _updateDripsBalance( uint64 lastUpdate, uint128 lastBalance, uint64 currEndTime, uint128 currAmtPerSec, int128 balanceDelta ) internal view returns (uint128 newBalance, int128 realBalanceDelta) { if (currEndTime > _currTimestamp()) currEndTime = _currTimestamp(); uint128 dripped = (currEndTime - lastUpdate) * currAmtPerSec; int128 currBalance = int128(lastBalance - dripped); int136 balance = currBalance + int136(balanceDelta); if (balance < 0) balance = 0; return (uint128(uint136(balance)), int128(balance - currBalance)); } /// @notice Emit an event when drips are updated. /// @param userOrAccount The user or their account /// @param balance The new drips balance. /// @param receivers The new list of the drips receivers. function _emitDripsUpdated( UserOrAccount memory userOrAccount, uint128 balance, DripsReceiver[] memory receivers ) internal { if (userOrAccount.isAccount) { emit DripsUpdated(userOrAccount.user, userOrAccount.account, balance, receivers); } else { emit DripsUpdated(userOrAccount.user, balance, receivers); } } /// @notice Updates the user's or the account's drips receivers' states. /// It applies the effects of the change of the drips configuration. /// @param userOrAccount The user or their account /// @param currReceivers The list of the drips receivers set in the last drips update /// of the user or the account. /// If this is the first update, pass an empty array. /// @param currEndTime Time when drips were supposed to end according to the last drips update. /// @param newReceivers The list of the drips receivers of the user or the account to be set. /// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs. /// @param newEndTime Time when drips will end according to the new drips configuration. function _updateDripsReceiversStates( UserOrAccount memory userOrAccount, DripsReceiver[] memory currReceivers, uint64 currEndTime, DripsReceiver[] memory newReceivers, uint64 newEndTime ) internal { // Skip iterating over `currReceivers` if dripping has run out uint256 currIdx = currEndTime > _currTimestamp() ? 0 : currReceivers.length; // Skip iterating over `newReceivers` if no new dripping is started uint256 newIdx = newEndTime > _currTimestamp() ? 0 : newReceivers.length; while (true) { // Each iteration gets the next drips update and applies it on the receiver state. // A drips update is composed of two drips receiver configurations, // one current and one new, or from a single drips receiver configuration // if the drips receiver is being added or removed. bool pickCurr = currIdx < currReceivers.length; bool pickNew = newIdx < newReceivers.length; if (!pickCurr && !pickNew) break; if (pickCurr && pickNew) { // There are two candidate drips receiver configurations to create a drips update. // Pick both if they describe the same receiver or the one with a lower address. // The one with a higher address won't be used in this iteration. // Because drips receivers lists are sorted by addresses and deduplicated, // all matching pairs of drips receiver configurations will be found. address currReceiver = currReceivers[currIdx].receiver; address newReceiver = newReceivers[newIdx].receiver; pickCurr = currReceiver <= newReceiver; pickNew = newReceiver <= currReceiver; } // The drips update parameters address receiver; int128 currAmtPerSec = 0; int128 newAmtPerSec = 0; if (pickCurr) { receiver = currReceivers[currIdx].receiver; currAmtPerSec = int128(currReceivers[currIdx].amtPerSec); // Clear the obsolete drips end _setDelta(receiver, currEndTime, currAmtPerSec); currIdx++; } if (pickNew) { receiver = newReceivers[newIdx].receiver; newAmtPerSec = int128(newReceivers[newIdx].amtPerSec); // Apply the new drips end _setDelta(receiver, newEndTime, -newAmtPerSec); newIdx++; } // Apply the drips update since now _setDelta(receiver, _currTimestamp(), newAmtPerSec - currAmtPerSec); _emitDripping(userOrAccount, receiver, uint128(newAmtPerSec), newEndTime); // The receiver may have never been used if (!pickCurr) { ReceiverState storage receiverState = _storage().receiverStates[receiver]; // The receiver has never been used, initialize it if (receiverState.nextCollectedCycle == 0) { receiverState.nextCollectedCycle = _currTimestamp() / cycleSecs + 1; } } } } /// @notice Emit an event when drips from a user to a receiver are updated. /// @param userOrAccount The user or their account /// @param receiver The receiver /// @param amtPerSec The new amount per second dripped from the user or the account /// to the receiver or 0 if the drips are stopped /// @param endTime The timestamp when dripping will stop function _emitDripping( UserOrAccount memory userOrAccount, address receiver, uint128 amtPerSec, uint64 endTime ) internal { if (amtPerSec == 0) endTime = _currTimestamp(); if (userOrAccount.isAccount) { emit Dripping(userOrAccount.user, userOrAccount.account, receiver, amtPerSec, endTime); } else { emit Dripping(userOrAccount.user, receiver, amtPerSec, endTime); } } /// @notice Calculates the timestamp when dripping will end. /// @param startTime Time when dripping is started. /// @param startBalance The drips balance when dripping is started. /// @param totalAmtPerSec The total amount per second of all the drips receivers /// @return dripsEndTime The dripping end time. function _dripsEndTime( uint64 startTime, uint128 startBalance, uint128 totalAmtPerSec ) internal pure returns (uint64 dripsEndTime) { if (totalAmtPerSec == 0) return startTime; uint256 endTime = startTime + uint256(startBalance / totalAmtPerSec); return endTime > MAX_TIMESTAMP ? MAX_TIMESTAMP : uint64(endTime); } /// @notice Asserts that the drips configuration is the currently used one. /// @param userOrAccount The user or their account /// @param lastUpdate The timestamp of the last drips update of the user or the account. /// If this is the first update, pass zero. /// @param lastBalance The drips balance after the last drips update of the user or the account. /// If this is the first update, pass zero. /// @param currReceivers The list of the drips receivers set in the last drips update /// of the user or the account. /// If this is the first update, pass an empty array. function _assertCurrDrips( UserOrAccount memory userOrAccount, uint64 lastUpdate, uint128 lastBalance, DripsReceiver[] memory currReceivers ) internal view { bytes32 expectedHash; if (userOrAccount.isAccount) { expectedHash = _storage().accountDripsHashes[userOrAccount.user][userOrAccount.account]; } else { expectedHash = _storage().userDripsHashes[userOrAccount.user]; } bytes32 actualHash = hashDrips(lastUpdate, lastBalance, currReceivers); require(actualHash == expectedHash, "Invalid current drips configuration"); } /// @notice Stores the hash of the new drips configuration to be used in `_assertCurrDrips`. /// @param userOrAccount The user or their account /// @param newBalance The user or the account drips balance. /// @param newReceivers The list of the drips receivers of the user or the account. /// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs. function _storeNewDrips( UserOrAccount memory userOrAccount, uint128 newBalance, DripsReceiver[] memory newReceivers ) internal { bytes32 newDripsHash = hashDrips(_currTimestamp(), newBalance, newReceivers); if (userOrAccount.isAccount) { _storage().accountDripsHashes[userOrAccount.user][userOrAccount.account] = newDripsHash; } else { _storage().userDripsHashes[userOrAccount.user] = newDripsHash; } } /// @notice Calculates the hash of the drips configuration. /// It's used to verify if drips configuration is the previously set one. /// @param update The timestamp of the drips update. /// If the drips have never been updated, pass zero. /// @param balance The drips balance. /// If the drips have never been updated, pass zero. /// @param receivers The list of the drips receivers. /// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs. /// If the drips have never been updated, pass an empty array. /// @return dripsConfigurationHash The hash of the drips configuration function hashDrips( uint64 update, uint128 balance, DripsReceiver[] memory receivers ) public pure returns (bytes32 dripsConfigurationHash) { if (update == 0 && balance == 0 && receivers.length == 0) return bytes32(0); return keccak256(abi.encode(receivers, update, balance)); } /// @notice Collects funds received by the user and sets their splits. /// The collected funds are split according to `currReceivers`. /// @param user The user /// @param currReceivers The list of the user's splits receivers which is currently in use. /// If this function is called for the first time for the user, should be an empty array. /// @param newReceivers The new list of the user's splits receivers. /// Must be sorted by the splits receivers' addresses, deduplicated and without 0 weights. /// Each splits receiver will be getting `weight / TOTAL_SPLITS_WEIGHT` /// share of the funds collected by the user. /// @return collected The collected amount /// @return split The amount split to the user's splits receivers function _setSplits( address user, SplitsReceiver[] memory currReceivers, SplitsReceiver[] memory newReceivers ) internal returns (uint128 collected, uint128 split) { (collected, split) = _collectInternal(user, currReceivers); _assertSplitsValid(newReceivers); _storage().splitsHash[user] = hashSplits(newReceivers); emit SplitsUpdated(user, newReceivers); _transfer(user, int128(collected)); } /// @notice Validates a list of splits receivers /// @param receivers The list of splits receivers /// Must be sorted by the splits receivers' addresses, deduplicated and without 0 weights. function _assertSplitsValid(SplitsReceiver[] memory receivers) internal pure { require(receivers.length <= MAX_SPLITS_RECEIVERS, "Too many splits receivers"); uint64 totalWeight = 0; address prevReceiver; for (uint256 i = 0; i < receivers.length; i++) { uint32 weight = receivers[i].weight; require(weight != 0, "Splits receiver weight is zero"); totalWeight += weight; address receiver = receivers[i].receiver; if (i > 0) { require(prevReceiver != receiver, "Duplicate splits receivers"); require(prevReceiver < receiver, "Splits receivers not sorted by address"); } prevReceiver = receiver; } require(totalWeight <= TOTAL_SPLITS_WEIGHT, "Splits weights sum too high"); } /// @notice Current user's splits hash, see `hashSplits`. /// @param user The user /// @return currSplitsHash The current user's splits hash function splitsHash(address user) public view returns (bytes32 currSplitsHash) { return _storage().splitsHash[user]; } /// @notice Asserts that the list of splits receivers is the user's currently used one. /// @param user The user /// @param currReceivers The list of the user's current splits receivers. function _assertCurrSplits(address user, SplitsReceiver[] memory currReceivers) internal view { require( hashSplits(currReceivers) == _storage().splitsHash[user], "Invalid current splits receivers" ); } /// @notice Calculates the hash of the list of splits receivers. /// @param receivers The list of the splits receivers. /// Must be sorted by the splits receivers' addresses, deduplicated and without 0 weights. /// @return receiversHash The hash of the list of splits receivers. function hashSplits(SplitsReceiver[] memory receivers) public pure returns (bytes32 receiversHash) { if (receivers.length == 0) return bytes32(0); return keccak256(abi.encode(receivers)); } /// @notice Called when funds need to be transferred between the user and the drips hub. /// The function must be called no more than once per transaction. /// @param user The user /// @param amt The transferred amount. /// Positive to transfer funds to the user, negative to transfer from them. function _transfer(address user, int128 amt) internal virtual; /// @notice Sets amt delta of a user on a given timestamp /// @param user The user /// @param timestamp The timestamp from which the delta takes effect /// @param amtPerSecDelta Change of the per-second receiving rate function _setDelta( address user, uint64 timestamp, int128 amtPerSecDelta ) internal { if (amtPerSecDelta == 0) return; mapping(uint64 => AmtDelta) storage amtDeltas = _storage().receiverStates[user].amtDeltas; // In order to set a delta on a specific timestamp it must be introduced in two cycles. // The cycle delta is split proportionally based on how much this cycle is affected. // The next cycle has the rest of the delta applied, so the update is fully completed. uint64 thisCycle = timestamp / cycleSecs + 1; uint64 nextCycleSecs = timestamp % cycleSecs; uint64 thisCycleSecs = cycleSecs - nextCycleSecs; amtDeltas[thisCycle].thisCycle += int128(uint128(thisCycleSecs)) * amtPerSecDelta; amtDeltas[thisCycle].nextCycle += int128(uint128(nextCycleSecs)) * amtPerSecDelta; } function _userOrAccount(address user) internal pure returns (UserOrAccount memory) { return UserOrAccount({isAccount: false, user: user, account: 0}); } function _userOrAccount(address user, uint256 account) internal pure returns (UserOrAccount memory) { return UserOrAccount({isAccount: true, user: user, account: account}); } function _currTimestamp() internal view returns (uint64) { return uint64(block.timestamp); } } ////// lib/radicle-drips-hub/src/ManagedDripsHub.sol /* pragma solidity ^0.8.7; */ /* import {UUPSUpgradeable} from "openzeppelin-contracts/proxy/utils/UUPSUpgradeable.sol"; */ /* import {ERC1967Proxy} from "openzeppelin-contracts/proxy/ERC1967/ERC1967Proxy.sol"; */ /* import {ERC1967Upgrade} from "openzeppelin-contracts/proxy/ERC1967/ERC1967Upgrade.sol"; */ /* import {StorageSlot} from "openzeppelin-contracts/utils/StorageSlot.sol"; */ /* import {DripsHub, SplitsReceiver} from "./DripsHub.sol"; */ /// @notice The DripsHub which is UUPS-upgradable, pausable and has an admin. /// It can't be used directly, only via a proxy. /// /// ManagedDripsHub uses the ERC-1967 admin slot to store the admin address. /// All instances of the contracts are owned by address `0x00`. /// While this contract is capable of updating the admin, /// the proxy is expected to set up the initial value of the ERC-1967 admin. /// /// All instances of the contracts are paused and can't be unpaused. /// When a proxy uses such contract via delegation, it's initially unpaused. abstract contract ManagedDripsHub is DripsHub, UUPSUpgradeable { /// @notice The ERC-1967 storage slot for the contract. /// It holds a single boolean indicating if the contract is paused. bytes32 private constant SLOT_PAUSED = bytes32(uint256(keccak256("eip1967.managedDripsHub.paused")) - 1); /// @notice Emitted when the pause is triggered. /// @param account The account which triggered the change. event Paused(address account); /// @notice Emitted when the pause is lifted. /// @param account The account which triggered the change. event Unpaused(address account); /// @notice Initializes the contract in paused state and with no admin. /// The contract instance can be used only as a call delegation target for a proxy. /// @param cycleSecs The length of cycleSecs to be used in the contract instance. /// Low value makes funds more available by shortening the average time of funds being frozen /// between being taken from the users' drips balances and being collectable by their receivers. /// High value makes collecting cheaper by making it process less cycles for a given time range. constructor(uint64 cycleSecs) DripsHub(cycleSecs) { _pausedSlot().value = true; } /// @notice Collects all received funds available for the user /// and transfers them out of the drips hub contract to that user's wallet. /// @param user The user /// @param currReceivers The list of the user's current splits receivers. /// @return collected The collected amount /// @return split The amount split to the user's splits receivers function collect(address user, SplitsReceiver[] memory currReceivers) public override whenNotPaused returns (uint128 collected, uint128 split) { return super.collect(user, currReceivers); } /// @notice Flushes uncollected cycles of the user. /// Flushed cycles won't need to be analyzed when the user collects from them. /// Calling this function does not collect and does not affect the collectable amount. /// /// This function is needed when collecting funds received over a period so long, that the gas /// needed for analyzing all the uncollected cycles can't fit in a single transaction. /// Calling this function allows spreading the analysis cost over multiple transactions. /// A cycle is never flushed more than once, even if this function is called many times. /// @param user The user /// @param maxCycles The maximum number of flushed cycles. /// If too low, flushing will be cheap, but will cut little gas from the next collection. /// If too high, flushing may become too expensive to fit in a single transaction. /// @return flushable The number of cycles which can be flushed function flushCycles(address user, uint64 maxCycles) public override whenNotPaused returns (uint64 flushable) { return super.flushCycles(user, maxCycles); } /// @notice Authorizes the contract upgrade. See `UUPSUpgradable` docs for more details. function _authorizeUpgrade(address newImplementation) internal view override onlyAdmin { newImplementation; } /// @notice Returns the address of the current admin. function admin() public view returns (address) { return _getAdmin(); } /// @notice Changes the admin of the contract. /// Can only be called by the current admin. function changeAdmin(address newAdmin) public onlyAdmin { _changeAdmin(newAdmin); } /// @notice Throws if called by any account other than the admin. modifier onlyAdmin() { require(admin() == msg.sender, "Caller is not the admin"); _; } /// @notice Returns true if the contract is paused, and false otherwise. function paused() public view returns (bool isPaused) { return _pausedSlot().value; } /// @notice Triggers stopped state. function pause() public whenNotPaused onlyAdmin { _pausedSlot().value = true; emit Paused(msg.sender); } /// @notice Returns to normal state. function unpause() public whenPaused onlyAdmin { _pausedSlot().value = false; emit Unpaused(msg.sender); } /// @notice Modifier to make a function callable only when the contract is not paused. modifier whenNotPaused() { require(!paused(), "Contract paused"); _; } /// @notice Modifier to make a function callable only when the contract is paused. modifier whenPaused() { require(paused(), "Contract not paused"); _; } /// @notice Gets the storage slot holding the paused flag. function _pausedSlot() private pure returns (StorageSlot.BooleanSlot storage) { return StorageSlot.getBooleanSlot(SLOT_PAUSED); } } /// @notice A generic ManagedDripsHub proxy. contract ManagedDripsHubProxy is ERC1967Proxy { constructor(ManagedDripsHub hubLogic, address admin) ERC1967Proxy(address(hubLogic), new bytes(0)) { _changeAdmin(admin); } } ////// lib/radicle-drips-hub/src/ERC20DripsHub.sol /* pragma solidity ^0.8.7; */ /* import {SplitsReceiver, DripsReceiver} from "./DripsHub.sol"; */ /* import {ManagedDripsHub} from "./ManagedDripsHub.sol"; */ /* import {IERC20Reserve} from "./ERC20Reserve.sol"; */ /* import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; */ /* import {StorageSlot} from "openzeppelin-contracts/utils/StorageSlot.sol"; */ /// @notice Drips hub contract for any ERC-20 token. Must be used via a proxy. /// See the base `DripsHub` and `ManagedDripsHub` contract docs for more details. contract ERC20DripsHub is ManagedDripsHub { /// @notice The ERC-1967 storage slot for the contract. /// It holds a single address of the ERC-20 reserve. bytes32 private constant SLOT_RESERVE = bytes32(uint256(keccak256("eip1967.erc20DripsHub.reserve")) - 1); /// @notice The address of the ERC-20 contract which tokens the drips hub works with IERC20 public immutable erc20; /// @notice Emitted when the reserve address is set event ReserveSet(IERC20Reserve oldReserve, IERC20Reserve newReserve); /// @param cycleSecs The length of cycleSecs to be used in the contract instance. /// Low value makes funds more available by shortening the average time of funds being frozen /// between being taken from the users' drips balances and being collectable by their receivers. /// High value makes collecting cheaper by making it process less cycles for a given time range. /// @param _erc20 The address of an ERC-20 contract which tokens the drips hub will work with. constructor(uint64 cycleSecs, IERC20 _erc20) ManagedDripsHub(cycleSecs) { erc20 = _erc20; } /// @notice Sets the drips configuration of the `msg.sender`. /// Transfers funds to or from the sender to fulfill the update of the drips balance. /// The sender must first grant the contract a sufficient allowance. /// @param lastUpdate The timestamp of the last drips update of the `msg.sender`. /// If this is the first update, pass zero. /// @param lastBalance The drips balance after the last drips update of the `msg.sender`. /// If this is the first update, pass zero. /// @param currReceivers The list of the drips receivers set in the last drips update /// of the `msg.sender`. /// If this is the first update, pass an empty array. /// @param balanceDelta The drips balance change to be applied. /// Positive to add funds to the drips balance, negative to remove them. /// @param newReceivers The list of the drips receivers of the `msg.sender` to be set. /// Must be sorted by the receivers' addresses, deduplicated and without 0 amtPerSecs. /// @return newBalance The new drips balance of the `msg.sender`. /// Pass it as `lastBalance` when updating that user or the account for the next time. /// @return realBalanceDelta The actually applied drips balance change. function setDrips( uint64 lastUpdate, uint128 lastBalance, DripsReceiver[] memory currReceivers, int128 balanceDelta, DripsReceiver[] memory newReceivers ) public whenNotPaused returns (uint128 newBalance, int128 realBalanceDelta) { return _setDrips( _userOrAccount(msg.sender), lastUpdate, lastBalance, currReceivers, balanceDelta, newReceivers ); } /// @notice Sets the drips configuration of an account of the `msg.sender`. /// See `setDrips` for more details /// @param account The account function setDrips( uint256 account, uint64 lastUpdate, uint128 lastBalance, DripsReceiver[] memory currReceivers, int128 balanceDelta, DripsReceiver[] memory newReceivers ) public whenNotPaused returns (uint128 newBalance, int128 realBalanceDelta) { return _setDrips( _userOrAccount(msg.sender, account), lastUpdate, lastBalance, currReceivers, balanceDelta, newReceivers ); } /// @notice Gives funds from the `msg.sender` to the receiver. /// The receiver can collect them immediately. /// Transfers the funds to be given from the sender's wallet to the drips hub contract. /// @param receiver The receiver /// @param amt The given amount function give(address receiver, uint128 amt) public whenNotPaused { _give(_userOrAccount(msg.sender), receiver, amt); } /// @notice Gives funds from the account of the `msg.sender` to the receiver. /// The receiver can collect them immediately. /// Transfers the funds to be given from the sender's wallet to the drips hub contract. /// @param account The account /// @param receiver The receiver /// @param amt The given amount function give( uint256 account, address receiver, uint128 amt ) public whenNotPaused { _give(_userOrAccount(msg.sender, account), receiver, amt); } /// @notice Collects funds received by the `msg.sender` and sets their splits. /// The collected funds are split according to `currReceivers`. /// @param currReceivers The list of the user's splits receivers which is currently in use. /// If this function is called for the first time for the user, should be an empty array. /// @param newReceivers The new list of the user's splits receivers. /// Must be sorted by the splits receivers' addresses, deduplicated and without 0 weights. /// Each splits receiver will be getting `weight / TOTAL_SPLITS_WEIGHT` /// share of the funds collected by the user. /// @return collected The collected amount /// @return split The amount split to the user's splits receivers function setSplits(SplitsReceiver[] memory currReceivers, SplitsReceiver[] memory newReceivers) public whenNotPaused returns (uint128 collected, uint128 split) { return _setSplits(msg.sender, currReceivers, newReceivers); } /// @notice Gets the the reserve where funds are stored. function reserve() public view returns (IERC20Reserve) { return IERC20Reserve(_reserveSlot().value); } /// @notice Set the new reserve address to store funds. /// @param newReserve The new reserve. function setReserve(IERC20Reserve newReserve) public onlyAdmin { require(newReserve.erc20() == erc20, "Invalid reserve ERC-20 address"); IERC20Reserve oldReserve = reserve(); if (address(oldReserve) != address(0)) erc20.approve(address(oldReserve), 0); _reserveSlot().value = address(newReserve); erc20.approve(address(newReserve), type(uint256).max); emit ReserveSet(oldReserve, newReserve); } function _reserveSlot() private pure returns (StorageSlot.AddressSlot storage) { return StorageSlot.getAddressSlot(SLOT_RESERVE); } function _transfer(address user, int128 amt) internal override { IERC20Reserve erc20Reserve = reserve(); require(address(erc20Reserve) != address(0), "Reserve unset"); if (amt > 0) { uint256 withdraw = uint128(amt); erc20Reserve.withdraw(withdraw); erc20.transfer(user, withdraw); } else if (amt < 0) { uint256 deposit = uint128(-amt); erc20.transferFrom(user, address(this), deposit); erc20Reserve.deposit(deposit); } } } ////// lib/radicle-drips-hub/src/DaiDripsHub.sol /* pragma solidity ^0.8.7; */ /* import {ERC20DripsHub, DripsReceiver, SplitsReceiver} from "./ERC20DripsHub.sol"; */ /* import {IDai} from "./Dai.sol"; */ /* import {IDaiReserve} from "./DaiReserve.sol"; */ struct PermitArgs { uint256 nonce; uint256 expiry; uint8 v; bytes32 r; bytes32 s; } /// @notice Drips hub contract for DAI token. Must be used via a proxy. /// See the base `DripsHub` contract docs for more details. contract DaiDripsHub is ERC20DripsHub { /// @notice The address of the Dai contract which tokens the drips hub works with. /// Always equal to `erc20`, but more strictly typed. IDai public immutable dai; /// @notice See `ERC20DripsHub` constructor documentation for more details. constructor(uint64 cycleSecs, IDai _dai) ERC20DripsHub(cycleSecs, _dai) { dai = _dai; } /// @notice Sets the drips configuration of the `msg.sender` /// and permits spending their Dai by the drips hub. /// This function is an extension of `setDrips`, see its documentation for more details. /// /// The user must sign a Dai permission document allowing the drips hub to spend their funds. /// These parameters will be passed to the Dai contract by this function. /// @param permitArgs The Dai permission arguments. function setDripsAndPermit( uint64 lastUpdate, uint128 lastBalance, DripsReceiver[] memory currReceivers, int128 balanceDelta, DripsReceiver[] memory newReceivers, PermitArgs calldata permitArgs ) public whenNotPaused returns (uint128 newBalance, int128 realBalanceDelta) { _permit(permitArgs); return setDrips(lastUpdate, lastBalance, currReceivers, balanceDelta, newReceivers); } /// @notice Sets the drips configuration of an account of the `msg.sender` /// and permits spending their Dai by the drips hub. /// This function is an extension of `setDrips`, see its documentation for more details. /// /// The user must sign a Dai permission document allowing the drips hub to spend their funds. /// These parameters will be passed to the Dai contract by this function. /// @param permitArgs The Dai permission arguments. function setDripsAndPermit( uint256 account, uint64 lastUpdate, uint128 lastBalance, DripsReceiver[] memory currReceivers, int128 balanceDelta, DripsReceiver[] memory newReceivers, PermitArgs calldata permitArgs ) public whenNotPaused returns (uint128 newBalance, int128 realBalanceDelta) { _permit(permitArgs); return setDrips(account, lastUpdate, lastBalance, currReceivers, balanceDelta, newReceivers); } /// @notice Gives funds from the `msg.sender` to the receiver /// and permits spending sender's Dai by the drips hub. /// This function is an extension of `give`, see its documentation for more details. /// /// The user must sign a Dai permission document allowing the drips hub to spend their funds. /// These parameters will be passed to the Dai contract by this function. /// @param permitArgs The Dai permission arguments. function giveAndPermit( address receiver, uint128 amt, PermitArgs calldata permitArgs ) public whenNotPaused { _permit(permitArgs); give(receiver, amt); } /// @notice Gives funds from the account of the `msg.sender` to the receiver /// and permits spending sender's Dai by the drips hub. /// This function is an extension of `give` see its documentation for more details. /// /// The user must sign a Dai permission document allowing the drips hub to spend their funds. /// These parameters will be passed to the Dai contract by this function. /// @param permitArgs The Dai permission arguments. function giveAndPermit( uint256 account, address receiver, uint128 amt, PermitArgs calldata permitArgs ) public whenNotPaused { _permit(permitArgs); give(account, receiver, amt); } /// @notice Permits the drips hub to spend the message sender's Dai. /// @param permitArgs The Dai permission arguments. function _permit(PermitArgs calldata permitArgs) internal { dai.permit( msg.sender, address(this), permitArgs.nonce, permitArgs.expiry, true, permitArgs.v, permitArgs.r, permitArgs.s ); } } ////// src/builder/interface.sol /* pragma solidity ^0.8.7; */ interface IBuilder { function buildMetaData( string memory projectName, uint128 tokenId, uint128 nftType, bool streaming, uint128 amtPerCycle, bool active ) external view returns (string memory); function buildMetaData( string memory projectName, uint128 tokenId, uint128 nftType, bool streaming, uint128 amtPerCycle, bool active, string memory ipfsHash ) external view returns (string memory); } ////// src/token.sol /* pragma solidity ^0.8.7; */ /* import {ERC721} from "openzeppelin-contracts/token/ERC721/ERC721.sol"; */ /* import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol"; */ /* import {Ownable} from "openzeppelin-contracts/access/Ownable.sol"; */ /* import {DaiDripsHub, DripsReceiver, IDai, SplitsReceiver} from "drips-hub/DaiDripsHub.sol"; */ /* import {IBuilder} from "./builder/interface.sol"; */ struct InputType { uint128 nftTypeId; uint64 limit; // minimum amtPerSecond or minGiveAmt uint128 minAmt; bool streaming; string ipfsHash; } interface IDripsToken { function init( string calldata name_, string calldata symbol_, address owner, string calldata contractURI_, InputType[] memory inputTypes, IBuilder builder_, SplitsReceiver[] memory splits ) external; } contract DripsToken is ERC721, Ownable, IDripsToken { address public immutable deployer; DaiDripsHub public immutable hub; IDai public immutable dai; uint64 public immutable cycleSecs; IBuilder public builder; string internal _name; string internal _symbol; string public contractURI; bool public initialized; struct Type { uint64 limit; uint64 minted; uint128 minAmt; bool streaming; string ipfsHash; } struct Token { uint64 timeMinted; // amtPerSec if the Token is streaming otherwise the amt given at mint uint128 amt; uint128 lastBalance; uint64 lastUpdate; } mapping(uint128 => Type) public nftTypes; mapping(uint256 => Token) public nfts; // events event NewType( uint128 indexed nftType, uint64 limit, uint128 minAmt, bool streaming, string ipfsHash ); event NewStreamingToken( uint256 indexed tokenId, address indexed receiver, uint128 indexed typeId, uint128 topUp, uint128 amtPerSec ); event NewToken( uint256 indexed tokenId, address indexed receiver, uint128 indexed typeId, uint128 giveAmt ); event NewContractURI(string contractURI); event NewBuilder(IBuilder builder); event SplitsUpdated(SplitsReceiver[] splits); constructor(DaiDripsHub hub_, address deployer_) ERC721("", "") { deployer = deployer_; hub = hub_; dai = hub_.dai(); cycleSecs = hub_.cycleSecs(); } modifier onlyTokenHolder(uint256 tokenId) { require(ownerOf(tokenId) == msg.sender, "not-nft-owner"); _; } function init( string calldata name_, string calldata symbol_, address owner, string calldata contractURI_, InputType[] memory inputTypes, IBuilder builder_, SplitsReceiver[] memory splits ) public override { require(!initialized, "already-initialized"); initialized = true; require(msg.sender == deployer, "not-deployer"); require(owner != address(0), "owner-address-is-zero"); _name = name_; _symbol = symbol_; _changeBuilder(builder_); _addTypes(inputTypes); _changeContractURI(contractURI_); _transferOwnership(owner); if (splits.length > 0) { _changeSplitsReceivers(new SplitsReceiver[](0), splits); } dai.approve(address(hub), type(uint256).max); } function changeContractURI(string calldata contractURI_) public onlyOwner { _changeContractURI(contractURI_); } function _changeContractURI(string calldata contractURI_) internal { contractURI = contractURI_; emit NewContractURI(contractURI_); } function _changeBuilder(IBuilder newBuilder) internal { builder = newBuilder; emit NewBuilder(newBuilder); } function addTypes(InputType[] memory inputTypes) public onlyOwner { _addTypes(inputTypes); } function _addTypes(InputType[] memory inputTypes) internal { for (uint256 i = 0; i < inputTypes.length; i++) { _addType( inputTypes[i].nftTypeId, inputTypes[i].limit, inputTypes[i].minAmt, inputTypes[i].ipfsHash, inputTypes[i].streaming ); } } function addStreamingType( uint128 newTypeId, uint64 limit, uint128 minAmtPerSec, string memory ipfsHash ) public onlyOwner { _addType(newTypeId, limit, minAmtPerSec, ipfsHash, true); } function addType( uint128 newTypeId, uint64 limit, uint128 minGiveAmt, string memory ipfsHash ) public onlyOwner { _addType(newTypeId, limit, minGiveAmt, ipfsHash, false); } function _addType( uint128 newTypeId, uint64 limit, uint128 minAmt, string memory ipfsHash, bool streaming_ ) internal { require(nftTypes[newTypeId].limit == 0, "nft-type-already-exists"); require(limit > 0, "zero-limit-not-allowed"); nftTypes[newTypeId].minAmt = minAmt; nftTypes[newTypeId].limit = limit; nftTypes[newTypeId].ipfsHash = ipfsHash; nftTypes[newTypeId].streaming = streaming_; emit NewType(newTypeId, limit, minAmt, streaming_, ipfsHash); } function createTokenId(uint128 id, uint128 nftType) public pure returns (uint256 tokenId) { return uint256((uint256(nftType) << 128)) | id; } function tokenType(uint256 tokenId) public pure returns (uint128 nftType) { return uint128(tokenId >> 128); } function mintStreaming( address nftReceiver, uint128 typeId, uint128 topUpAmt, uint128 amtPerSec, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external returns (uint256) { dai.permit(msg.sender, address(this), nonce, expiry, true, v, r, s); return mintStreaming(nftReceiver, typeId, topUpAmt, amtPerSec); } function mint( address nftReceiver, uint128 typeId, uint128 amtGive, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external returns (uint256) { dai.permit(msg.sender, address(this), nonce, expiry, true, v, r, s); return mint(nftReceiver, typeId, amtGive); } function mint( address nftReceiver, uint128 typeId, uint128 giveAmt ) public returns (uint256 newTokenId) { require(giveAmt >= nftTypes[typeId].minAmt, "giveAmt-too-low"); require(nftTypes[typeId].streaming == false, "type-is-streaming"); newTokenId = _mintInternal(nftReceiver, typeId, giveAmt); // one time give instead of streaming hub.give(newTokenId, address(this), giveAmt); nfts[newTokenId].amt = giveAmt; emit NewToken(newTokenId, nftReceiver, typeId, giveAmt); } function authMint( address nftReceiver, uint128 typeId, uint128 value ) public onlyOwner returns (uint256 newTokenId) { require(nftTypes[typeId].streaming == false, "type-is-streaming"); newTokenId = _mintInternal(nftReceiver, typeId, 0); // amt is needed for influence nfts[newTokenId].amt = value; emit NewToken(newTokenId, nftReceiver, typeId, 0); } function _mintInternal( address nftReceiver, uint128 typeId, uint128 topUpAmt ) internal returns (uint256 newTokenId) { require(nftTypes[typeId].minted++ < nftTypes[typeId].limit, "nft-type-reached-limit"); newTokenId = createTokenId(nftTypes[typeId].minted, typeId); _mint(nftReceiver, newTokenId); nfts[newTokenId].timeMinted = uint64(block.timestamp); // transfer currency to Token registry if (topUpAmt > 0) dai.transferFrom(nftReceiver, address(this), topUpAmt); } function mintStreaming( address nftReceiver, uint128 typeId, uint128 topUpAmt, uint128 amtPerSec ) public returns (uint256 newTokenId) { require(amtPerSec >= nftTypes[typeId].minAmt, "amt-per-sec-too-low"); require(nftTypes[typeId].streaming, "nft-type-not-streaming"); require(topUpAmt >= amtPerSec * cycleSecs, "toUp-too-low"); newTokenId = _mintInternal(nftReceiver, typeId, topUpAmt); // start streaming hub.setDrips(newTokenId, 0, 0, _receivers(0), int128(topUpAmt), _receivers(amtPerSec)); nfts[newTokenId].amt = amtPerSec; nfts[newTokenId].lastUpdate = uint64(block.timestamp); nfts[newTokenId].lastBalance = topUpAmt; emit NewStreamingToken(newTokenId, nftReceiver, typeId, topUpAmt, amtPerSec); } function collect(SplitsReceiver[] calldata currSplits) public onlyOwner returns (uint128 collected, uint128 split) { (, split) = hub.collect(address(this), currSplits); collected = uint128(dai.balanceOf(address(this))); dai.transfer(owner(), collected); } function collectable(SplitsReceiver[] calldata currSplits) public view returns (uint128 toCollect, uint128 toSplit) { (toCollect, toSplit) = hub.collectable(address(this), currSplits); toCollect += uint128(dai.balanceOf(address(this))); } function topUp( uint256 tokenId, uint128 topUpAmt, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { dai.permit(msg.sender, address(this), nonce, expiry, true, v, r, s); topUp(tokenId, topUpAmt); } function topUp(uint256 tokenId, uint128 topUpAmt) public onlyTokenHolder(tokenId) { require(nftTypes[tokenType(tokenId)].streaming, "not-a-streaming-nft"); dai.transferFrom(msg.sender, address(this), topUpAmt); DripsReceiver[] memory receivers = _tokenReceivers(tokenId); (uint128 newBalance, ) = hub.setDrips( tokenId, nfts[tokenId].lastUpdate, nfts[tokenId].lastBalance, receivers, int128(topUpAmt), receivers ); nfts[tokenId].lastUpdate = uint64(block.timestamp); nfts[tokenId].lastBalance = newBalance; } function withdraw(uint256 tokenId, uint128 withdrawAmt) public onlyTokenHolder(tokenId) returns (uint128 withdrawn) { uint128 withdrawableAmt = withdrawable(tokenId); if (withdrawAmt > withdrawableAmt) { withdrawAmt = withdrawableAmt; } DripsReceiver[] memory receivers = _tokenReceivers(tokenId); (uint128 newBalance, int128 realBalanceDelta) = hub.setDrips( tokenId, nfts[tokenId].lastUpdate, nfts[tokenId].lastBalance, receivers, -int128(withdrawAmt), receivers ); nfts[tokenId].lastUpdate = uint64(block.timestamp); nfts[tokenId].lastBalance = newBalance; withdrawn = uint128(-realBalanceDelta); dai.transfer(msg.sender, withdrawn); } function changeSplitsReceivers( SplitsReceiver[] memory currSplits, SplitsReceiver[] memory newSplits ) public onlyOwner { _changeSplitsReceivers(currSplits, newSplits); } function _changeSplitsReceivers( SplitsReceiver[] memory currSplits, SplitsReceiver[] memory newSplits ) internal { hub.setSplits(currSplits, newSplits); emit SplitsUpdated(newSplits); } function withdrawable(uint256 tokenId) public view returns (uint128) { require(_exists(tokenId), "nonexistent-token"); if (nftTypes[tokenType(tokenId)].streaming == false) return 0; Token storage nft = nfts[tokenId]; uint64 spentUntil = uint64(block.timestamp); uint64 minSpentUntil = nft.timeMinted + cycleSecs; if (spentUntil < minSpentUntil) spentUntil = minSpentUntil; uint192 spent = (spentUntil - nft.lastUpdate) * uint192(nft.amt); if (nft.lastBalance < spent) return nft.lastBalance % nft.amt; return nft.lastBalance - uint128(spent); } function activeUntil(uint256 tokenId) public view returns (uint128) { require(_exists(tokenId), "nonexistent-token"); Type storage nftType = nftTypes[tokenType(tokenId)]; if (nftType.streaming == false || nftType.minAmt == 0) { return type(uint128).max; } Token storage nft = nfts[tokenId]; return nft.lastUpdate + nft.lastBalance / nft.amt - 1; } function active(uint256 tokenId) public view returns (bool) { return activeUntil(tokenId) >= block.timestamp; } function streaming(uint256 tokenId) public view returns (bool) { return nftTypes[tokenType(tokenId)].streaming; } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function changeBuilder(IBuilder newBuilder) public onlyOwner { _changeBuilder(newBuilder); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "nonexistent-token"); string memory ipfsHash = nftTypes[tokenType(tokenId)].ipfsHash; uint128 amtPerCycle = nfts[tokenId].amt * cycleSecs; if (bytes(ipfsHash).length == 0) { return builder.buildMetaData( name(), uint128(tokenId), tokenType(tokenId), nftTypes[tokenType(tokenId)].streaming, amtPerCycle, active(tokenId) ); } return builder.buildMetaData( name(), uint128(tokenId), tokenType(tokenId), nftTypes[tokenType(tokenId)].streaming, amtPerCycle, active(tokenId), ipfsHash ); } function currLeftSecsInCycle() public view returns (uint64) { return cycleSecs - (uint64(block.timestamp) % cycleSecs); } function influence(uint256 tokenId) public view returns (uint256 influenceScore) { if (active(tokenId)) { if (streaming(tokenId) == false) { return nfts[tokenId].amt; } return nfts[tokenId].amt * (block.timestamp - nfts[tokenId].timeMinted); } return 0; } function _tokenReceivers(uint256 tokenId) internal view returns (DripsReceiver[] memory receivers) { return _receivers(nfts[tokenId].amt); } function _receivers(uint128 amtPerSec) internal view returns (DripsReceiver[] memory receivers) { if (amtPerSec == 0) return new DripsReceiver[](0); receivers = new DripsReceiver[](1); receivers[0] = DripsReceiver(address(this), amtPerSec); } }
Collects all received funds available for the user and transfers them out of the drips hub contract to that user's wallet. user The user currReceivers The list of the user's current splits receivers. return collected The collected amount return split The amount split to the user's splits receivers
function collect(address user, SplitsReceiver[] memory currReceivers) public virtual returns (uint128 collected, uint128 split) { (collected, split) = _collectInternal(user, currReceivers); _transfer(user, int128(collected)); }
13,437,379
pragma solidity 0.4.24; import "./interfaces/ApprovedRegistryInterface.sol"; import "./interfaces/KyberNetworkInterface.sol"; import "./interfaces/BillableInterface.sol"; import "./WETH.sol"; import "./base/math/SafeMath.sol"; import "./base/ownership/Ownable.sol"; /** @title Approved contract, tokens and gas prices. */ /** @author Kerman Kohli - <[email protected]> */ contract ApprovedRegistry is ApprovedRegistryInterface, Ownable { using SafeMath for uint256; mapping (address => uint256) public approvedTokenMapping; // Exchange rate cache (in case Kyber is down). mapping (address => bool) public approvedContractMapping; KyberNetworkInterface public kyberProxy; WETH public wrappedEther; address[] public approvedContractArray; address[] public approvedTokenArray; event ContractAdded(address indexed target); event ContractRemoved(address indexed target); event TokenAdded(address indexed target); event TokenRemoved(address indexed target); event CachedPriceOverwritten(address indexed token, uint256 indexed price); /** * MODIFIERS */ modifier hasContractBeenApproved(address _contractAddress, bool _expectedResult) { require(isContractAuthorised(_contractAddress) == _expectedResult, "The contract should be authorised"); _; } modifier hasTokenBeenApproved(address _tokenAddress, bool _expectedResult) { require(isTokenAuthorised(_tokenAddress) == _expectedResult, "The token should be authorised"); _; } /** * PUBLIC FUNCTIONS */ /** @dev Set the addresses for the relevant contracts * @param _kyberAddress the address for the kyber network contract. */ constructor(address _kyberAddress) public { // @TODO: Figure out how to add tests for this kyberProxy = KyberNetworkInterface(_kyberAddress); } /** @dev Get exchange rate for token. * @param _tokenAddress is the address for the token. */ function getRateFor(address _tokenAddress) public view returns (uint256) { // If the token is the native currency, then the exchange rate is 1 if (_tokenAddress == address(wrappedEther)) { return 1*10**18; } var (, rate) = kyberProxy.getExpectedRate( ERC20(_tokenAddress), ERC20(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee), 10**18 ); if (rate > 0) { approvedTokenMapping[_tokenAddress] = rate; return rate; } // Gas spike hence return cached value uint256 cachedRate = approvedTokenMapping[_tokenAddress]; if (cachedRate == 0) { // Fail safe in case Kyber gives 0 cachedRate = 66*10**14; } return cachedRate; } /** @dev Add an approved subscription contract to be used. * @param _contractAddress is the address of the subscription contract. */ function addApprovedContract(address _contractAddress) public onlyOwner hasContractBeenApproved(_contractAddress, false) { approvedContractArray.push(_contractAddress); emit ContractAdded(_contractAddress); } /** @dev Add an approved token to be used. * @param _tokenAddress is the address of the token to be used. */ function addApprovedToken(address _tokenAddress, bool _isWETH) public onlyOwner hasTokenBeenApproved(_tokenAddress, false) { approvedTokenArray.push(_tokenAddress); if (_isWETH == true && address(wrappedEther) == address(0)) { wrappedEther = WETH(_tokenAddress); } emit TokenAdded(_tokenAddress); } /** @dev Remove an approved subscription contract. * @param _contractAddress is the address of the subscription contract. */ function removeApprovedContract(address _contractAddress) public onlyOwner { for (uint256 i = 0; i < approvedContractArray.length; i++) { if (approvedContractArray[i] == _contractAddress) { approvedContractArray[i] = approvedContractArray[approvedContractArray.length - 1]; approvedContractArray.length--; approvedContractMapping[_contractAddress] = false; emit ContractRemoved(_contractAddress); break; } } } /** @dev Remove an approved token to be used. * @param _tokenAddress is the address of the token to remove. */ function removeApprovedToken(address _tokenAddress) public onlyOwner { for (uint256 i = 0; i < approvedTokenArray.length; i++) { if (approvedTokenArray[i] == _tokenAddress) { approvedTokenArray[i] = approvedTokenArray[approvedTokenArray.length - 1]; approvedTokenArray.length--; approvedTokenMapping[_tokenAddress] = 0; emit TokenRemoved(_tokenAddress); break; } } if (_tokenAddress == address(wrappedEther)) { delete wrappedEther; } } /** @dev Get approved contract array. */ function getApprovedContracts() public view returns (address[]) { return approvedContractArray; } /** @dev Get approved token array. */ function getApprovedTokens() public view returns (address[]) { return approvedTokenArray; } /** @dev Check if a subscription has been authorised. * @param _contractAddress is the address of the contract. */ function isContractAuthorised(address _contractAddress) public returns (bool) { require(_contractAddress != 0, "A valid contract was not passed"); bool contractFoundInRegistry = false; for (uint256 i = 0; i < approvedContractArray.length; i++) { if (approvedContractArray[i] == _contractAddress) { contractFoundInRegistry = true; break; } } return contractFoundInRegistry; } /** @dev Check if a token has been authorised. * @param _tokenAddress is the address of the token. */ function isTokenAuthorised(address _tokenAddress) public returns (bool) { require(_tokenAddress != 0, "An empty token address was passed"); bool tokenFoundInRegistry = false; for (uint256 i = 0; i < approvedTokenArray.length; i++) { if (approvedTokenArray[i] == _tokenAddress) { tokenFoundInRegistry = true; break; } } return tokenFoundInRegistry; } /** @dev Check if the token is a wrapped asset. * @param _tokenAddress is the address of the token. */ function isTokenWrapped(address _tokenAddress) public returns (bool) { require(_tokenAddress != 0, "An empty token address was passed"); return address(_tokenAddress) == address(wrappedEther); } /** @dev Force overwrite the cached price * @param _tokenAddress to set for * @param _price to set for */ function forceUpdateCachedPrice(address _tokenAddress, uint256 _price) public onlyOwner { approvedTokenMapping[_tokenAddress] = _price; emit CachedPriceOverwritten(_tokenAddress, _price); } }
Get exchange rate for token. _tokenAddress is the address for the token./ If the token is the native currency, then the exchange rate is 1 Fail safe in case Kyber gives 0
function getRateFor(address _tokenAddress) public view returns (uint256) { if (_tokenAddress == address(wrappedEther)) { return 1*10**18; } var (, rate) = kyberProxy.getExpectedRate( ERC20(_tokenAddress), ERC20(0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee), 10**18 ); if (rate > 0) { approvedTokenMapping[_tokenAddress] = rate; return rate; } if (cachedRate == 0) { cachedRate = 66*10**14; } return cachedRate; }
14,020,366
./full_match/8453/0xe00d28787E7fd5ba420049C6Aec160a5Beb02fe1/sources/contracts/Ledger.sol
getContextArnAllocations After looking at the aggregate arn balance sheet for say, a trust or key context, you'll want to see an allocation across both providers and their collateral balances for a given asset. 'OK I see Chainlink, what is that composed of?' 'Who can withdrawal it?'. When done at the ledger level, is essentially a "TVL" measurement of a given ARN for the entire ledger. At the trust level, it shows a provider-based porfolio allocation for a given asset. At the key level, it represents withdrawal rights. context LEDGER_CONTEXT_ID, TRUST_CONTEXT_ID, KEY_CONTEXT_ID identifier either 0, a trustId, or keyId depending on context. arn the asset you want to inspect.i return an array of providers for the given asset return an array of their respective balances for the asset./
function getContextArnAllocations(uint256 context, uint256 identifier, bytes32 arn) external view returns(address[] memory, uint256[] memory) { CollateralProviderLedger.CollateralProviderContext storage cxt = getContextLedger(context, identifier); return cxt.getProvidersAndArnBalances(arn); }
11,559,706
./full_match/97/0xe9E19bc8EE05502620610517E32f98eEb653600E/sources/project_/contracts/BetDex.sol
return _validateAuthorization(hash, input.v, input.r, input.s, input.signatureVersion, input.extraSignature);
function _validateSignatures(Input calldata input, bytes32 hash) internal view returns (bool) { require( (input.timestamp - SIGNATURE_TIMESTAMP_THRESHOLD) < block.timestamp, "INVALID_TIMESTAMP" ); return _validateAuthorization(hash, input.v, input.r, input.s); }
3,290,377
./full_match/4/0xB62652A9f4ac3D85F09dA08F31963108Dd2BfD23/sources/contracts/OptionMarketPricer.sol
The entry point for the OptionMarket into the pricing logic when a trade is performed. listing The OptionListing. trade The Trade. pricingGlobals The PricingGlobals. boardBaseIv The base IV of the OptionBoard./
function updateCacheAndGetTotalCost( IOptionMarket.OptionListing memory listing, IOptionMarket.Trade memory trade, ILyraGlobals.PricingGlobals memory pricingGlobals, uint boardBaseIv ) external override onlyOptionMarket returns ( uint totalCost, uint newBaseIv, uint newSkew ) { (newBaseIv, newSkew) = ivImpactForTrade(listing, trade, pricingGlobals, boardBaseIv); trade.vol = newBaseIv.multiplyDecimal(newSkew); require(trade.vol >= pricingGlobals.volatilityCutoff, "vol out of trading range"); Pricing memory pricing = greekCache.updateListingCacheAndGetPrice( ILyraGlobals.GreekCacheGlobals(pricingGlobals.rateAndCarry, pricingGlobals.spotPrice), listing.id, int(listing.longCall).sub(int(listing.shortCall)), int(listing.longPut).sub(int(listing.shortPut)), newBaseIv, newSkew ); require( pricing.callDelta >= pricingGlobals.minDelta && pricing.callDelta <= (int(SafeDecimalMath.UNIT).sub(pricingGlobals.minDelta)), "delta out of trading range" ); totalCost = getPremium(trade, pricing, pricingGlobals); }
12,434,392
/** * @title Funding Vault * @author Clément Lesaege - <[email protected]> * Bug Bounties: This code hasn't undertaken a bug bounty program yet. */ pragma solidity ^0.4.15; import "../Arbitrable.sol"; import "minimetoken/contracts/MiniMeToken.sol"; /** @title Funding Vault * A contract storing the ETH raised in a crowdfunding event. * Funds are delivered when milestones are reached. * The team can claim a milestone is reached. Token holders will have some time to dispute that claim. * When some token holders vote to dispute the claim, extra time is given to other token holders to dispute that claim. * If a sufficient amount of token holders dispute it. A dispute is created and the arbitrator will decide if the milestone has been reached. * When there is a disagreement a vote token is created. Holders should send the voteToken to the Vault to disagree with the milestone. * Token holders can also claim that the team failed to deliver and ask for the remaining ETH to be given back to a different contract. * This contract can be the vault of another team, or a contract to reimburse. */ contract FundingVault is Arbitrable { address public team; MiniMeToken public token; address public funder; uint public disputeThreshold; uint public claimToWithdrawTime; uint public additionalTimeToWithdraw; uint public timeout; struct Milestone { uint amount; // The maximum amount which can be unlocked for this milestone. uint amountClaimed; // The current amount which is claimed. uint claimTime; // The time the current claim was made. Or 0 if it's not currently claimed. bool disputed; // True if a dispute has been raised. uint feeTeam; // Arbitration fee paid by the team. uint feeHolders; // Arbitration fee paid by token holders. MiniMeToken voteToken; // Forked token which will be used to vote. uint disputeID; // ID of the dispute if this claim is disputed. uint lastTotalFeePayment; // Time of the last total fee payment, useful for timeouts. bool lastTotalFeePaymentIsTeam; // True if the last interaction is from the team. address payerForHolders; // The address who first paid the arbitration fee and will be refunded in case of victory. } Milestone[] public milestones; mapping(uint => uint) public disputeIDToMilstoneID; // Map (disputeID => milestoneID). uint ousterID; //The ID of the milestone created at construction. To be disputed when the funders claim the team is not doing their job. bool canChangeTeam; //True if the holders have attempted an oust and won the dispute. Allows the funder to select a new team (only once). uint8 constant AMOUNT_OF_CHOICES = 2; uint8 constant TEAM_WINS = 1; uint8 constant HOLDERS_WINS = 2; /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _contractHash Keccak256 hash of the plain text contract. * @param _team The address of the team who will be able to claim milestone completion. * @param _token The token whose holders are able to dispute milestone claims. * @param _funder The party putting funds in the vault. * @param _disputeThreshold The ‱ of tokens required to dispute a milestone. * @param _claimToWithdrawTime The base time in seconds after a claim is considered non-disputed (i.e if no token holders dispute it). * @param _additionalTimeToWithdraw The time in seconds which is added per ‱ of tokens disputing the claim. * @param _timeout Maximum time to pay arbitration fees after the other side did. */ constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData, bytes32 _contractHash, address _team, address _token, address _funder, uint _disputeThreshold, uint _claimToWithdrawTime, uint _additionalTimeToWithdraw, uint _timeout) public Arbitrable(_arbitrator,_arbitratorExtraData,_contractHash) { team=_team; token=MiniMeToken(_token); funder=_funder; disputeThreshold=_disputeThreshold; claimToWithdrawTime=_claimToWithdrawTime; additionalTimeToWithdraw=_additionalTimeToWithdraw; timeout=_timeout; ousterID = milestones.push(Milestone({ //Create a base milestone to be disputed when the funders claim the team is not doing their job. amount:0, amountClaimed:0, claimTime:0, disputed:false, feeTeam:0, feeHolders:0, voteToken:MiniMeToken(0x0), disputeID:0, lastTotalFeePayment:0, lastTotalFeePaymentIsTeam:false, payerForHolders:0x0 }))-1; canChangeTeam = false; } /** @dev Give the funds for a milestone. * @return milestoneID The ID of the milestone which was created. */ function fundMilestone() public payable returns(uint milestoneID) { require(msg.sender==funder); return milestones.push(Milestone({ amount:msg.value, amountClaimed:0, claimTime:0, disputed:false, feeTeam:0, feeHolders:0, voteToken:MiniMeToken(0x0), disputeID:0, lastTotalFeePayment:0, lastTotalFeePaymentIsTeam:false, payerForHolders:0x0 }))-1; } //Restricts Milestone function with functionality not necessary for Ouster. modifier isNotOuster(uint _milestoneID) { require(ousterID != _milestoneID); _; } /** @dev Claim funds of a milestone. * @param _milestoneID The ID of the milestone. * @param _amount The amount claim. Note that the team can claim less than the amount of a milestone. This allows partial completion claims. */ function claimMilestone(uint _milestoneID, uint _amount) public isNotOuster(_milestoneID) { Milestone storage milestone=milestones[_milestoneID]; require(msg.sender==team); require(milestone.claimTime==0); // Verify another claim is not active. require(milestone.amount<=_amount); milestone.claimTime=now; } /** @dev Make a forked token to dispute a claim. * This avoid creating a token all the time, since most milestones should not be disputed. * @param _milestoneID The ID of the milestone. */ function makeVoteToken(uint _milestoneID) public { Milestone storage milestone=milestones[_milestoneID]; if( ousterID != _milestoneID ) { require(milestone.claimTime!=0); } // The milestone is currently claimed by the team, unless this is the ouster. require(address(milestone.voteToken)==0x0); // Token has not already been made. milestone.voteToken=MiniMeToken(token.createCloneToken( "", token.decimals(), "", block.number, true )); } /** @dev Pay fee to dispute a milestone. To be called by parties claiming the milestone was not completed. * The first party to pay the fee entirely will be reimbursed if the dispute is won. * Note that holders can make a smart contract to crowdfund the fee. * In the rare event the arbitrationCost is increased, anyone can pay the extra, but it is always the first payer who can be reimbursed. * @param _milestoneID The milestone which is disputed. */ function payDisputeFeeByHolders(uint _milestoneID) public payable { Milestone storage milestone=milestones[_milestoneID]; uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); require(!milestone.disputed); // The milestone is not already disputed. require(milestone.voteToken.balanceOf(this) >= (disputeThreshold*milestone.voteToken.totalSupply())/1000); // There is enough votes. require(milestone.feeHolders<arbitrationCost); // Fee has not be paid before. require(milestone.feeHolders+msg.value>=arbitrationCost); // Enough is paid. milestone.feeHolders+=msg.value; if (milestone.payerForHolders==0x0) milestone.payerForHolders=msg.sender; if (milestone.feeTeam>=arbitrationCost) { // Enough has been paid by all sides. createDispute(_milestoneID,arbitrationCost); } else if (milestone.lastTotalFeePayment==0) { // First time the fee is paid. milestone.lastTotalFeePayment=now; } else if(milestone.lastTotalFeePaymentIsTeam) { // The team was the last one who had paid entirely. milestone.lastTotalFeePaymentIsTeam=false; milestone.lastTotalFeePayment=now; } } /** @dev Pay fee to for a milestone dispute. To be called by the team when the holders have enough votes and fee paid. * @param _milestoneID The milestone which is disputed. */ function payDisputeFeeByTeam(uint _milestoneID) public payable { Milestone storage milestone=milestones[_milestoneID]; uint arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); require(msg.sender==team); require(!milestone.disputed); // A dispute has not been created yet. require(milestone.voteToken.balanceOf(this) >= (disputeThreshold*milestone.voteToken.totalSupply())/1000); // There is enough votes. require(milestone.feeTeam+msg.value>=arbitrationCost); // Make sure enough is paid. Team can't pay partially. milestone.feeTeam+=msg.value; if (milestone.feeHolders>=arbitrationCost) { // Enough has been paid by all sides. createDispute(_milestoneID,arbitrationCost); } else if (milestone.lastTotalFeePayment==0) { // First time the fee is paid. milestone.lastTotalFeePayment=now; milestone.lastTotalFeePaymentIsTeam=true; } else if(!milestone.lastTotalFeePaymentIsTeam) { // The holders were the last ones who had paid entirely. milestone.lastTotalFeePaymentIsTeam=true; milestone.lastTotalFeePayment=now; } } /** @dev Create a dispute. * @param _milestoneID The milestone which is disputed. * @param _arbitrationCost The amount which should be paid to the arbitrator. */ function createDispute(uint _milestoneID, uint _arbitrationCost) internal { Milestone storage milestone=milestones[_milestoneID]; milestone.disputed=true; milestone.feeTeam-=_arbitrationCost; // Remove the fee from the team pool for accounting. Note that at this point it does not matter which fee variable we decrement. milestone.disputeID=arbitrator.createDispute(AMOUNT_OF_CHOICES,arbitratorExtraData); disputeIDToMilstoneID[milestone.disputeID]=_milestoneID; } /** @dev Withdraw the money claimed in a milestone. * To be called when a dispute has not been created within the time limit. * @param _milestoneID The milestone which is disputed. */ function withdraw(uint _milestoneID) public isNotOuster(_milestoneID) { Milestone storage milestone=milestones[_milestoneID]; require(msg.sender==team); require(!milestone.disputed); require(milestone.voteToken.balanceOf(this) < (disputeThreshold*milestone.voteToken.totalSupply())/1000); // There is not enough votes. require((now-milestone.claimTime) > claimToWithdrawTime+(additionalTimeToWithdraw*milestone.voteToken.balanceOf(this))/(1000*milestone.voteToken.totalSupply())); team.transfer(milestone.amountClaimed+milestone.feeTeam+milestone.feeHolders); // Pay the amount claimed and the unused fees. milestone.amount-=milestone.amountClaimed; milestone.amountClaimed=0; milestone.claimTime=0; milestone.feeTeam=0; milestone.feeHolders=0; } // TODO: Timeouts /** @dev Timeout to use when the holders don't pay the fee. * @param _milestoneID The milestone which is disputed. */ function timeoutByTeam(uint _milestoneID) public { Milestone storage milestone=milestones[_milestoneID]; require(msg.sender==team); require(milestone.lastTotalFeePaymentIsTeam); require(now-milestone.lastTotalFeePayment > timeout); team.transfer(milestone.amountClaimed+milestone.feeTeam+milestone.feeHolders); // Pay the amount claimed and the unused fees to the team. milestone.amount-=milestone.amountClaimed; milestone.amountClaimed=0; milestone.claimTime=0; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.lastTotalFeePayment=0; milestone.lastTotalFeePaymentIsTeam=false; milestone.payerForHolders=0x0; } /** @dev Timeout to use whe the team don't pay the fee. * @param _milestoneID The milestone which is disputed. */ function timeoutByHolders(uint _milestoneID) public { Milestone storage milestone=milestones[_milestoneID]; require(!milestone.lastTotalFeePaymentIsTeam); require(now-milestone.lastTotalFeePayment > timeout); milestone.payerForHolders.transfer(milestone.feeTeam+milestone.feeHolders); // Pay the unused fees to the payer for holders. milestone.amountClaimed=0; milestone.claimTime=0; milestone.disputed=false; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.lastTotalFeePayment=0; milestone.payerForHolders=0x0; canChangeTeam = true; //since the team was nonresponsive, the holders are free to change the team. } /** @dev Appeal an appealable ruling. * Transfer the funds to the arbitrator. * @param _milestoneID The milestone which is disputed. */ function appeal(uint _milestoneID) public payable { Milestone storage milestone=milestones[_milestoneID]; arbitrator.appeal.value(msg.value)(milestone.disputeID,arbitratorExtraData); } /** @dev Execute a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal{ Milestone storage milestone=milestones[disputeIDToMilstoneID[_disputeID]]; require(milestone.voteToken.balanceOf(this) >= (disputeThreshold*milestone.voteToken.totalSupply())/1000); // Make sure there is enough votes to protect against a malicious arbitrator. uint _milestoneID = disputeIDToMilstoneID[_disputeID]; if (_ruling==TEAM_WINS) { team.transfer(milestone.amountClaimed+milestone.feeTeam+milestone.feeHolders); // Pay the amount claimed and the unused fees to the team. milestone.amount-=milestone.amountClaimed; milestone.amountClaimed=0; milestone.claimTime=0; milestone.disputed=false; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.disputeID=0; milestone.lastTotalFeePayment=0; milestone.lastTotalFeePaymentIsTeam=false; milestone.payerForHolders=0x0; } else if (_ruling==HOLDERS_WINS) { milestone.payerForHolders.transfer(milestone.feeTeam+milestone.feeHolders); // Pay the unused fees to the payer for holders. milestone.amountClaimed=0; milestone.claimTime=0; milestone.disputed=false; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.disputeID=0; milestone.lastTotalFeePayment=0; milestone.lastTotalFeePaymentIsTeam=false; milestone.payerForHolders=0x0; if( ousterID == _milestoneID ) { //if this is the ouster milestone canChangeTeam = true; //allow the funder to change the team } } } /** @dev Change the team. Note that the holders would have to make * the funder a votable contract if they want a vote on who the new team will be. * @param _newTeam the new team. */ function changeTeam(address _newTeam) public { require(msg.sender == funder); //The sender must be the funder. require(canChangeTeam); team = _newTeam; canChangeTeam = false; //This can only be called once. } }
Execute a ruling of a dispute. _disputeID ID of the dispute in the Arbitrator contract. _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision"./
function executeRuling(uint _disputeID, uint _ruling) internal{ Milestone storage milestone=milestones[disputeIDToMilstoneID[_disputeID]]; uint _milestoneID = disputeIDToMilstoneID[_disputeID]; if (_ruling==TEAM_WINS) { milestone.amount-=milestone.amountClaimed; milestone.amountClaimed=0; milestone.claimTime=0; milestone.disputed=false; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.disputeID=0; milestone.lastTotalFeePayment=0; milestone.lastTotalFeePaymentIsTeam=false; milestone.payerForHolders=0x0; milestone.amountClaimed=0; milestone.claimTime=0; milestone.disputed=false; milestone.feeTeam=0; milestone.feeHolders=0; milestone.voteToken=MiniMeToken(0x0); milestone.disputeID=0; milestone.lastTotalFeePayment=0; milestone.lastTotalFeePaymentIsTeam=false; milestone.payerForHolders=0x0; } } else if (_ruling==HOLDERS_WINS) { }
2,547,961
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {ILooksRareToken} from "../interfaces/ILooksRareToken.sol"; /** * @title LooksRareToken (LOOKS) * @notice LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRAR'''''''''''''''''''''''''''''''''''OOKSRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKS:. .;OOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOO,. .,KSRARELOOKSRARELOOKSR LOOKSRARELOOKSRAREL' ..',;:LOOKS::;,'.. 'RARELOOKSRARELOOKSR LOOKSRARELOOKSRAR. .,:LOOKSRARELOOKSRARELO:,. .RELOOKSRARELOOKSR LOOKSRARELOOKS:. .;RARELOOKSRARELOOKSRARELOOKSl;. .:OOKSRARELOOKSR LOOKSRARELOO;. .'OKSRARELOOKSRARELOOKSRARELOOKSRARE'. .;KSRARELOOKSR LOOKSRAREL,. .,LOOKSRARELOOK:;;:"""":;;;lELOOKSRARELO,. .,RARELOOKSR LOOKSRAR. .;okLOOKSRAREx:. .;OOKSRARELOOK;. .RELOOKSR LOOKS:. .:dOOOLOOKSRARE' .''''.. .OKSRARELOOKSR:. .LOOKSR LOx;. .cKSRARELOOKSRAR' 'LOOKSRAR' .KSRARELOOKSRARc.. .OKSR L;. .cxOKSRARELOOKSRAR. .LOOKS.RARE' ;kRARELOOKSRARExc. .;R LO' .;oOKSRARELOOKSRAl. .LOOKS.RARE. :kRARELOOKSRAREo;. 'SR LOOK;. .,KSRARELOOKSRAx, .;LOOKSR;. .oSRARELOOKSRAo,. .;OKSR LOOKSk:. .'RARELOOKSRARd;. .... 'oOOOOOOOOOOxc'. .:LOOKSR LOOKSRARc. .:dLOOKSRAREko;. .,lxOOOOOOOOOd:. .ARELOOKSR LOOKSRARELo' .;oOKSRARELOOxoc;,....,;:ldkOOOOOOOOkd;. 'SRARELOOKSR LOOKSRARELOOd,. .,lSRARELOOKSRARELOOKSRARELOOKSRkl,. .,OKSRARELOOKSR LOOKSRARELOOKSx;. ..;oxELOOKSRARELOOKSRARELOkxl:.. .:LOOKSRARELOOKSR LOOKSRARELOOKSRARc. .':cOKSRARELOOKSRALOc;'. .ARELOOKSRARELOOKSR LOOKSRARELOOKSRARELl' ...'',,,,''... 'SRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOo,. .,OKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSx;. .;xOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRLO:. .:SRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRLOOKl. .lOKSRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRLOOKSRo'. .'oLOOKSRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRLOOKSRARd;. .;xRELOOKSRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRLOOKSRARELO:. .:kRARELOOKSRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKl. .cOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRo' 'oLOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARE,. .,dRELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR */ contract LooksRareToken is ERC20, Ownable, ILooksRareToken { uint256 private immutable _SUPPLY_CAP; /** * @notice Constructor * @param _premintReceiver address that receives the premint * @param _premintAmount amount to premint * @param _cap supply cap (to prevent abusive mint) */ constructor( address _premintReceiver, uint256 _premintAmount, uint256 _cap ) ERC20("LooksRare Token", "LOOKS") { require(_cap > _premintAmount, "LOOKS: Premint amount is greater than cap"); // Transfer the sum of the premint to address _mint(_premintReceiver, _premintAmount); _SUPPLY_CAP = _cap; } /** * @notice Mint LOOKS tokens * @param account address to receive tokens * @param amount amount to mint * @return status true if mint is successful, false if not */ function mint(address account, uint256 amount) external override onlyOwner returns (bool status) { if (totalSupply() + amount <= _SUPPLY_CAP) { _mint(account, amount); return true; } return false; } /** * @notice View supply cap */ function SUPPLY_CAP() external view override returns (uint256) { return _SUPPLY_CAP; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ILooksRareToken is IERC20 { function SUPPLY_CAP() external view returns (uint256); function mint(address account, uint256 amount) external returns (bool); } // 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 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/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); }
Mint LOOKS tokens account address to receive tokens amount amount to mint return status true if mint is successful, false if not/
function mint(address account, uint256 amount) external override onlyOwner returns (bool status) { if (totalSupply() + amount <= _SUPPLY_CAP) { _mint(account, amount); return true; } return false; }
1,328,620
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title A mintable ERC20 token used by agora.space contract AgoraToken is ERC20, Ownable { uint8 private immutable tokenDecimals; constructor( string memory _name, string memory _symbol, uint8 _decimals ) ERC20(_name, _symbol) { tokenDecimals = _decimals; } /// @dev See {ERC20-decimals} function decimals() public view override returns (uint8) { return tokenDecimals; } /// @notice Mints tokens to an account /// @param _account The address receiving the tokens /// @param _amount The amount of tokens to be minted function mint(address _account, uint256 _amount) external onlyOwner { _mint(_account, _amount); } /// @notice Burns tokens from an account /// @param _account The address the tokens will be burnt from /// @param _amount The amount of tokens to be burned function burn(address _account, uint256 _amount) external onlyOwner { _burn(_account, _amount); } }
Mints tokens to an account _account The address receiving the tokens _amount The amount of tokens to be minted
function mint(address _account, uint256 _amount) external onlyOwner { _mint(_account, _amount); }
12,563,144
./full_match/1/0x4a99733458349505A6FCbcF6CD0a0eD18666586A/sources/contracts/exchangeIssuance/ExchangeIssuance.sol
Issues an exact amount of SetTokens for given amount of input ERC20 tokens. The excess amount of tokens is returned in an equivalent amount of ether. _setToken Address of the SetToken to be issued _inputToken Address of the input token _amountSetToken Amount of SetTokens to issue _maxAmountInputToken Maximum amount of input tokens to be used to issue SetTokens/
function issueExactSetFromToken( ISetToken _setToken, IERC20 _inputToken, uint256 _amountSetToken, uint256 _maxAmountInputToken ) isSetToken(_setToken) external nonReentrant { require(_amountSetToken > 0 && _maxAmountInputToken > 0, "ExchangeIssuance: INVALID INPUTS"); _inputToken.safeTransferFrom(msg.sender, address(this), _maxAmountInputToken); uint256 initETHAmount = address(_inputToken) == WETH ? _maxAmountInputToken : _swapTokenForWETH(_inputToken, _maxAmountInputToken); uint256 amountEthSpent = _issueExactSetFromWETH(_setToken, _amountSetToken); uint256 amountEthReturn = initETHAmount.sub(amountEthSpent); if (amountEthReturn > 0) { IWETH(WETH).withdraw(amountEthReturn); msg.sender.transfer(amountEthReturn); } emit ExchangeIssue(msg.sender, _setToken, _inputToken, _maxAmountInputToken, _amountSetToken); }
16,459,118
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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 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 { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "contracts/interfaces/ITrancheToken.sol"; import "contracts/interfaces/IRegistry.sol"; import "contracts/libraries/OndoLibrary.sol"; import "contracts/interfaces/IWETH.sol"; /** * @title Global values used by many contracts * @notice This is mostly used for access control */ contract Registry is IRegistry, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; bool private _paused; bool public override tokenMinting; uint256 public constant override denominator = 10000; IWETH public immutable override weth; EnumerableSet.AddressSet private deadTokens; address payable public fallbackRecipient; mapping(address => string) public strategistNames; modifier onlyRole(bytes32 _role) { require(hasRole(_role, msg.sender), "Unauthorized: Invalid role"); _; } constructor( address _governance, address payable _fallbackRecipient, address _weth ) { require( _fallbackRecipient != address(0) && _fallbackRecipient != address(this), "Invalid address" ); _setupRole(DEFAULT_ADMIN_ROLE, _governance); _setupRole(OLib.GOVERNANCE_ROLE, _governance); _setRoleAdmin(OLib.VAULT_ROLE, OLib.DEPLOYER_ROLE); _setRoleAdmin(OLib.ROLLOVER_ROLE, OLib.DEPLOYER_ROLE); _setRoleAdmin(OLib.STRATEGY_ROLE, OLib.DEPLOYER_ROLE); fallbackRecipient = _fallbackRecipient; weth = IWETH(_weth); } /** * @notice General ACL check * @param _role One of the predefined roles * @param _account Address to check * @return Access/Denied */ function authorized(bytes32 _role, address _account) public view override returns (bool) { return hasRole(_role, _account); } /** * @notice Add a new official strategist * @dev grantRole protects this ACL * @param _strategist Address of new strategist * @param _name Display name for UI */ function addStrategist(address _strategist, string calldata _name) external { grantRole(OLib.STRATEGIST_ROLE, _strategist); strategistNames[_strategist] = _name; } function enableTokens() external override onlyRole(OLib.GOVERNANCE_ROLE) { tokenMinting = true; } function disableTokens() external override onlyRole(OLib.GOVERNANCE_ROLE) { tokenMinting = false; } /** * @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); /* * @notice Helper to expose a Pausable interface to tools */ function paused() public view override returns (bool) { return _paused; } /** * @notice Turn on paused variable. Everything stops! */ function pause() external override onlyRole(OLib.PANIC_ROLE) { _paused = true; emit Paused(msg.sender); } /** * @notice Turn off paused variable. Everything resumes. */ function unpause() external override onlyRole(OLib.GUARDIAN_ROLE) { _paused = false; emit Unpaused(msg.sender); } /** * @notice Manually determine which TrancheToken instances can be recycled * @dev Move into another list where createVault can delete to save gas. Done manually for safety. * @param _tokens List of tokens */ function tokensDeclaredDead(address[] calldata _tokens) external onlyRole(OLib.GUARDIAN_ROLE) { for (uint256 i = 0; i < _tokens.length; i++) { deadTokens.add(_tokens[i]); } } /** * @notice Called by createVault to delete a few dead contracts * @param _tranches Number of tranches (really, number of contracts to delete) */ function recycleDeadTokens(uint256 _tranches) external override onlyRole(OLib.VAULT_ROLE) { uint256 toRecycle = deadTokens.length() >= _tranches ? _tranches : deadTokens.length(); while (toRecycle > 0) { address last = deadTokens.at(deadTokens.length() - 1); try ITrancheToken(last).destroy(fallbackRecipient) {} catch {} deadTokens.remove(last); toRecycle -= 1; } } /** * @notice Who will get any random eth from dead tranchetokens * @param _target Receipient of ETH */ function setFallbackRecipient(address payable _target) external onlyRole(OLib.GOVERNANCE_ROLE) { fallbackRecipient = _target; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "contracts/interfaces/IWETH.sol"; /** * @title Global values used by many contracts * @notice This is mostly used for access control */ interface IRegistry is IAccessControl { function paused() external view returns (bool); function pause() external; function unpause() external; function tokenMinting() external view returns (bool); function denominator() external view returns (uint256); function weth() external view returns (IWETH); function authorized(bytes32 _role, address _account) external view returns (bool); function enableTokens() external; function disableTokens() external; function recycleDeadTokens(uint256 _tranches) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface ITrancheToken is IERC20Upgradeable { function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; function destroy(address payable _receiver) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Arrays.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; //import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Helper functions */ library OLib { using Arrays for uint256[]; using OLib for OLib.Investor; // State transition per Vault. Just linear transitions. enum State {Inactive, Deposit, Live, Withdraw} // Only supports 2 tranches for now enum Tranche {Senior, Junior} struct VaultParams { address seniorAsset; address juniorAsset; address strategist; address strategy; uint256 hurdleRate; uint256 startTime; uint256 enrollment; uint256 duration; string seniorName; string seniorSym; string juniorName; string juniorSym; uint256 seniorTrancheCap; uint256 seniorUserCap; uint256 juniorTrancheCap; uint256 juniorUserCap; } struct RolloverParams { VaultParams vault; address strategist; string seniorName; string seniorSym; string juniorName; string juniorSym; } bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant PANIC_ROLE = keccak256("PANIC_ROLE"); bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); bytes32 public constant DEPLOYER_ROLE = keccak256("DEPLOYER_ROLE"); bytes32 public constant CREATOR_ROLE = keccak256("CREATOR_ROLE"); bytes32 public constant STRATEGIST_ROLE = keccak256("STRATEGIST_ROLE"); bytes32 public constant VAULT_ROLE = keccak256("VAULT_ROLE"); bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE"); bytes32 public constant STRATEGY_ROLE = keccak256("STRATEGY_ROLE"); // Both sums are running sums. If a user deposits [$1, $5, $3], then // userSums would be [$1, $6, $9]. You can figure out the deposit // amount be subtracting userSums[i]-userSum[i-1]. // prefixSums is the total deposited for all investors + this // investors deposit at the time this deposit is made. So at // prefixSum[0], it would be $1 + totalDeposits, where totalDeposits // could be $1000 because other investors have put in money. struct Investor { uint256[] userSums; uint256[] prefixSums; bool claimed; bool withdrawn; } /** * @dev Given the total amount invested by the Vault, we want to find * out how many of this investor's deposits were actually * used. Use findUpperBound on the prefixSum to find the point * where total deposits were accepted. For example, if $2000 was * deposited by all investors and $1000 was invested, then some * position in the prefixSum splits the array into deposits that * got in, and deposits that didn't get in. That same position * maps to userSums. This is the user's deposits that got * in. Since we are keeping track of the sums, we know at that * position the total deposits for a user was $15, even if it was * 15 $1 deposits. And we know the amount that didn't get in is * the last value in userSum - the amount that got it. * @param investor A specific investor * @param invested The total amount invested by this Vault */ function getInvestedAndExcess(Investor storage investor, uint256 invested) internal view returns (uint256 userInvested, uint256 excess) { uint256[] storage prefixSums_ = investor.prefixSums; uint256 length = prefixSums_.length; if (length == 0) { // There were no deposits. Return 0, 0. return (userInvested, excess); } uint256 leastUpperBound = prefixSums_.findUpperBound(invested); if (length == leastUpperBound) { // All deposits got in, no excess. Return total deposits, 0 userInvested = investor.userSums[length - 1]; return (userInvested, excess); } uint256 prefixSum = prefixSums_[leastUpperBound]; if (prefixSum == invested) { // Not all deposits got in, but there are no partial deposits userInvested = investor.userSums[leastUpperBound]; excess = investor.userSums[length - 1] - userInvested; } else { // Let's say some of my deposits got in. The last deposit, // however, was $100 and only $30 got in. Need to split that // deposit so $30 got in, $70 is excess. userInvested = leastUpperBound > 0 ? investor.userSums[leastUpperBound - 1] : 0; uint256 depositAmount = investor.userSums[leastUpperBound] - userInvested; if (prefixSum - depositAmount < invested) { userInvested += (depositAmount + invested - prefixSum); excess = investor.userSums[length - 1] - userInvested; } else { excess = investor.userSums[length - 1] - userInvested; } } } } /** * @title Subset of SafeERC20 from openZeppelin * * @dev Some non-standard ERC20 contracts (e.g. Tether) break * `approve` by forcing it to behave like `safeApprove`. This means * `safeIncreaseAllowance` will fail when it tries to adjust the * allowance. The code below simply adds an extra call to * `approve(spender, 0)`. */ library OndoSaferERC20 { using SafeERC20 for IERC20; function ondoSafeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; token.safeApprove(spender, 0); token.safeApprove(spender, newAllowance); } }
Turn off paused variable. Everything resumes./
function unpause() external override onlyRole(OLib.GUARDIAN_ROLE) { _paused = false; emit Unpaused(msg.sender); }
1,397,524
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./interfaces/IRewardStaking.sol"; import "./interfaces/ILockedCvx.sol"; import "./interfaces/IDelegation.sol"; import "./interfaces/ICrvDepositor.sol"; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; //Basic functionality to integrate with locking cvx contract BasicCvxHolder{ using SafeERC20 for IERC20; using Address for address; address public constant cvxCrv = address(0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7); address public constant cvxcrvStaking = address(0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e); address public constant cvx = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); address public constant crvDeposit = address(0x8014595F2AB54cD7c604B00E9fb932176fDc86Ae); address public operator; ILockedCvx public immutable cvxlocker; constructor(address _cvxlocker) public { cvxlocker = ILockedCvx(_cvxlocker); operator = msg.sender; } function setApprovals() external { IERC20(cvxCrv).safeApprove(cvxcrvStaking, 0); IERC20(cvxCrv).safeApprove(cvxcrvStaking, uint256(-1)); IERC20(cvx).safeApprove(address(cvxlocker), 0); IERC20(cvx).safeApprove(address(cvxlocker), uint256(-1)); IERC20(crv).safeApprove(crvDeposit, 0); IERC20(crv).safeApprove(crvDeposit, uint256(-1)); } function setOperator(address _op) external { require(msg.sender == operator, "!auth"); operator = _op; } function setDelegate(address _delegateContract, address _delegate) external{ require(msg.sender == operator, "!auth"); // IDelegation(_delegateContract).setDelegate(keccak256("cvx.eth"), _delegate); IDelegation(_delegateContract).setDelegate("cvx.eth", _delegate); } function lock(uint256 _amount, uint256 _spendRatio) external{ require(msg.sender == operator, "!auth"); if(_amount > 0){ IERC20(cvx).safeTransferFrom(msg.sender, address(this), _amount); } _amount = IERC20(cvx).balanceOf(address(this)); cvxlocker.lock(address(this),_amount,_spendRatio); } function processExpiredLocks(bool _relock, uint256 _spendRatio) external{ require(msg.sender == operator, "!auth"); cvxlocker.processExpiredLocks(_relock, _spendRatio, address(this)); } function processRewards() external{ require(msg.sender == operator, "!auth"); cvxlocker.getReward(address(this), true); IRewardStaking(cvxcrvStaking).getReward(address(this), true); uint256 crvBal = IERC20(crv).balanceOf(address(this)); if (crvBal > 0) { ICrvDepositor(crvDeposit).deposit(crvBal, true); } uint cvxcrvBal = IERC20(cvxCrv).balanceOf(address(this)); if(cvxcrvBal > 0){ IRewardStaking(cvxcrvStaking).stake(cvxcrvBal); } } function withdrawCvxCrv(uint256 _amount, address _withdrawTo) external{ require(msg.sender == operator, "!auth"); require(_withdrawTo != address(0),"bad address"); IRewardStaking(cvxcrvStaking).withdraw(_amount, true); uint cvxcrvBal = IERC20(cvxCrv).balanceOf(address(this)); if(cvxcrvBal > 0){ IERC20(cvxCrv).safeTransfer(_withdrawTo, cvxcrvBal); } } function withdrawTo(IERC20 _asset, uint256 _amount, address _to) external { require(msg.sender == operator, "!auth"); _asset.safeTransfer(_to, _amount); } function execute( address _to, uint256 _value, bytes calldata _data ) external returns (bool, bytes memory) { require(msg.sender == operator,"!auth"); (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } }
IDelegation(_delegateContract).setDelegate(keccak256("cvx.eth"), _delegate);
function setDelegate(address _delegateContract, address _delegate) external{ require(msg.sender == operator, "!auth"); IDelegation(_delegateContract).setDelegate("cvx.eth", _delegate); }
12,891,518
./partial_match/4/0x8CAb6E250CBE9129962a5Dc837d70c478d5C3af5/sources/FatMasterFarmer.sol
lock 100% of reward if it come from bounus time
function _harvest(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFatPerShare).div(1e12).sub(user.rewardDebt); uint256 masterBal = fat.balanceOf(address(this)); if (pending > masterBal) { pending = masterBal; } if(pending > 0) { fat.transfer(msg.sender, pending); uint256 lockAmount = 0; if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) { lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div(100); fat.lock(msg.sender, lockAmount); } user.rewardDebtAtBlock = block.number; emit SendFatReward(msg.sender, _pid, pending, lockAmount); } user.rewardDebt = user.amount.mul(pool.accFatPerShare).div(1e12); } }
8,563,358
./full_match/1/0x83Ed35aEE375180d4Fb7C32743DFce6510717294/sources/browser/TELOS_FAAS.sol
Deposit LP tokens to FarmingBad for FaasToken allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFAASPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeFaasTransfer(msg.sender, pending); } } if(_amount > 0) { uint256 _taxAmount = _amount.mul(DEV_TAX).div(100); _amount = _amount.sub(_taxAmount); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); pool.lpToken.safeTransferFrom(address(msg.sender), address(devaddr), _taxAmount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accFAASPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
3,187,075
pragma solidity ^0.4.24; // Amis Dex OnChainOrderBook follows ERC20 Standards contract ERC20 { function totalSupply() constant returns (uint); function balanceOf(address _owner) constant returns (uint balance); function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } // Amis Dex on-chain order book matching engine Version 0.1.2. // https://github.com/amisolution/ERC20-AMIS/contracts/OnChainOrderBookV012b.sol // This smart contract is a variation of a neat ERC20 token as base, ETH as quoted, // and standard fees with incentivized reward token. // This contract allows minPriceExponent, baseMinInitialSize, and baseMinRemainingSize // to be set at init() time appropriately for the token decimals and likely value. // contract OnChainOrderBookV012b { enum BookType { ERC20EthV1 } enum Direction { Invalid, Buy, Sell } enum Status { Unknown, Rejected, Open, Done, NeedsGas, Sending, // not used by contract - web UI only FailedSend, // not used by contract - web UI only FailedTxn // not used by contract - web UI only } enum ReasonCode { None, InvalidPrice, InvalidSize, InvalidTerms, InsufficientFunds, WouldTake, Unmatched, TooManyMatches, ClientCancel } enum Terms { GTCNoGasTopup, GTCWithGasTopup, ImmediateOrCancel, MakerOnly } struct Order { // these are immutable once placed: address client; uint16 price; // packed representation of side + price uint sizeBase; Terms terms; // these are mutable until Done or Rejected: Status status; ReasonCode reasonCode; uint128 executedBase; // gross amount executed in base currency (before fee deduction) uint128 executedCntr; // gross amount executed in quoted currency (before fee deduction) uint128 feesBaseOrCntr; // base for buy, cntr for sell uint128 feesRwrd; } struct OrderChain { uint128 firstOrderId; uint128 lastOrderId; } struct OrderChainNode { uint128 nextOrderId; uint128 prevOrderId; } // Rebuild the expected state of the contract given: // - ClientPaymentEvent log history // - ClientOrderEvent log history // - Calling getOrder for the other immutable order fields of orders referenced by ClientOrderEvent enum ClientPaymentEventType { Deposit, Withdraw, TransferFrom, Transfer } enum BalanceType { Base, Cntr, Rwrd } event ClientPaymentEvent( address indexed client, ClientPaymentEventType clientPaymentEventType, BalanceType balanceType, int clientBalanceDelta ); enum ClientOrderEventType { Create, Continue, Cancel } event ClientOrderEvent( address indexed client, ClientOrderEventType clientOrderEventType, uint128 orderId, uint maxMatches ); enum MarketOrderEventType { // orderCount++, depth += depthBase Add, // orderCount--, depth -= depthBase Remove, // orderCount--, depth -= depthBase, traded += tradeBase // (depth change and traded change differ when tiny remaining amount refunded) CompleteFill, // orderCount unchanged, depth -= depthBase, traded += tradeBase PartialFill } // Technically not needed but these events can be used to maintain an order book or // watch for fills. Note that the orderId and price are those of the maker. event MarketOrderEvent( uint256 indexed eventTimestamp, uint128 indexed orderId, MarketOrderEventType marketOrderEventType, uint16 price, uint depthBase, uint tradeBase ); // the base token (e.g. AMIS) ERC20 baseToken; // minimum order size (inclusive) uint baseMinInitialSize; // set at init // if following partial match, the remaining gets smaller than this, remove from Order Book and refund: // generally we make this 10% of baseMinInitialSize uint baseMinRemainingSize; // set at init // maximum order size (exclusive) // chosen so that even multiplied by the max price (or divided by the min price), // and then multiplied by ethRwrdRate, it still fits in 2^127, allowing us to save // some gas by storing executed + fee fields as uint128. // even with 18 decimals, this still allows order sizes up to 1,000,000,000. // if we encounter a token with e.g. 36 decimals we'll have to revisit ... uint constant baseMaxSize = 10 ** 30; // the counter currency or ETH traded pair // (no address because it is ETH) // avoid the book getting cluttered up with tiny amounts not worth the gas uint constant cntrMinInitialSize = 10 finney; // see comments for baseMaxSize uint constant cntrMaxSize = 10 ** 30; // the reward token that can be used to pay fees (AMIS / ORA / CRSW) ERC20 rwrdToken; // set at init // used to convert ETH amount to reward tokens when paying fee with reward tokens uint constant ethRwrdRate = 1000; // funds that belong to clients (base, counter, and reward) mapping (address => uint) balanceBaseForClient; mapping (address => uint) balanceCntrForClient; mapping (address => uint) balanceRwrdForClient; // fee charged on liquidity taken, expressed as a divisor // (e.g. 2000 means 1/2000, or 0.05%) uint constant feeDivisor = 2000; // fees charged are given to: address feeCollector; // set at init // all orders ever created mapping (uint128 => Order) orderForOrderId; // Effectively a compact mapping from price to whether there are any open orders at that price. // See "Price Calculation Constants" below as to why 85. uint256[85] occupiedPriceBitmaps; // These allow us to walk over the orders in the book at a given price level (and add more). mapping (uint16 => OrderChain) orderChainForOccupiedPrice; mapping (uint128 => OrderChainNode) orderChainNodeForOpenOrderId; // These allow a client to (reasonably) efficiently find their own orders // without relying on events (which even indexed are a bit expensive to search // and cannot be accessed from smart contracts). See walkOrders. mapping (address => uint128) mostRecentOrderIdForClient; mapping (uint128 => uint128) clientPreviousOrderIdBeforeOrderId; // Price Calculation Constants. // // We pack direction and price into a crafty decimal floating point representation // for efficient indexing by price, the main thing we lose by doing so is precision - // we only have 3 significant figures in our prices. // // An unpacked price consists of: // // direction - invalid / buy / sell // mantissa - ranges from 100 to 999 representing 0.100 to 0.999 // exponent - ranges from minimumPriceExponent to minimumPriceExponent + 11 // (e.g. -5 to +6 for a typical pair where minPriceExponent = -5) // // The packed representation has 21601 different price values: // // 0 = invalid (can be used as marker value) // 1 = buy at maximum price (0.999 * 10 ** 6) // ... = other buy prices in descending order // 5400 = buy at 1.00 // ... = other buy prices in descending order // 10800 = buy at minimum price (0.100 * 10 ** -5) // 10801 = sell at minimum price (0.100 * 10 ** -5) // ... = other sell prices in descending order // 16201 = sell at 1.00 // ... = other sell prices in descending order // 21600 = sell at maximum price (0.999 * 10 ** 6) // 21601+ = do not use // // If we want to map each packed price to a boolean value (which we do), // we require 85 256-bit words. Or 42.5 for each side of the book. int8 minPriceExponent; // set at init uint constant invalidPrice = 0; // careful: max = largest unpacked value, not largest packed value uint constant maxBuyPrice = 1; uint constant minBuyPrice = 10800; uint constant minSellPrice = 10801; uint constant maxSellPrice = 21600; // Constructor. // // Sets feeCollector to the creator. Creator needs to call init() to finish setup. // function OnChainOrderBookV012b() { address creator = msg.sender; feeCollector = creator; } // "Public" Management - set address of base and reward tokens. // // Can only be done once (normally immediately after creation) by the fee collector. // // Used instead of a constructor to make deployment easier. // // baseMinInitialSize is the minimum order size in token-wei; // the minimum resting size will be one tenth of that. // // minPriceExponent controls the range of prices supported by the contract; // the range will be 0.100*10**minPriceExponent to 0.999*10**(minPriceExponent + 11) // but careful; this is in token-wei : wei, ignoring the number of decimals of the token // e.g. -5 implies 1 token-wei worth between 0.100e-5 to 0.999e+6 wei // which implies same token:eth exchange rate if token decimals are 18 like eth, // but if token decimals are 8, that would imply 1 token worth 10 wei to 0.000999 ETH. // function init(ERC20 _baseToken, ERC20 _rwrdToken, uint _baseMinInitialSize, int8 _minPriceExponent) public { require(msg.sender == feeCollector); require(address(baseToken) == 0); require(address(_baseToken) != 0); require(address(rwrdToken) == 0); require(address(_rwrdToken) != 0); require(_baseMinInitialSize >= 10); require(_baseMinInitialSize < baseMaxSize / 1000000); require(_minPriceExponent >= -20 && _minPriceExponent <= 20); if (_minPriceExponent < 2) { require(_baseMinInitialSize >= 10 ** uint(3-int(minPriceExponent))); } baseMinInitialSize = _baseMinInitialSize; // dust prevention. truncation ok, know >= 10 baseMinRemainingSize = _baseMinInitialSize / 10; minPriceExponent = _minPriceExponent; // attempt to catch bad tokens: require(_baseToken.totalSupply() > 0); baseToken = _baseToken; require(_rwrdToken.totalSupply() > 0); rwrdToken = _rwrdToken; } // "Public" Management - change fee collector // // The new fee collector only gets fees charged after this point. // function changeFeeCollector(address newFeeCollector) public { address oldFeeCollector = feeCollector; require(msg.sender == oldFeeCollector); require(newFeeCollector != oldFeeCollector); feeCollector = newFeeCollector; } // Public Info View - what is being traded here, what are the limits? // function getBookInfo() public constant returns ( BookType _bookType, address _baseToken, address _rwrdToken, uint _baseMinInitialSize, uint _cntrMinInitialSize, int8 _minPriceExponent, uint _feeDivisor, address _feeCollector ) { return ( BookType.ERC20EthV1, address(baseToken), address(rwrdToken), baseMinInitialSize, // can assume min resting size is one tenth of this cntrMinInitialSize, minPriceExponent, feeDivisor, feeCollector ); } // Public Funds View - get balances held by contract on behalf of the client, // or balances approved for deposit but not yet claimed by the contract. // // Excludes funds in open orders. // // Helps a web ui get a consistent snapshot of balances. // // It would be nice to return the off-exchange ETH balance too but there's a // bizarre bug in geth (and apparently as a result via MetaMask) that leads // to unpredictable behaviour when looking up client balances in constant // functions - see e.g. https://github.com/ethereum/solidity/issues/2325 . // function getClientBalances(address client) public constant returns ( uint bookBalanceBase, uint bookBalanceCntr, uint bookBalanceRwrd, uint approvedBalanceBase, uint approvedBalanceRwrd, uint ownBalanceBase, uint ownBalanceRwrd ) { bookBalanceBase = balanceBaseForClient[client]; bookBalanceCntr = balanceCntrForClient[client]; bookBalanceRwrd = balanceRwrdForClient[client]; approvedBalanceBase = baseToken.allowance(client, address(this)); approvedBalanceRwrd = rwrdToken.allowance(client, address(this)); ownBalanceBase = baseToken.balanceOf(client); ownBalanceRwrd = rwrdToken.balanceOf(client); } // Public Funds moves - deposit previously-approved base tokens. // function transferFromBase() public { address client = msg.sender; address book = address(this); // we trust the ERC20 token contract not to do nasty things like call back into us - // if we cannot trust the token then why are we allowing it to be traded? uint amountBase = baseToken.allowance(client, book); require(amountBase > 0); // NB: needs change for older ERC20 tokens that don't return bool require(baseToken.transferFrom(client, book, amountBase)); // belt and braces assert(baseToken.allowance(client, book) == 0); balanceBaseForClient[client] += amountBase; ClientPaymentEvent(client, ClientPaymentEventType.TransferFrom, BalanceType.Base, int(amountBase)); } // Public Funds moves - withdraw base tokens (as a transfer). // function transferBase(uint amountBase) public { address client = msg.sender; require(amountBase > 0); require(amountBase <= balanceBaseForClient[client]); // overflow safe since we checked less than balance above balanceBaseForClient[client] -= amountBase; // we trust the ERC20 token contract not to do nasty things like call back into us - require(baseToken.transfer(client, amountBase)); ClientPaymentEvent(client, ClientPaymentEventType.Transfer, BalanceType.Base, -int(amountBase)); } // Public Funds moves - deposit counter quoted currency (ETH or DAI). // function depositCntr() public payable { address client = msg.sender; uint amountCntr = msg.value; require(amountCntr > 0); // overflow safe - if someone owns pow(2,255) ETH we have bigger problems balanceCntrForClient[client] += amountCntr; ClientPaymentEvent(client, ClientPaymentEventType.Deposit, BalanceType.Cntr, int(amountCntr)); } // Public Funds Move - withdraw counter quoted currency (ETH or DAI). // function withdrawCntr(uint amountCntr) public { address client = msg.sender; require(amountCntr > 0); require(amountCntr <= balanceCntrForClient[client]); // overflow safe - checked less than balance above balanceCntrForClient[client] -= amountCntr; // safe - not enough gas to do anything interesting in fallback, already adjusted balance client.transfer(amountCntr); ClientPaymentEvent(client, ClientPaymentEventType.Withdraw, BalanceType.Cntr, -int(amountCntr)); } // Public Funds Move - deposit previously-approved incentivized reward tokens. // function transferFromRwrd() public { address client = msg.sender; address book = address(this); uint amountRwrd = rwrdToken.allowance(client, book); require(amountRwrd > 0); // we created the incentivized reward token so we know it supports ERC20 properly and is not evil require(rwrdToken.transferFrom(client, book, amountRwrd)); // belt and braces assert(rwrdToken.allowance(client, book) == 0); balanceRwrdForClient[client] += amountRwrd; ClientPaymentEvent(client, ClientPaymentEventType.TransferFrom, BalanceType.Rwrd, int(amountRwrd)); } // Public Funds Manipulation - withdraw base tokens (as a transfer). // function transferRwrd(uint amountRwrd) public { address client = msg.sender; require(amountRwrd > 0); require(amountRwrd <= balanceRwrdForClient[client]); // overflow safe - checked less than balance above balanceRwrdForClient[client] -= amountRwrd; // we created the incentivized reward token so we know it supports ERC20 properly and is not evil require(rwrdToken.transfer(client, amountRwrd)); ClientPaymentEvent(client, ClientPaymentEventType.Transfer, BalanceType.Rwrd, -int(amountRwrd)); } // Public Order View - get full details of an order. // // If the orderId does not exist, status will be Unknown. // function getOrder(uint128 orderId) public constant returns ( address client, uint16 price, uint sizeBase, Terms terms, Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr, uint feesBaseOrCntr, uint feesRwrd) { Order storage order = orderForOrderId[orderId]; return (order.client, order.price, order.sizeBase, order.terms, order.status, order.reasonCode, order.executedBase, order.executedCntr, order.feesBaseOrCntr, order.feesRwrd); } // Public Order View - get mutable details of an order. // // If the orderId does not exist, status will be Unknown. // function getOrderState(uint128 orderId) public constant returns ( Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr, uint feesBaseOrCntr, uint feesRwrd) { Order storage order = orderForOrderId[orderId]; return (order.status, order.reasonCode, order.executedBase, order.executedCntr, order.feesBaseOrCntr, order.feesRwrd); } // Public Order View - enumerate all recent orders + all open orders for one client. // // Not really designed for use from a smart contract transaction. // Baseline concept: // - client ensures order ids are generated so that most-signficant part is time-based; // - client decides they want all orders after a certain point-in-time, // and chooses minClosedOrderIdCutoff accordingly; // - before that point-in-time they just get open and needs gas orders // - client calls walkClientOrders with maybeLastOrderIdReturned = 0 initially; // - then repeats with the orderId returned by walkClientOrders; // - (and stops if it returns a zero orderId); // // Note that client is only used when maybeLastOrderIdReturned = 0. // function walkClientOrders( address client, uint128 maybeLastOrderIdReturned, uint128 minClosedOrderIdCutoff ) public constant returns ( uint128 orderId, uint16 price, uint sizeBase, Terms terms, Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr, uint feesBaseOrCntr, uint feesRwrd) { if (maybeLastOrderIdReturned == 0) { orderId = mostRecentOrderIdForClient[client]; } else { orderId = clientPreviousOrderIdBeforeOrderId[maybeLastOrderIdReturned]; } while (true) { if (orderId == 0) return; Order storage order = orderForOrderId[orderId]; if (orderId >= minClosedOrderIdCutoff) break; if (order.status == Status.Open || order.status == Status.NeedsGas) break; orderId = clientPreviousOrderIdBeforeOrderId[orderId]; } return (orderId, order.price, order.sizeBase, order.terms, order.status, order.reasonCode, order.executedBase, order.executedCntr, order.feesBaseOrCntr, order.feesRwrd); } // Internal Price Calculation - turn packed price into a friendlier unpacked price. // function unpackPrice(uint16 price) internal constant returns ( Direction direction, uint16 mantissa, int8 exponent ) { uint sidedPriceIndex = uint(price); uint priceIndex; if (sidedPriceIndex < 1 || sidedPriceIndex > maxSellPrice) { direction = Direction.Invalid; mantissa = 0; exponent = 0; return; } else if (sidedPriceIndex <= minBuyPrice) { direction = Direction.Buy; priceIndex = minBuyPrice - sidedPriceIndex; } else { direction = Direction.Sell; priceIndex = sidedPriceIndex - minSellPrice; } uint zeroBasedMantissa = priceIndex % 900; uint zeroBasedExponent = priceIndex / 900; mantissa = uint16(zeroBasedMantissa + 100); exponent = int8(zeroBasedExponent) + minPriceExponent; return; } // Internal Price Calculation - is a packed price on the buy side? // // Throws an error if price is invalid. // function isBuyPrice(uint16 price) internal constant returns (bool isBuy) { // yes, this looks odd, but max here is highest _unpacked_ price return price >= maxBuyPrice && price <= minBuyPrice; } // Internal Price Calculation - turn a packed buy price into a packed sell price. // // Invalid price remains invalid. // function computeOppositePrice(uint16 price) internal constant returns (uint16 opposite) { if (price < maxBuyPrice || price > maxSellPrice) { return uint16(invalidPrice); } else if (price <= minBuyPrice) { return uint16(maxSellPrice - (price - maxBuyPrice)); } else { return uint16(maxBuyPrice + (maxSellPrice - price)); } } // Internal Price Calculation - compute amount in counter currency that would // be obtained by selling baseAmount at the given unpacked price (if no fees). // // Notes: // - Does not validate price - caller must ensure valid. // - Could overflow producing very unexpected results if baseAmount very // large - caller must check this. // - This rounds the amount towards zero. // - May truncate to zero if baseAmount very small - potentially allowing // zero-cost buys or pointless sales - caller must check this. // function computeCntrAmountUsingUnpacked( uint baseAmount, uint16 mantissa, int8 exponent ) internal constant returns (uint cntrAmount) { if (exponent < 0) { return baseAmount * uint(mantissa) / 1000 / 10 ** uint(-exponent); } else { return baseAmount * uint(mantissa) / 1000 * 10 ** uint(exponent); } } // Internal Price Calculation - compute amount in counter currency that would // be obtained by selling baseAmount at the given packed price (if no fees). // // Notes: // - Does not validate price - caller must ensure valid. // - Direction of the packed price is ignored. // - Could overflow producing very unexpected results if baseAmount very // large - caller must check this. // - This rounds the amount towards zero (regardless of Buy or Sell). // - May truncate to zero if baseAmount very small - potentially allowing // zero-cost buys or pointless sales - caller must check this. // function computeCntrAmountUsingPacked( uint baseAmount, uint16 price ) internal constant returns (uint) { var (, mantissa, exponent) = unpackPrice(price); return computeCntrAmountUsingUnpacked(baseAmount, mantissa, exponent); } // Public Order Placement - create order and try to match it and/or add it to the book. // function createOrder( uint128 orderId, uint16 price, uint sizeBase, Terms terms, uint maxMatches ) public { address client = msg.sender; require(orderId != 0 && orderForOrderId[orderId].client == 0); ClientOrderEvent(client, ClientOrderEventType.Create, orderId, maxMatches); orderForOrderId[orderId] = Order(client, price, sizeBase, terms, Status.Unknown, ReasonCode.None, 0, 0, 0, 0); uint128 previousMostRecentOrderIdForClient = mostRecentOrderIdForClient[client]; mostRecentOrderIdForClient[client] = orderId; clientPreviousOrderIdBeforeOrderId[orderId] = previousMostRecentOrderIdForClient; Order storage order = orderForOrderId[orderId]; var (direction, mantissa, exponent) = unpackPrice(price); if (direction == Direction.Invalid) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InvalidPrice; return; } if (sizeBase < baseMinInitialSize || sizeBase > baseMaxSize) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InvalidSize; return; } uint sizeCntr = computeCntrAmountUsingUnpacked(sizeBase, mantissa, exponent); if (sizeCntr < cntrMinInitialSize || sizeCntr > cntrMaxSize) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InvalidSize; return; } if (terms == Terms.MakerOnly && maxMatches != 0) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InvalidTerms; return; } if (!debitFunds(client, direction, sizeBase, sizeCntr)) { order.status = Status.Rejected; order.reasonCode = ReasonCode.InsufficientFunds; return; } processOrder(orderId, maxMatches); } // Public Order Placement - cancel order // function cancelOrder(uint128 orderId) public { address client = msg.sender; Order storage order = orderForOrderId[orderId]; require(order.client == client); Status status = order.status; if (status != Status.Open && status != Status.NeedsGas) { return; } ClientOrderEvent(client, ClientOrderEventType.Cancel, orderId, 0); if (status == Status.Open) { removeOpenOrderFromBook(orderId); MarketOrderEvent(block.timestamp, orderId, MarketOrderEventType.Remove, order.price, order.sizeBase - order.executedBase, 0); } refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.ClientCancel); } // Public Order Placement - continue placing an order in 'NeedsGas' state // function continueOrder(uint128 orderId, uint maxMatches) public { address client = msg.sender; Order storage order = orderForOrderId[orderId]; require(order.client == client); if (order.status != Status.NeedsGas) { return; } ClientOrderEvent(client, ClientOrderEventType.Continue, orderId, maxMatches); order.status = Status.Unknown; processOrder(orderId, maxMatches); } // Internal Order Placement - remove a still-open order from the book. // // Caller's job to update/refund the order + raise event, this just // updates the order chain and bitmask. // // Too expensive to do on each resting order match - we only do this for an // order being cancelled. See matchWithOccupiedPrice for similar logic. // function removeOpenOrderFromBook(uint128 orderId) internal { Order storage order = orderForOrderId[orderId]; uint16 price = order.price; OrderChain storage orderChain = orderChainForOccupiedPrice[price]; OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId]; uint128 nextOrderId = orderChainNode.nextOrderId; uint128 prevOrderId = orderChainNode.prevOrderId; if (nextOrderId != 0) { OrderChainNode storage nextOrderChainNode = orderChainNodeForOpenOrderId[nextOrderId]; nextOrderChainNode.prevOrderId = prevOrderId; } else { orderChain.lastOrderId = prevOrderId; } if (prevOrderId != 0) { OrderChainNode storage prevOrderChainNode = orderChainNodeForOpenOrderId[prevOrderId]; prevOrderChainNode.nextOrderId = nextOrderId; } else { orderChain.firstOrderId = nextOrderId; } if (nextOrderId == 0 && prevOrderId == 0) { uint bmi = price / 256; // index into array of bitmaps uint bti = price % 256; // bit position within bitmap // we know was previously occupied so XOR clears occupiedPriceBitmaps[bmi] ^= 2 ** bti; } } // Internal Order Placement - credit funds received when taking liquidity from book // function creditExecutedFundsLessFees(uint128 orderId, uint originalExecutedBase, uint originalExecutedCntr) internal { Order storage order = orderForOrderId[orderId]; uint liquidityTakenBase = order.executedBase - originalExecutedBase; uint liquidityTakenCntr = order.executedCntr - originalExecutedCntr; // Normally we deduct the fee from the currency bought (base for buy, cntr for sell), // however we also accept reward tokens from the reward balance if it covers the fee, // with the reward amount converted from the ETH amount (the counter currency here) // at a fixed exchange rate. // Overflow safe since we ensure order size < 10^30 in both currencies (see baseMaxSize). // Can truncate to zero, which is fine. uint feesRwrd = liquidityTakenCntr / feeDivisor * ethRwrdRate; uint feesBaseOrCntr; address client = order.client; uint availRwrd = balanceRwrdForClient[client]; if (feesRwrd <= availRwrd) { balanceRwrdForClient[client] = availRwrd - feesRwrd; balanceRwrdForClient[feeCollector] = feesRwrd; // Need += rather than = because could have paid some fees earlier in NeedsGas situation. // Overflow safe since we ensure order size < 10^30 in both currencies (see baseMaxSize). // Can truncate to zero, which is fine. order.feesRwrd += uint128(feesRwrd); if (isBuyPrice(order.price)) { balanceBaseForClient[client] += liquidityTakenBase; } else { balanceCntrForClient[client] += liquidityTakenCntr; } } else if (isBuyPrice(order.price)) { // See comments in branch above re: use of += and overflow safety. feesBaseOrCntr = liquidityTakenBase / feeDivisor; balanceBaseForClient[order.client] += (liquidityTakenBase - feesBaseOrCntr); order.feesBaseOrCntr += uint128(feesBaseOrCntr); balanceBaseForClient[feeCollector] += feesBaseOrCntr; } else { // See comments in branch above re: use of += and overflow safety. feesBaseOrCntr = liquidityTakenCntr / feeDivisor; balanceCntrForClient[order.client] += (liquidityTakenCntr - feesBaseOrCntr); order.feesBaseOrCntr += uint128(feesBaseOrCntr); balanceCntrForClient[feeCollector] += feesBaseOrCntr; } } // Internal Order Placement - process a created and sanity checked order. // // Used both for new orders and for gas topup. // function processOrder(uint128 orderId, uint maxMatches) internal { Order storage order = orderForOrderId[orderId]; uint ourOriginalExecutedBase = order.executedBase; uint ourOriginalExecutedCntr = order.executedCntr; var (ourDirection,) = unpackPrice(order.price); uint theirPriceStart = (ourDirection == Direction.Buy) ? minSellPrice : maxBuyPrice; uint theirPriceEnd = computeOppositePrice(order.price); MatchStopReason matchStopReason = matchAgainstBook(orderId, theirPriceStart, theirPriceEnd, maxMatches); creditExecutedFundsLessFees(orderId, ourOriginalExecutedBase, ourOriginalExecutedCntr); if (order.terms == Terms.ImmediateOrCancel) { if (matchStopReason == MatchStopReason.Satisfied) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.None); return; } else if (matchStopReason == MatchStopReason.MaxMatches) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.TooManyMatches); return; } else if (matchStopReason == MatchStopReason.BookExhausted) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.Unmatched); return; } } else if (order.terms == Terms.MakerOnly) { if (matchStopReason == MatchStopReason.MaxMatches) { refundUnmatchedAndFinish(orderId, Status.Rejected, ReasonCode.WouldTake); return; } else if (matchStopReason == MatchStopReason.BookExhausted) { enterOrder(orderId); return; } } else if (order.terms == Terms.GTCNoGasTopup) { if (matchStopReason == MatchStopReason.Satisfied) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.None); return; } else if (matchStopReason == MatchStopReason.MaxMatches) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.TooManyMatches); return; } else if (matchStopReason == MatchStopReason.BookExhausted) { enterOrder(orderId); return; } } else if (order.terms == Terms.GTCWithGasTopup) { if (matchStopReason == MatchStopReason.Satisfied) { refundUnmatchedAndFinish(orderId, Status.Done, ReasonCode.None); return; } else if (matchStopReason == MatchStopReason.MaxMatches) { order.status = Status.NeedsGas; return; } else if (matchStopReason == MatchStopReason.BookExhausted) { enterOrder(orderId); return; } } assert(false); // should not be possible to reach here } // Used internally to indicate why we stopped matching an order against the book. enum MatchStopReason { None, MaxMatches, Satisfied, PriceExhausted, BookExhausted } // Internal Order Placement - Match the given order against the book. // // Resting orders matched will be updated, removed from book and funds credited to their owners. // // Only updates the executedBase and executedCntr of the given order - caller is responsible // for crediting matched funds, charging fees, marking order as done / entering it into the book. // // matchStopReason returned will be one of MaxMatches, Satisfied or BookExhausted. // // Calling with maxMatches == 0 is ok - and expected when the order is a maker-only order. // function matchAgainstBook( uint128 orderId, uint theirPriceStart, uint theirPriceEnd, uint maxMatches ) internal returns ( MatchStopReason matchStopReason ) { Order storage order = orderForOrderId[orderId]; uint bmi = theirPriceStart / 256; // index into array of bitmaps uint bti = theirPriceStart % 256; // bit position within bitmap uint bmiEnd = theirPriceEnd / 256; // last bitmap to search uint btiEnd = theirPriceEnd % 256; // stop at this bit in the last bitmap uint cbm = occupiedPriceBitmaps[bmi]; // original copy of current bitmap uint dbm = cbm; // dirty version of current bitmap where we may have cleared bits uint wbm = cbm >> bti; // working copy of current bitmap which we keep shifting // Optimized loops could render a better matching engine yet! bool removedLastAtPrice; matchStopReason = MatchStopReason.None; while (bmi < bmiEnd) { if (wbm == 0 || bti == 256) { if (dbm != cbm) { occupiedPriceBitmaps[bmi] = dbm; } bti = 0; bmi++; cbm = occupiedPriceBitmaps[bmi]; wbm = cbm; dbm = cbm; } else { if ((wbm & 1) != 0) { // careful - copy-and-pasted in loop below ... (removedLastAtPrice, maxMatches, matchStopReason) = matchWithOccupiedPrice(order, uint16(bmi * 256 + bti), maxMatches); if (removedLastAtPrice) { dbm ^= 2 ** bti; } if (matchStopReason == MatchStopReason.PriceExhausted) { matchStopReason = MatchStopReason.None; } else if (matchStopReason != MatchStopReason.None) { // we might still have changes in dbm to write back - see later break; } } bti += 1; wbm /= 2; } } if (matchStopReason == MatchStopReason.None) { // we've reached the last bitmap we need to search, // we'll stop at btiEnd not 256 this time. while (bti <= btiEnd && wbm != 0) { if ((wbm & 1) != 0) { // careful - copy-and-pasted in loop above ... (removedLastAtPrice, maxMatches, matchStopReason) = matchWithOccupiedPrice(order, uint16(bmi * 256 + bti), maxMatches); if (removedLastAtPrice) { dbm ^= 2 ** bti; } if (matchStopReason == MatchStopReason.PriceExhausted) { matchStopReason = MatchStopReason.None; } else if (matchStopReason != MatchStopReason.None) { break; } } bti += 1; wbm /= 2; } } // Careful - if we exited the first loop early, or we went into the second loop, // (luckily can't both happen) then we haven't flushed the dirty bitmap back to // storage - do that now if we need to. if (dbm != cbm) { occupiedPriceBitmaps[bmi] = dbm; } if (matchStopReason == MatchStopReason.None) { matchStopReason = MatchStopReason.BookExhausted; } } // Internal Order Placement. // // Match our order against up to maxMatches resting orders at the given price (which // is known by the caller to have at least one resting order). // // The matches (partial or complete) of the resting orders are recorded, and their // funds are credited. // // The on chain orderbook with resting orders is updated, but the occupied price bitmap is NOT - // the caller must clear the relevant bit if removedLastAtPrice = true is returned. // // Only updates the executedBase and executedCntr of our order - caller is responsible // for e.g. crediting our matched funds, updating status. // // Calling with maxMatches == 0 is ok - and expected when the order is a maker-only order. // // Returns: // removedLastAtPrice: // true iff there are no longer any resting orders at this price - caller will need // to update the occupied price bitmap. // // matchesLeft: // maxMatches passed in minus the number of matches made by this call // // matchStopReason: // If our order is completely matched, matchStopReason will be Satisfied. // If our order is not completely matched, matchStopReason will be either: // MaxMatches (we are not allowed to match any more times) // or: // PriceExhausted (nothing left on the book at this exact price) // function matchWithOccupiedPrice( Order storage ourOrder, uint16 theirPrice, uint maxMatches ) internal returns ( bool removedLastAtPrice, uint matchesLeft, MatchStopReason matchStopReason) { matchesLeft = maxMatches; uint workingOurExecutedBase = ourOrder.executedBase; uint workingOurExecutedCntr = ourOrder.executedCntr; uint128 theirOrderId = orderChainForOccupiedPrice[theirPrice].firstOrderId; matchStopReason = MatchStopReason.None; while (true) { if (matchesLeft == 0) { matchStopReason = MatchStopReason.MaxMatches; break; } uint matchBase; uint matchCntr; (theirOrderId, matchBase, matchCntr, matchStopReason) = matchWithTheirs((ourOrder.sizeBase - workingOurExecutedBase), theirOrderId, theirPrice); workingOurExecutedBase += matchBase; workingOurExecutedCntr += matchCntr; matchesLeft -= 1; if (matchStopReason != MatchStopReason.None) { break; } } ourOrder.executedBase = uint128(workingOurExecutedBase); ourOrder.executedCntr = uint128(workingOurExecutedCntr); if (theirOrderId == 0) { orderChainForOccupiedPrice[theirPrice].firstOrderId = 0; orderChainForOccupiedPrice[theirPrice].lastOrderId = 0; removedLastAtPrice = true; } else { // NB: in some cases (e.g. maxMatches == 0) this is a no-op. orderChainForOccupiedPrice[theirPrice].firstOrderId = theirOrderId; orderChainNodeForOpenOrderId[theirOrderId].prevOrderId = 0; removedLastAtPrice = false; } } // Internal Order Placement. // // Match up to our remaining amount against a resting order in the book. // // The match (partial, complete or effectively-complete) of the resting order // is recorded, and their funds are credited. // // Their order is NOT removed from the book by this call - the caller must do that // if the nextTheirOrderId returned is not equal to the theirOrderId passed in. // // Returns: // // nextTheirOrderId: // If we did not completely match their order, will be same as theirOrderId. // If we completely matched their order, will be orderId of next order at the // same price - or zero if this was the last order and we've now filled it. // // matchStopReason: // If our order is completely matched, matchStopReason will be Satisfied. // If our order is not completely matched, matchStopReason will be either // PriceExhausted (if nothing left at this exact price) or None (if can continue). // function matchWithTheirs( uint ourRemainingBase, uint128 theirOrderId, uint16 theirPrice) internal returns ( uint128 nextTheirOrderId, uint matchBase, uint matchCntr, MatchStopReason matchStopReason) { Order storage theirOrder = orderForOrderId[theirOrderId]; uint theirRemainingBase = theirOrder.sizeBase - theirOrder.executedBase; if (ourRemainingBase < theirRemainingBase) { matchBase = ourRemainingBase; } else { matchBase = theirRemainingBase; } matchCntr = computeCntrAmountUsingPacked(matchBase, theirPrice); // It may seem a bit odd to stop here if our remaining amount is very small - // there could still be resting orders we can match it against. During network congestion gas // cost of matching each order can become quite high - potentially high enough to // wipe out the profit the taker hopes for from trading the tiny amount left. if ((ourRemainingBase - matchBase) < baseMinRemainingSize) { matchStopReason = MatchStopReason.Satisfied; } else { matchStopReason = MatchStopReason.None; } bool theirsDead = recordTheirMatch(theirOrder, theirOrderId, theirPrice, matchBase, matchCntr); if (theirsDead) { nextTheirOrderId = orderChainNodeForOpenOrderId[theirOrderId].nextOrderId; if (matchStopReason == MatchStopReason.None && nextTheirOrderId == 0) { matchStopReason = MatchStopReason.PriceExhausted; } } else { nextTheirOrderId = theirOrderId; } } // Internal Order Placement. // // Record match (partial or complete) of resting order, and credit them their funds. // // If their order is completely matched, the order is marked as done, // and "theirsDead" is returned as true. // // The order is NOT removed from the book by this call - the caller // must do that if theirsDead is true. // // No sanity checks are made - the caller must be sure the order is // not already done and has sufficient remaining. (Yes, we'd like to // check here too but we cannot afford the gas). // function recordTheirMatch( Order storage theirOrder, uint128 theirOrderId, uint16 theirPrice, uint matchBase, uint matchCntr ) internal returns (bool theirsDead) { // they are a maker so no fees // overflow safe - see comments about baseMaxSize // executedBase cannot go > sizeBase due to logic in matchWithTheirs theirOrder.executedBase += uint128(matchBase); theirOrder.executedCntr += uint128(matchCntr); if (isBuyPrice(theirPrice)) { // they have bought base (using the counter they already paid when creating the order) balanceBaseForClient[theirOrder.client] += matchBase; } else { // they have bought counter (using the base they already paid when creating the order) balanceCntrForClient[theirOrder.client] += matchCntr; } uint stillRemainingBase = theirOrder.sizeBase - theirOrder.executedBase; // avoid leaving tiny amounts in the book - refund remaining if too small if (stillRemainingBase < baseMinRemainingSize) { refundUnmatchedAndFinish(theirOrderId, Status.Done, ReasonCode.None); // someone building an UI on top needs to know how much was match and how much was refund MarketOrderEvent(block.timestamp, theirOrderId, MarketOrderEventType.CompleteFill, theirPrice, matchBase + stillRemainingBase, matchBase); return true; } else { MarketOrderEvent(block.timestamp, theirOrderId, MarketOrderEventType.PartialFill, theirPrice, matchBase, matchBase); return false; } } // Internal Order Placement. // // Refund any unmatched funds in an order (based on executed vs size) and move to a final state. // // The order is NOT removed from the book by this call and no event is raised. // // No sanity checks are made - the caller must be sure the order has not already been refunded. // function refundUnmatchedAndFinish(uint128 orderId, Status status, ReasonCode reasonCode) internal { Order storage order = orderForOrderId[orderId]; uint16 price = order.price; if (isBuyPrice(price)) { uint sizeCntr = computeCntrAmountUsingPacked(order.sizeBase, price); balanceCntrForClient[order.client] += sizeCntr - order.executedCntr; } else { balanceBaseForClient[order.client] += order.sizeBase - order.executedBase; } order.status = status; order.reasonCode = reasonCode; } // Internal Order Placement. // // Enter a not completely matched order into the book, marking the order as open. // // This updates the occupied price bitmap and chain. // // No sanity checks are made - the caller must be sure the order // has some unmatched amount and has been paid for! // function enterOrder(uint128 orderId) internal { Order storage order = orderForOrderId[orderId]; uint16 price = order.price; OrderChain storage orderChain = orderChainForOccupiedPrice[price]; OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId]; if (orderChain.firstOrderId == 0) { orderChain.firstOrderId = orderId; orderChain.lastOrderId = orderId; orderChainNode.nextOrderId = 0; orderChainNode.prevOrderId = 0; uint bitmapIndex = price / 256; uint bitIndex = price % 256; occupiedPriceBitmaps[bitmapIndex] |= (2 ** bitIndex); } else { uint128 existingLastOrderId = orderChain.lastOrderId; OrderChainNode storage existingLastOrderChainNode = orderChainNodeForOpenOrderId[existingLastOrderId]; orderChainNode.nextOrderId = 0; orderChainNode.prevOrderId = existingLastOrderId; existingLastOrderChainNode.nextOrderId = orderId; orderChain.lastOrderId = orderId; } MarketOrderEvent(block.timestamp, orderId, MarketOrderEventType.Add, price, order.sizeBase - order.executedBase, 0); order.status = Status.Open; } // Internal Order Placement. // // Charge the client for the cost of placing an order in the given direction. // // Return true if successful, false otherwise. // function debitFunds( address client, Direction direction, uint sizeBase, uint sizeCntr ) internal returns (bool success) { if (direction == Direction.Buy) { uint availableCntr = balanceCntrForClient[client]; if (availableCntr < sizeCntr) { return false; } balanceCntrForClient[client] = availableCntr - sizeCntr; return true; } else if (direction == Direction.Sell) { uint availableBase = balanceBaseForClient[client]; if (availableBase < sizeBase) { return false; } balanceBaseForClient[client] = availableBase - sizeBase; return true; } else { return false; } } // Public Book View // // Intended for public book depth enumeration from web3 (or similar). // // Not suitable for use from a smart contract transaction - gas usage // could be very high if we have many orders at the same price. // // Start at the given inclusive price (and side) and walk down the book // (getting less aggressive) until we find some open orders or reach the // least aggressive price. // // Returns the price where we found the order(s), the depth at that price // (zero if none found), order count there, and the current blockNumber. // // (The blockNumber is handy if you're taking a snapshot which you intend // to keep up-to-date with the market order events). // // To walk through the on-chain orderbook, the caller should start by calling walkBook with the // most aggressive buy price (Buy @ 999000). // If the price returned is the least aggressive buy price (Buy @ 0.000001), // the side is complete. // Otherwise, call walkBook again with the (packed) price returned + 1. // Then repeat for the sell side, starting with Sell @ 0.000001 and stopping // when Sell @ 999000 is returned. // function walkBook(uint16 fromPrice) public constant returns ( uint16 price, uint depthBase, uint orderCount, uint blockNumber ) { uint priceStart = fromPrice; uint priceEnd = (isBuyPrice(fromPrice)) ? minBuyPrice : maxSellPrice; // See comments in matchAgainstBook re: how these crazy loops work. uint bmi = priceStart / 256; uint bti = priceStart % 256; uint bmiEnd = priceEnd / 256; uint btiEnd = priceEnd % 256; uint wbm = occupiedPriceBitmaps[bmi] >> bti; while (bmi < bmiEnd) { if (wbm == 0 || bti == 256) { bti = 0; bmi++; wbm = occupiedPriceBitmaps[bmi]; } else { if ((wbm & 1) != 0) { // careful - copy-pasted in below loop price = uint16(bmi * 256 + bti); (depthBase, orderCount) = sumDepth(orderChainForOccupiedPrice[price].firstOrderId); return (price, depthBase, orderCount, block.number); } bti += 1; wbm /= 2; } } // we've reached the last bitmap we need to search, stop at btiEnd not 256 this time. while (bti <= btiEnd && wbm != 0) { if ((wbm & 1) != 0) { // careful - copy-pasted in above loop price = uint16(bmi * 256 + bti); (depthBase, orderCount) = sumDepth(orderChainForOccupiedPrice[price].firstOrderId); return (price, depthBase, orderCount, block.number); } bti += 1; wbm /= 2; } return (uint16(priceEnd), 0, 0, block.number); } // Internal Book View. // // See walkBook - adds up open depth at a price starting from an // order which is assumed to be open. Careful - unlimited gas use. // function sumDepth(uint128 orderId) internal constant returns (uint depth, uint orderCount) { while (true) { Order storage order = orderForOrderId[orderId]; depth += order.sizeBase - order.executedBase; orderCount++; orderId = orderChainNodeForOpenOrderId[orderId].nextOrderId; if (orderId == 0) { return (depth, orderCount); } } } } // helper for automating book creation contract OnChainOrderBookV012bFactory { event BookCreated (address bookAddress); function OnChainOrderBookV012bFactory() { } function createBook(ERC20 _baseToken, ERC20 _rwrdToken, address _feeCollector, uint _baseMinInitialSize, int8 _minPriceExponent) public { OnChainOrderBookV012b book = new OnChainOrderBookV012b(); book.init(_baseToken, _rwrdToken, _baseMinInitialSize, _minPriceExponent); book.changeFeeCollector(_feeCollector); BookCreated(address(book)); } }
Public Info View - what is being traded here, what are the limits?
function getBookInfo() public constant returns ( BookType _bookType, address _baseToken, address _rwrdToken, uint _baseMinInitialSize, uint _cntrMinInitialSize, int8 _minPriceExponent, uint _feeDivisor, address _feeCollector ) { return ( BookType.ERC20EthV1, address(baseToken), address(rwrdToken), cntrMinInitialSize, minPriceExponent, feeDivisor, feeCollector ); }
914,655
pragma solidity ^0.4.23; // ---------------------------------------------------------------------------- // ERC20Interface - Standard ERC20 Interface Definition // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Based on the final ERC20 specification at: // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function name() public view returns (string); function symbol() public view returns (string); function decimals() public view returns (uint8); function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 balance); function allowance(address _owner, address _spender) public view returns (uint256 remaining); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } // ---------------------------------------------------------------------------- // Math - General Math Utility Library // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- library Math { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 r = a + b; require(r >= a); return r; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 r = a * b; require(r / a == b); return r; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } } // ---------------------------------------------------------------------------- // Owned - Ownership model with 2 phase transfers // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- // Implements a simple ownership model with 2-phase transfer. contract Owned { address public owner; address public proposedOwner; event OwnershipTransferInitiated(address indexed _proposedOwner); event OwnershipTransferCompleted(address indexed _newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(isOwner(msg.sender) == true); _; } function isOwner(address _address) public view returns (bool) { return (_address == owner); } function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) { require(_proposedOwner != address(0)); require(_proposedOwner != address(this)); require(_proposedOwner != owner); proposedOwner = _proposedOwner; emit OwnershipTransferInitiated(proposedOwner); return true; } function completeOwnershipTransfer() public returns (bool) { require(msg.sender == proposedOwner); owner = msg.sender; proposedOwner = address(0); emit OwnershipTransferCompleted(owner); return true; } } // ---------------------------------------------------------------------------- // Finalizable - Basic implementation of the finalization pattern // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- contract Finalizable is Owned() { bool public finalized; event Finalized(); constructor() public { finalized = false; } function finalize() public onlyOwner returns (bool) { require(!finalized); finalized = true; emit Finalized(); return true; } } // ---------------------------------------------------------------------------- // OpsManaged - Implements an Owner and Ops Permission Model // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- // // Implements a security model with owner and ops. // contract OpsManaged is Owned() { address public opsAddress; event OpsAddressUpdated(address indexed _newAddress); constructor() public { } modifier onlyOwnerOrOps() { require(isOwnerOrOps(msg.sender)); _; } function isOps(address _address) public view returns (bool) { return (opsAddress != address(0) && _address == opsAddress); } function isOwnerOrOps(address _address) public view returns (bool) { return (isOwner(_address) || isOps(_address)); } function setOpsAddress(address _newOpsAddress) public onlyOwner returns (bool) { require(_newOpsAddress != owner); require(_newOpsAddress != address(this)); opsAddress = _newOpsAddress; emit OpsAddressUpdated(opsAddress); return true; } } // ---------------------------------------------------------------------------- // ERC20Token - Standard ERC20 Implementation // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- contract ERC20Token is ERC20Interface { using Math for uint256; string private tokenName; string private tokenSymbol; uint8 private tokenDecimals; uint256 internal tokenTotalSupply; mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) allowed; constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply, address _initialTokenHolder) public { tokenName = _name; tokenSymbol = _symbol; tokenDecimals = _decimals; tokenTotalSupply = _totalSupply; // The initial balance of tokens is assigned to the given token holder address. balances[_initialTokenHolder] = _totalSupply; // Per EIP20, the constructor should fire a Transfer event if tokens are assigned to an account. emit Transfer(0x0, _initialTokenHolder, _totalSupply); } function name() public view returns (string) { return tokenName; } function symbol() public view returns (string) { return tokenSymbol; } function decimals() public view returns (uint8) { return tokenDecimals; } function totalSupply() public view returns (uint256) { return tokenTotalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function transfer(address _to, uint256 _value) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } } // ---------------------------------------------------------------------------- // FinalizableToken - Extension to ERC20Token with ops and finalization // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- // // ERC20 token with the following additions: // 1. Owner/Ops Ownership // 2. Finalization // contract FinalizableToken is ERC20Token, OpsManaged, Finalizable { using Math for uint256; // The constructor will assign the initial token supply to the owner (msg.sender). constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public ERC20Token(_name, _symbol, _decimals, _totalSupply, msg.sender) OpsManaged() Finalizable() { } function transfer(address _to, uint256 _value) public returns (bool success) { validateTransfer(msg.sender, _to); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { validateTransfer(msg.sender, _to); return super.transferFrom(_from, _to, _value); } function validateTransfer(address _sender, address _to) private view { // Once the token is finalized, everybody can transfer tokens. if (finalized) { return; } if (isOwner(_to)) { return; } // Before the token is finalized, only owner and ops are allowed to initiate transfers. // This allows them to move tokens while the sale is still ongoing for example. require(isOwnerOrOps(_sender)); } } // ---------------------------------------------------------------------------- // FlexibleTokenSale - Token Sale Contract // Enuma Blockchain Platform // // Copyright (c) 2017 Enuma Technologies Limited. // https://www.enuma.io/ // ---------------------------------------------------------------------------- contract FlexibleTokenSale is Finalizable, OpsManaged { using Math for uint256; // // Lifecycle // uint256 public startTime; uint256 public endTime; bool public suspended; // // Pricing // uint256 public tokensPerKEther; uint256 public bonus; uint256 public maxTokensPerAccount; uint256 public contributionMin; uint256 public tokenConversionFactor; // // Wallets // address public walletAddress; // // Token // FinalizableToken public token; // // Counters // uint256 public totalTokensSold; uint256 public totalEtherCollected; // // Events // event Initialized(); event TokensPerKEtherUpdated(uint256 _newValue); event MaxTokensPerAccountUpdated(uint256 _newMax); event BonusUpdated(uint256 _newValue); event SaleWindowUpdated(uint256 _startTime, uint256 _endTime); event WalletAddressUpdated(address _newAddress); event SaleSuspended(); event SaleResumed(); event TokensPurchased(address _beneficiary, uint256 _cost, uint256 _tokens); event TokensReclaimed(uint256 _amount); constructor(uint256 _startTime, uint256 _endTime, address _walletAddress) public OpsManaged() { require(_endTime > _startTime); require(_walletAddress != address(0)); require(_walletAddress != address(this)); walletAddress = _walletAddress; finalized = false; suspended = false; startTime = _startTime; endTime = _endTime; // Use some defaults config values. Classes deriving from FlexibleTokenSale // should set their own defaults tokensPerKEther = 100000; bonus = 0; maxTokensPerAccount = 0; contributionMin = 0.1 ether; totalTokensSold = 0; totalEtherCollected = 0; } function currentTime() public constant returns (uint256) { return now; } // Initialize should be called by the owner as part of the deployment + setup phase. // It will associate the sale contract with the token contract and perform basic checks. function initialize(FinalizableToken _token) external onlyOwner returns(bool) { require(address(token) == address(0)); require(address(_token) != address(0)); require(address(_token) != address(this)); require(address(_token) != address(walletAddress)); require(isOwnerOrOps(address(_token)) == false); token = _token; // This factor is used when converting cost <-> tokens. // 18 is because of the ETH -> Wei conversion. // 3 because prices are in K ETH instead of just ETH. // 4 because bonuses are expressed as 0 - 10000 for 0.00% - 100.00% (with 2 decimals). tokenConversionFactor = 10**(uint256(18).sub(_token.decimals()).add(3).add(4)); require(tokenConversionFactor > 0); emit Initialized(); return true; } // // Owner Configuation // // Allows the owner to change the wallet address which is used for collecting // ether received during the token sale. function setWalletAddress(address _walletAddress) external onlyOwner returns(bool) { require(_walletAddress != address(0)); require(_walletAddress != address(this)); require(_walletAddress != address(token)); require(isOwnerOrOps(_walletAddress) == false); walletAddress = _walletAddress; emit WalletAddressUpdated(_walletAddress); return true; } // Allows the owner to set an optional limit on the amount of tokens that can be purchased // by a contributor. It can also be set to 0 to remove limit. function setMaxTokensPerAccount(uint256 _maxTokens) external onlyOwner returns(bool) { maxTokensPerAccount = _maxTokens; emit MaxTokensPerAccountUpdated(_maxTokens); return true; } // Allows the owner to specify the conversion rate for ETH -> tokens. // For example, passing 1,000,000 would mean that 1 ETH would purchase 1000 tokens. function setTokensPerKEther(uint256 _tokensPerKEther) external onlyOwner returns(bool) { require(_tokensPerKEther > 0); tokensPerKEther = _tokensPerKEther; emit TokensPerKEtherUpdated(_tokensPerKEther); return true; } // Allows the owner to set a bonus to apply to all purchases. // For example, setting it to 2000 means that instead of receiving 200 tokens, // for a given price, contributors would receive 240 tokens (20.00% bonus). function setBonus(uint256 _bonus) external onlyOwner returns(bool) { require(_bonus <= 10000); bonus = _bonus; emit BonusUpdated(_bonus); return true; } // Allows the owner to set a sale window which will allow the sale (aka buyTokens) to // receive contributions between _startTime and _endTime. Once _endTime is reached, // the sale contract will automatically stop accepting incoming contributions. function setSaleWindow(uint256 _startTime, uint256 _endTime) external onlyOwner returns(bool) { require(_startTime > 0); require(_endTime > _startTime); startTime = _startTime; endTime = _endTime; emit SaleWindowUpdated(_startTime, _endTime); return true; } // Allows the owner to suspend the sale until it is manually resumed at a later time. function suspend() external onlyOwner returns(bool) { if (suspended == true) { return false; } suspended = true; emit SaleSuspended(); return true; } // Allows the owner to resume the sale. function resume() external onlyOwner returns(bool) { if (suspended == false) { return false; } suspended = false; emit SaleResumed(); return true; } // // Contributions // // Default payable function which can be used to purchase tokens. function () payable public { buyTokens(msg.sender); } // Allows the caller to purchase tokens for a specific beneficiary (proxy purchase). function buyTokens(address _beneficiary) public payable returns (uint256) { return buyTokensInternal(_beneficiary, bonus); } function buyTokensInternal(address _beneficiary, uint256 _bonus) internal returns (uint256) { require(!finalized); require(!suspended); require(currentTime() >= startTime); require(currentTime() <= endTime); require(msg.value >= contributionMin); require(_beneficiary != address(0)); require(_beneficiary != address(this)); require(_beneficiary != address(token)); // We don't want to allow the wallet collecting ETH to // directly be used to purchase tokens. require(msg.sender != address(walletAddress)); // Check how many tokens are still available for sale. uint256 saleBalance = token.balanceOf(address(this)); require(saleBalance > 0); // Calculate how many tokens the contributor could purchase based on ETH received. uint256 tokens = msg.value.mul(tokensPerKEther).mul(_bonus.add(10000)).div(tokenConversionFactor); require(tokens > 0); uint256 cost = msg.value; uint256 refund = 0; // Calculate what is the maximum amount of tokens that the contributor // should be allowed to purchase uint256 maxTokens = saleBalance; if (maxTokensPerAccount > 0) { // There is a maximum amount of tokens per account in place. // Check if the user already hit that limit. uint256 userBalance = getUserTokenBalance(_beneficiary); require(userBalance < maxTokensPerAccount); uint256 quotaBalance = maxTokensPerAccount.sub(userBalance); if (quotaBalance < saleBalance) { maxTokens = quotaBalance; } } require(maxTokens > 0); if (tokens > maxTokens) { // The contributor sent more ETH than allowed to purchase. // Limit the amount of tokens that they can purchase in this transaction. tokens = maxTokens; // Calculate the actual cost for that new amount of tokens. cost = tokens.mul(tokenConversionFactor).div(tokensPerKEther.mul(_bonus.add(10000))); if (msg.value > cost) { // If the contributor sent more ETH than needed to buy the tokens, // the balance should be refunded. refund = msg.value.sub(cost); } } // This is the actual amount of ETH that can be sent to the wallet. uint256 contribution = msg.value.sub(refund); walletAddress.transfer(contribution); // Update our stats counters. totalTokensSold = totalTokensSold.add(tokens); totalEtherCollected = totalEtherCollected.add(contribution); // Transfer tokens to the beneficiary. require(token.transfer(_beneficiary, tokens)); // Issue a refund for the excess ETH, as needed. if (refund > 0) { msg.sender.transfer(refund); } emit TokensPurchased(_beneficiary, cost, tokens); return tokens; } // Returns the number of tokens that the user has purchased. Will be checked against the // maximum allowed. Can be overriden in a sub class to change the calculations. function getUserTokenBalance(address _beneficiary) internal view returns (uint256) { return token.balanceOf(_beneficiary); } // Allows the owner to take back the tokens that are assigned to the sale contract. function reclaimTokens() external onlyOwner returns (bool) { uint256 tokens = token.balanceOf(address(this)); if (tokens == 0) { return false; } address tokenOwner = token.owner(); require(tokenOwner != address(0)); require(token.transfer(tokenOwner, tokens)); emit TokensReclaimed(tokens); return true; } } // ---------------------------------------------------------------------------- // CaspianTokenConfig - Token Contract Configuration // // Copyright (c) 2018 Caspian, Limited (TM). // http://www.caspian.tech/ // ---------------------------------------------------------------------------- contract CaspianTokenConfig { string public constant TOKEN_SYMBOL = "CSP"; string public constant TOKEN_NAME = "Caspian Token"; uint8 public constant TOKEN_DECIMALS = 18; uint256 public constant DECIMALSFACTOR = 10**uint256(TOKEN_DECIMALS); uint256 public constant TOKEN_TOTALSUPPLY = 1000000000 * DECIMALSFACTOR; } // ---------------------------------------------------------------------------- // CaspianTokenSaleConfig - Token Sale Configuration // // Copyright (c) 2018 Caspian, Limited (TM). // http://www.caspian.tech/ // ---------------------------------------------------------------------------- contract CaspianTokenSaleConfig is CaspianTokenConfig { // // Time // uint256 public constant INITIAL_STARTTIME = 1538553600; // 2018-10-03, 08:00:00 UTC uint256 public constant INITIAL_ENDTIME = 1538726400; // 2018-10-05, 08:00:00 UTC // // Purchases // // Minimum amount of ETH that can be used for purchase. uint256 public constant CONTRIBUTION_MIN = 0.5 ether; // Price of tokens, based on the 1 ETH = 4000 CSP conversion ratio. uint256 public constant TOKENS_PER_KETHER = 4000000; // Amount of bonus applied to the sale. 2000 = 20.00% bonus, 750 = 7.50% bonus, 0 = no bonus. uint256 public constant BONUS = 0; // Maximum amount of tokens that can be purchased for each account. 0 for no maximum. uint256 public constant TOKENS_ACCOUNT_MAX = 400000 * DECIMALSFACTOR; // 100 ETH Max } // ---------------------------------------------------------------------------- // CaspianTokenSale - Token Sale Contract // // Copyright (c) 2018 Caspian, Limited (TM). // http://www.caspian.tech/ // // Based on code from Enuma Technologies. // Copyright (c) 2017 Enuma Technologies Limited. // ---------------------------------------------------------------------------- contract CaspianTokenSale is FlexibleTokenSale, CaspianTokenSaleConfig { // // Whitelist // uint8 public currentPhase; mapping(address => uint8) public whitelist; // // Events // event WhitelistUpdated(address indexed _account, uint8 _phase); constructor(address wallet) public FlexibleTokenSale(INITIAL_STARTTIME, INITIAL_ENDTIME, wallet) { tokensPerKEther = TOKENS_PER_KETHER; bonus = BONUS; maxTokensPerAccount = TOKENS_ACCOUNT_MAX; contributionMin = CONTRIBUTION_MIN; currentPhase = 1; } // Allows the owner or ops to add/remove people from the whitelist. function updateWhitelist(address _address, uint8 _phase) external onlyOwnerOrOps returns (bool) { return updateWhitelistInternal(_address, _phase); } function updateWhitelistInternal(address _address, uint8 _phase) internal returns (bool) { require(_address != address(0)); require(_address != address(this)); require(_address != walletAddress); require(_phase <= 1); whitelist[_address] = _phase; emit WhitelistUpdated(_address, _phase); return true; } // Allows the owner or ops to add/remove people from the whitelist, in batches. function updateWhitelistBatch(address[] _addresses, uint8 _phase) external onlyOwnerOrOps returns (bool) { require(_addresses.length > 0); for (uint256 i = 0; i < _addresses.length; i++) { require(updateWhitelistInternal(_addresses[i], _phase)); } return true; } // This is an extension to the buyToken function in FlexibleTokenSale which also takes // care of checking contributors against the whitelist. Since buyTokens supports proxy payments // we check that both the sender and the beneficiary have been whitelisted. function buyTokensInternal(address _beneficiary, uint256 _bonus) internal returns (uint256) { require(whitelist[msg.sender] >= currentPhase); require(whitelist[_beneficiary] >= currentPhase); return super.buyTokensInternal(_beneficiary, _bonus); } }
Allows the owner to change the wallet address which is used for collecting ether received during the token sale.
function setWalletAddress(address _walletAddress) external onlyOwner returns(bool) { require(_walletAddress != address(0)); require(_walletAddress != address(this)); require(_walletAddress != address(token)); require(isOwnerOrOps(_walletAddress) == false); walletAddress = _walletAddress; emit WalletAddressUpdated(_walletAddress); return true; }
14,515,407
./full_match/1/0xE8c1B97913cB46BB8741e6FA483717Ea89FfC56d/sources/contracts/TeaVaultV2.sol
Withdraw ERC721 tokens Only the investor can do this _token address of the NFT _tokenId the NFT to withdraw
function withdraw721(address _recipient, address _token, uint256 _tokenId) external nonReentrant onlyInvestor { if (_recipient == address(0)) revert InvalidRecipientAddress(); IERC721(_token).safeTransferFrom(address(this), _recipient, _tokenId); emit Token721Withdrawed(msg.sender, _recipient, _token, _tokenId); }
3,870,437
./partial_match/1/0x66bB9D104c55861feb3Ec3559433F01f6373c966/sources/contracts/FXPool.sol
Set emergency alarm _emergency turn on or off
function setEmergency(bool _emergency) external onlyOwner { emergency = _emergency; emit EmergencyAlarm(_emergency); }
15,919,434
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@chainlink/contracts/src/v0.6/interfaces/KeeperCompatibleInterface.sol"; import "./LendingService.sol"; import "./TokenSwapService.sol"; import "./utils/PriceFeedHelper.sol"; import "hardhat/console.sol"; /** @notice ==================== MARKET NEUTRAL PAIRS TRADING STRATEGY ========================= * Aims to profit regardless of broader market's trend; * Takes simultaneous long/short positions to extract alpha and eliminate beta! * After activating this trading BOT, trader will have tokensForLong in the lending pool; and * tokenForShort-swapped-into stable coins in the wallet * Should the pairs' price go as expected, profit will be made after BOT is ended; and * the performance is not affected by the general market condition within the pairs' sector * ============================================================================================= */ contract MarketNeutralPairsTradingBot is Ownable, KeeperCompatibleInterface { using SafeERC20 for IERC20; using SafeMath for uint; using SafeMath for uint256; /// The following are Aave V2's token tracker addreses on Kovan address constant Kovan_Aave_ETHUSD = 0x4281eCF07378Ee595C564a59048801330f3084eE; address constant Kovan_Aave_SNXUSD = 0x7FDb81B0b8a010dd4FFc57C3fecbf145BA8Bd947; address constant Kovan_Aave_LINKUSD = 0xAD5ce863aE3E4E9394Ab43d4ba0D80f419F61789; address constant Kovan_Aave_DAIUSD = 0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD; /// The following are Uniswap's token tracker address on Kovan address constant Kovan_Uniswap_LINKUSD = 0xa36085F69e2889c224210F603D836748e7dC0088; // Chainlink Kovan faucet too address constant Kovan_Uniswap_DAIUSD = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; address public trader; /// Stable coin tokens are used to faciliate the synthetic short leg /// Use DAI for now address public tokenStableCoin; uint256 private tradeAmountForLong; uint256 private tradeAmountForShort; address public tokenUsedToPay; address private tokenForLong; address private tokenForShort; /// How much time to keep the BOT running until call it stop (i.e. 1 week) uint256 private stopBotTimeLapse; uint256 private stopBotProfitTarget; uint256 private stopBotStopLossThreshold; uint256 private leverageRatio; uint256 public platformFee; /// Set the deadline to be wait time allowed to derive the Unix timestamp after which the transaction will revert uint256 public swapDeadlineBeforeRevert; LendingService public lendingService; TokenSwapService public tokenSwapService; uint256 private startBotTimestamp; bool private isPaymentTokenTheSameAsLongToken; uint256 private finalPnL; PriceFeedHelper public priceFeedHelper; /// Event logs event LogActivateBot(address _trader, address _tokenUsedToPay, address _tokenForLong, address _tokenForShort, uint256 _tradeAmountForLong, uint256 _startBotTimestamp, uint256 _stopBotTimeLapse); event LogStopBot(address _trader, address _tokenForLong, address _tokenForShort, uint256 _stopBotTimeLapse, uint256 _totalAmountIn); /** * @dev Constructor -- will be called once trader is done with all data input * and clicks on "Save Bot" button */ constructor( uint256 _tradeAmountForLong, address _tokenUsedToPay, address _tokenForLong, address _tokenForShort, uint256 _stopBotTimeLapse, uint256 _stopBotProfitTarget, uint256 _stopBotStopLossThreshold, uint256 _leverageRatio ) public { require(_tradeAmountForLong > 0, "Trade amount must be greater than zero"); require(_tokenUsedToPay != address(0), "Payment Token address cannot be the zero address"); require(_tokenForLong != address(0), "Long Token address cannot be the zero address"); require(_tokenForShort != address(0), "Short Token address cannot be the zero address"); require(_tokenForShort != _tokenForLong, "Short Token address cannot be the same as Long Token address"); require(_stopBotTimeLapse > 0, "Bot ending time cannot be earlier than now"); trader = msg.sender; /// Use some hardcoded addresses for testing purposes tokenStableCoin = Kovan_Uniswap_DAIUSD; tradeAmountForLong = _tradeAmountForLong; tokenUsedToPay = _tokenUsedToPay; tokenForLong = Kovan_Aave_SNXUSD; tokenForShort = Kovan_Uniswap_LINKUSD; stopBotTimeLapse = _stopBotTimeLapse; stopBotProfitTarget = 0; /// Default to zero for now stopBotStopLossThreshold = 0; /// Default to zero for now leverageRatio = 1; /// Default to 1 for now platformFee = 0; /// Assuming zero fee for now; Update to final fee later swapDeadlineBeforeRevert = 20 * 60 seconds; /// Assuming 20min for now; Update to user input later lendingService = new LendingService(tokenForLong, tokenForShort); tokenSwapService = new TokenSwapService(); isPaymentTokenTheSameAsLongToken = (_tokenUsedToPay != _tokenForLong) ? false : true; priceFeedHelper = new PriceFeedHelper(); } /** * @notice Implementing Chainlink keepers checkUpkeep function * @dev Only time-based stopBot condition is implemented for now * Will implement profit target and stop-loss based conditions later */ function checkUpkeep(bytes calldata /* checkData */) external override returns (bool, bytes memory) { bool upkeepNeeded; if (block.timestamp >= (stopBotTimeLapse + startBotTimestamp)) { upkeepNeeded = true; } return (upkeepNeeded, bytes("")); } /** * @notice Implementing Chainlink keepers performUpkeep function */ function performUpkeep(bytes calldata performData) external override { stopBot(); } /** * @notice ============================= STEPS TO ACTIVATE TRADING BOT ================================= * LONG LEG: * 1) If tokenForLong is different than payment token * => Use an AMM to swap payment token for tokenForLong * Else * => No swap necessary; directly use payment token for deposit * 2) Deposit net amount of tokenForLong to a lenging pool * 3) Just hold & earn yield passively; And use as collateral to boroow * SHORT LEG: * 1) Borrow tokenForShort from the same lending pool (use tokenForLong as collateral) * 2) Use an AMM to swap tokenForShort for stable coin (DAI or USDC for example) * 3) OPTIONAL: Deposit or stake the stable coins obtained to earn additional yield * * @notice ============================== STEPS TO STOP TRADING BOT ==================================== * SHORT LEG UNWIND: * 1) OPTIONAL: Withdraw or unstake the stable coins * 2) Use an AMM to swap the stable coins back into tokenForShort * Either we get more than we borrowed * (price of tokenForShort went down, we take profit), * Or need to get additional stable coins to have enough to repay lending pool * (price of tokenForShort went up, we take loss) * 3) Repay total borrowed tokenForShort (+ interest) to the lending pool used * LONG LEG UNWIND: * Withdraw tokenForLong from Aave (total deposited amount + yield earned) * * @notice ============================= TRADE PARAMS USED CURRENTLY ==================================== * For POC demo purposes * ETH is only used as gas fee; assuming tokenUsedToPay is an non-ETH ERC20 token - i.e. DAI * Use SNXUSD as tokenForLong * Use LINKUSD as tokenForShort * Use DAIUSD as the stable coin to swap to/from the borrowed tokenForShort * Use Aave V2 lending pool for deposit/borrow services * Use Uniswap V2 AMM pool for token swap services * * ===================================================================================================== */ /** * @dev function activeBot() -- Will be called after trader clicks "Activate Bot" button * on the Bot confirmation screen */ function activateBot() public onlyOwner { /// Set Bot starting time to now startBotTimestamp = block.timestamp; /// Transfers tradeAmount from trader to this smart contract IERC20(tokenUsedToPay).safeTransferFrom(trader, address(this), tradeAmountForLong); /// To Be Implemented later: A better way to handle gas fees uint256 netAmount = tradeAmountForLong - platformFee; /// ================================================================== /// ** The Long Leg ** /// ================================================================== /// Approve net amount transfer for token swap service IERC20(tokenUsedToPay).safeApprove(address(tokenSwapService), netAmount); /// First, swap payment token into tokenForLong if needed, via AMM pool if (!isPaymentTokenTheSameAsLongToken) { tokenSwapService.tradeOnUniswapV2( tokenUsedToPay, tokenForLong, priceFeedHelper.getLatestPrice("DAIUSD"), priceFeedHelper.getLatestPrice("SNXUSD"), netAmount, 0, address(this), (swapDeadlineBeforeRevert + block.timestamp) ); /// Approve transfer of swapped tokenForLong for the lending service IERC20(tokenForLong).safeApprove( address(lendingService), IERC20(tokenForLong).balanceOf(address(this)) ); /// Deposit net trade amount of tokenForLong via the lending service lendingService.deposit( IERC20(tokenForLong).balanceOf(address(this)), address(this) ); } else { /// Approve net amount transfer of tokenForLong for the lending service IERC20(tokenForLong).safeApprove(address(lendingService), netAmount); /// Deposit net trade amount of tokenForLong via the lending service lendingService.deposit(netAmount, address(this)); } /// ================================================================== /// ** The Short Leg ** /// ================================================================== /// Use viable interest rate mode for now which means first param value = 2 lendingService.borrow(2, address(this)); /// Swap borrowed tokenForShort for stable coin (DAI is used here) tokenSwapService.tradeOnUniswapV2( tokenForShort, tokenStableCoin, priceFeedHelper.getLatestPrice("LINKUSD"), priceFeedHelper.getLatestPrice("DAIUSD"), IERC20(tokenForShort).balanceOf(address(this)), 0, address(this), (swapDeadlineBeforeRevert + block.timestamp) ); /// TO Be Implemented later: Deposit or stake the stable coins obtained to earn additional yield emit LogActivateBot(trader, tokenUsedToPay, tokenForLong, tokenForShort, tradeAmountForLong, startBotTimestamp, stopBotTimeLapse); } /** * @dev function stopBot() -- Will be called from potentially any 1 out of the 3 pre-defined conditions: * Condition 1) Time based: * Bot stops when block time reaches stopBotTimeLapse + startBotTimestamp; * Condition 2) Profit target based: * Bot stops when trading profit reaches profit target * Condition 3) Stoploss threshold based: * Bot stops when trade mark-to-market positions exceeds predefined stoploss threshold * For example, the threshold could be set at 5% above lending pool liquidation threshold, * to avoid lending pool positions getting liquidated if price went against prediction * @dev The current POC only implemented the time-based condition; * The other 2 conditions to be implemented later * @dev Successfully integrated with Chainlink keepers to stop Bot automatically :) */ function stopBot() internal { /// =========================================================== /// ** STEP 1 -- Swap stable coins back into tokenForShort ** /// =========================================================== uint256 amountToSwap; uint256 availStableCoin = IERC20(tokenStableCoin).balanceOf(address(this)); uint256 tokenForShortAmountToGetBack = SafeMath.div( SafeMath.mul(availStableCoin, priceFeedHelper.getLatestPrice("DAIUSD")), priceFeedHelper.getLatestPrice("LINKUSD") ); /// Check if there's enough amount of tokenForShort to pay back lending pool bool enoughToPayBack = (tokenForShortAmountToGetBack >= lendingService.getBorrowedBalance(address(this))) ? true : false; if (enoughToPayBack) { amountToSwap = availStableCoin; } else { uint256 amountShortage = SafeMath.sub(lendingService.getBorrowedBalance(address(this)), tokenForShortAmountToGetBack); uint256 additionalStableCoinNeeded = SafeMath.div( SafeMath.mul(amountShortage, priceFeedHelper.getLatestPrice("LINKUSD")), priceFeedHelper.getLatestPrice("DAIUSD") ); /// Transfer additional stable coins needed to repay from trader to this contract IERC20(tokenStableCoin).safeTransferFrom(trader, address(this), additionalStableCoinNeeded); amountToSwap = IERC20(tokenStableCoin).balanceOf(address(this)); tokenSwapService.tradeOnUniswapV2( tokenStableCoin, tokenForShort, priceFeedHelper.getLatestPrice("DAIUSD"), priceFeedHelper.getLatestPrice("LINKUSD"), amountToSwap, 0, address(this), (swapDeadlineBeforeRevert + block.timestamp) ); } /// ==================================================================================== /// ** STEP 2 - Repay total borrowed tokenForShort (+ interest) to the lending pool ** /// ==================================================================================== uint256 finalAmountRepaid = lendingService.repay(2, address(this)); /// ======================================================================================= /// ** STEP 3 - Withdraw deposited tokenForLong (+ yield earned) from the lending pool ** /// ======================================================================================= uint256 finalAmountWithdrawn = lendingService.withdraw(lendingService.getDepositedBalance(address(this)), address(this)); emit LogStopBot(trader, tokenForLong, tokenForShort, stopBotTimeLapse, tradeAmountForLong); } }
function stopBot() -- Will be called from potentially any 1 out of the 3 pre-defined conditions: Condition 1) Time based: Bot stops when block time reaches stopBotTimeLapse + startBotTimestamp; Condition 2) Profit target based: Bot stops when trading profit reaches profit target Condition 3) Stoploss threshold based: Bot stops when trade mark-to-market positions exceeds predefined stoploss threshold For example, the threshold could be set at 5% above lending pool liquidation threshold, to avoid lending pool positions getting liquidated if price went against prediction The current POC only implemented the time-based condition; The other 2 conditions to be implemented later Successfully integrated with Chainlink keepers to stop Bot automatically :)/ =========================================================== STEP 1 -- Swap stable coins back into tokenForShort =========================================================== Check if there's enough amount of tokenForShort to pay back lending pool
function stopBot() internal { uint256 amountToSwap; uint256 availStableCoin = IERC20(tokenStableCoin).balanceOf(address(this)); uint256 tokenForShortAmountToGetBack = SafeMath.div( SafeMath.mul(availStableCoin, priceFeedHelper.getLatestPrice("DAIUSD")), priceFeedHelper.getLatestPrice("LINKUSD") ); bool enoughToPayBack = (tokenForShortAmountToGetBack >= lendingService.getBorrowedBalance(address(this))) ? true : false; if (enoughToPayBack) { amountToSwap = availStableCoin; uint256 amountShortage = SafeMath.sub(lendingService.getBorrowedBalance(address(this)), tokenForShortAmountToGetBack); uint256 additionalStableCoinNeeded = SafeMath.div( SafeMath.mul(amountShortage, priceFeedHelper.getLatestPrice("LINKUSD")), priceFeedHelper.getLatestPrice("DAIUSD") ); IERC20(tokenStableCoin).safeTransferFrom(trader, address(this), additionalStableCoinNeeded); amountToSwap = IERC20(tokenStableCoin).balanceOf(address(this)); tokenSwapService.tradeOnUniswapV2( tokenStableCoin, tokenForShort, priceFeedHelper.getLatestPrice("DAIUSD"), priceFeedHelper.getLatestPrice("LINKUSD"), amountToSwap, 0, address(this), (swapDeadlineBeforeRevert + block.timestamp) ); emit LogStopBot(trader, tokenForLong, tokenForShort, stopBotTimeLapse, tradeAmountForLong); }
12,768,846
// SPDX-License-Identifier: MIT pragma solidity =0.6.6; pragma experimental ABIEncoderV2; import '../interfaces/IApeRouter02.sol'; import '../interfaces/IApeFactory.sol'; import '../interfaces/IApePair.sol'; import '../utils/SweeperUpgradeable.sol'; /// @title LP fee manager /// @author ApeSwap.finance /// @notice Swap LP token fees collected to different token contract LPFeeManagerV2 is SweeperUpgradeable { IApeRouter02 public router; IApeFactory public factory; event LiquidityRemoved(address indexed pairAddress, uint256 amountA, uint256 amountB); event LiquidityRemovalFailed(address indexed pairAddress); event Swap(uint256 amountIn, uint256 amountOut, address[] path); event SwapFailed(uint256 amountIn, uint256 amountOut, address[] path); function initialize( address _router ) external initializer { __Ownable_init(); router = IApeRouter02(_router); factory = IApeFactory(router.factory()); // Setup Sweeper to allow native withdraws allowNativeSweep = true; } /// @notice Remove LP and unwrap to base tokens /// @param _lpTokens address list of LP tokens to unwrap /// @param _amounts Amount of each LP token to sell /// @param _token0Outs Minimum token 0 output requested. /// @param _token1Outs Minimum token 1 output requested. /// @param _to address the tokens need to be transferred to. /// @param _revertOnFailure If false, the tx will not revert on liquidity removal failures function removeLiquidityTokens( address[] calldata _lpTokens, uint256[] calldata _amounts, uint256[] calldata _token0Outs, uint256[] calldata _token1Outs, address _to, bool _revertOnFailure ) external onlyOwner { address toAddress = _to == address(0) ? address(this) : _to; for (uint256 i = 0; i < _lpTokens.length; i++) { IApePair pair = IApePair(_lpTokens[i]); pair.approve(address(router), _amounts[i]); try router.removeLiquidity( pair.token0(), pair.token1(), _amounts[i], _token0Outs[i], _token1Outs[i], toAddress, block.timestamp + 600 ) returns (uint256 amountA, uint256 amountB) { emit LiquidityRemoved(address(pair), amountA, amountB); } catch { if (_revertOnFailure) { revert('failed to remove liquidity'); } else { emit LiquidityRemovalFailed(address(pair)); } } } } /// @notice Swap amount in vs amount out /// @param _amountIns Array of amount ins /// @param _amountOuts Array of amount outs /// @param _paths path to follow for swapping /// @param _to address the tokens need to be transferred to. /// @param _revertOnFailure If false, the tx will not revert on swap failures function swapTokens( uint256[] calldata _amountIns, uint256[] calldata _amountOuts, address[][] calldata _paths, address _to, bool _revertOnFailure ) external onlyOwner { address toAddress = _to == address(0) ? address(this) : _to; for (uint256 i = 0; i < _amountIns.length; i++) { IERC20 token = IERC20(_paths[i][0]); token.approve(address(router), _amountIns[i]); try router.swapExactTokensForTokens( _amountIns[i], _amountOuts[i], _paths[i], toAddress, block.timestamp + 600 ) { emit Swap(_amountIns[i], _amountOuts[i], _paths[i]); } catch { if (_revertOnFailure) { revert('failed to swap tokens'); } else { emit SwapFailed(_amountIns[i], _amountOuts[i], _paths[i]); } } } } } // SPDX-License-Identifier: MIT pragma solidity =0.6.6; /* * ApeSwapFinance * App: https://apeswap.finance * Medium: https://ape-swap.medium.com * Twitter: https://twitter.com/ape_swap * Telegram: https://t.me/ape_swap * Announcements: https://t.me/ape_swap_news * GitHub: https://github.com/ApeSwapFinance */ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @dev Sweep any ERC20 token. * Sometimes people accidentally send tokens to a contract without any way to retrieve them. * This contract makes sure any erc20 tokens can be removed from the contract. */ contract SweeperUpgradeable is OwnableUpgradeable { mapping (address => bool) public lockedTokens; bool public allowNativeSweep; event SweepWithdrawToken(address indexed receiver, IERC20 indexed token, uint256 balance); event SweepWithdrawNative( address indexed receiver, uint256 balance ); /** * @dev Transfers erc20 tokens to owner * Only owner of contract can call this function */ function sweepTokens( IERC20[] calldata tokens, address to ) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = tokens[i]; require(!lockedTokens[address(token)], "Tokens can't be swept"); uint256 balance = token.balanceOf(address(this)); token.transfer(to, balance); emit SweepWithdrawToken(to, token, balance); } } /// @notice Sweep native coin /// @param _to address the native coins should be transferred to function sweepNative(address payable _to) external onlyOwner { require(allowNativeSweep, "Not allowed"); uint256 balance = address(this).balance; _to.transfer(balance); emit SweepWithdrawNative(_to, balance); } /** * @dev Refuse native sweep. * Once refused can't be allowed again */ function refuseNativeSweep() public onlyOwner { allowNativeSweep = false; } /** * @dev Lock single token so they can't be transferred from the contract. * Once locked it can't be unlocked */ function lockToken(address token) public onlyOwner { _lockToken(token); } /** * @dev Lock multiple tokens so they can't be transferred from the contract. * Once locked it can't be unlocked */ function lockTokens(address[] memory tokens) public onlyOwner { _lockTokens(tokens); } /** * @dev Lock single token so they can't be transferred from the contract. * Once locked it can't be unlocked */ function _lockToken(address token) internal { lockedTokens[token] = true; } /** * @dev Lock multiple tokens so they can't be transferred from the contract. * Once locked it can't be unlocked */ function _lockTokens(address[] memory tokens) internal { for (uint256 i = 0; i < tokens.length; i++) { _lockToken(tokens[i]); } } } pragma solidity >=0.6.2; import './IApeRouter01.sol'; interface IApeRouter02 is IApeRouter01 { 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; } pragma solidity >=0.6.2; interface IApeRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.6; interface IApePair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.6.6; interface IApeFactory { 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../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.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; }
Remove LP and unwrap to base tokens _lpTokens address list of LP tokens to unwrap _amounts Amount of each LP token to sell _token0Outs Minimum token 0 output requested. _token1Outs Minimum token 1 output requested. _to address the tokens need to be transferred to. _revertOnFailure If false, the tx will not revert on liquidity removal failures
function removeLiquidityTokens( address[] calldata _lpTokens, uint256[] calldata _amounts, uint256[] calldata _token0Outs, uint256[] calldata _token1Outs, address _to, bool _revertOnFailure ) external onlyOwner { address toAddress = _to == address(0) ? address(this) : _to; for (uint256 i = 0; i < _lpTokens.length; i++) { IApePair pair = IApePair(_lpTokens[i]); pair.approve(address(router), _amounts[i]); try router.removeLiquidity( pair.token0(), pair.token1(), _amounts[i], _token0Outs[i], _token1Outs[i], toAddress, block.timestamp + 600 ) returns (uint256 amountA, uint256 amountB) { emit LiquidityRemoved(address(pair), amountA, amountB); if (_revertOnFailure) { revert('failed to remove liquidity'); emit LiquidityRemovalFailed(address(pair)); } } } }
5,994,835
./full_match/100/0x240930F183D8A3c5845Fa49066b36df41cE680c2/sources/contracts/ERC4626-router/src/ERC4626Router.sol
@inheritdoc IERC4626Router amount out passes through so only one slippage check is needed
function redeemToDeposit( IERC4626 fromVault, IERC4626 toVault, address to, uint256 shares, uint256 minSharesOut ) external payable override returns (uint256 sharesOut) { uint256 amount = redeem(fromVault, address(this), shares, 0); return deposit(toVault, to, amount, minSharesOut); }
14,271,606
//SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./SafeMath.sol"; import "./Address.sol"; import "./IERC20.sol"; import "./ReentrantGuard.sol"; import "./IKeysStaking.sol"; /** * * KEYS Token Locking Contract * Contract Developed By DeFi Mark (MoonMark) * */ contract KEYSLockBox is ReentrancyGuard, IERC20, IKeysStaking{ using SafeMath for uint256; using Address for address; // KEYS Contract address constant KEYS = 0xe0a189C975e4928222978A74517442239a0b86ff; // precision factor uint256 constant precision = 10**36; // Total Dividends Per Farm uint256 public dividendsPerToken; // 88 day lock time uint256 public lockTime = 2534400; // 8 day harvest time uint256 public harvestTime = 230400; // Locker Structure struct StakedUser { uint256 tokensLocked; uint256 timeLocked; uint256 lastClaim; uint256 totalExcluded; } // Users -> StakedUser mapping ( address => StakedUser ) users; // total locked across all lockers uint256 totalLocked; // minimum stake amount uint256 public minToStake = 100 * 10**9; // reduced purchase fee uint256 public fee = 2; // fee for unstaking too early uint256 public earlyFee = 8; // multisignature wallet address public multisig = 0xfCacEAa7b4cf845f2cfcE6a3dA680dF1BB05015c; // Ownership address public owner; modifier onlyOwner(){require(owner == msg.sender, 'Only Owner'); _;} // Events event TransferOwnership(address newOwner); event UpdateFee(uint256 newFee); event UpdateLockTime(uint256 newTime); event UpdatedStakingMinimum(uint256 minimumKeys); event UpdatedFeeReceiver(address feeReceiver); event UpdatedEarlyFee(uint256 newFee); constructor() { owner = 0xfCacEAa7b4cf845f2cfcE6a3dA680dF1BB05015c; } function totalSupply() external view override returns (uint256) { return totalLocked; } function balanceOf(address account) public view override returns (uint256) { return users[account].tokensLocked; } function allowance(address holder, address spender) external view override returns (uint256) { return holder == spender ? balanceOf(holder) : 0; } function name() public pure override returns (string memory) { return "Locked Keys"; } function symbol() public pure override returns (string memory) { return "LOCKEDKEYS"; } function decimals() public pure override returns (uint8) { return 9; } function approve(address spender, uint256 amount) public view override returns (bool) { return users[msg.sender].tokensLocked >= amount && spender != msg.sender; } function transfer(address recipient, uint256 amount) external override returns (bool) { // ensure claim requirements if (recipient == KEYS) { _unlock(msg.sender, msg.sender, amount); } else if (recipient == address(this)){ _reinvestKeys(msg.sender); } else { _makeClaim(msg.sender); } return true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if (recipient == KEYS) { _unlock(msg.sender, msg.sender, amount); } else if (recipient == address(this)){ _reinvestKeys(msg.sender); } else { _makeClaim(msg.sender); } return true && sender == recipient; } /////////////////////////////////// ////// OWNER FUNCTIONS /////// /////////////////////////////////// function transferOwnership(address newOwner) external onlyOwner { owner = newOwner; emit TransferOwnership(newOwner); } function updateFee(uint256 newFee) external onlyOwner { fee = newFee; emit UpdateFee(newFee); } function updateFeeReceiver(address newReceiver) external onlyOwner { multisig = newReceiver; emit UpdatedFeeReceiver(newReceiver); } function setEarlyFee(uint256 newFee) external onlyOwner { earlyFee = newFee; emit UpdatedEarlyFee(newFee); } function setMinimumToStake(uint256 minimum) external onlyOwner { minToStake = minimum; emit UpdatedStakingMinimum(minimum); } function setLockTime(uint256 newTime) external onlyOwner { require(newTime <= 10**6, 'Lock Time Too Long'); lockTime = newTime; emit UpdateLockTime(newTime); } function withdraw(bool eth, address token, uint256 amount, address recipient) external onlyOwner { if (eth) { require(address(this).balance >= amount, 'Insufficient Balance'); (bool s,) = payable(recipient).call{value: amount}(""); require(s, 'Failure on ETH Withdrawal'); } else { IERC20(token).transfer(recipient, amount); } } /////////////////////////////////// ////// PUBLIC FUNCTIONS /////// /////////////////////////////////// /** Adds KEYS To The Pending Rewards Of KEYS Stakers */ function deposit(uint256 amount) external override { uint256 received = _transferIn(amount); dividendsPerToken += received.mul(precision).div(totalLocked); } function claimReward() external nonReentrant { _makeClaim(msg.sender); } function claimRewardForUser(address user) external nonReentrant { _makeClaim(user); } function unlock(uint256 amount) external nonReentrant { _unlock(msg.sender, msg.sender, amount); } function unlockFor(uint256 amount, address keysRecipient) external nonReentrant { _unlock(msg.sender, keysRecipient, amount); } function unlockAll() external nonReentrant { _unlock(msg.sender, msg.sender, users[msg.sender].tokensLocked); } function stakeKeys(uint256 numKeys) external nonReentrant { uint256 received = _transferIn(numKeys); require(received >= minToStake, 'Minimum To Stake Not Reached'); _lock(msg.sender, received); } function reinvestKeys() external nonReentrant { _reinvestKeys(msg.sender); } function _reinvestKeys(address user) internal { uint256 amount = pendingRewards(user); require(amount > 0, 'Zero Amount'); // set locker data users[user].tokensLocked += amount; users[user].lastClaim = block.number; users[user].totalExcluded = currentDividends(users[user].tokensLocked); // increment total locked totalLocked += amount; // Transfer StakedKeys emit Transfer(address(0), user, amount); } /////////////////////////////////// ////// INTERNAL FUNCTIONS /////// /////////////////////////////////// function _makeClaim(address user) internal { // ensure claim requirements require(users[user].tokensLocked > 0, 'Zero Tokens Locked'); require(users[user].lastClaim + harvestTime <= block.number, 'Claim Wait Time Not Reached'); uint256 amount = pendingRewards(user); require(amount > 0,'Zero Rewards'); _claimReward(user); } function _claimReward(address user) internal { uint256 amount = pendingRewards(user); if (amount == 0) return; // update claim stats users[user].lastClaim = block.number; users[user].totalExcluded = currentDividends(users[user].tokensLocked); // transfer tokens bool s = IERC20(KEYS).transfer(user, amount); require(s,'Failure On Token Transfer'); } function _transferIn(uint256 amount) internal returns (uint256) { uint256 before = IERC20(KEYS).balanceOf(address(this)); bool s = IERC20(KEYS).transferFrom(msg.sender, address(this), amount); uint256 difference = IERC20(KEYS).balanceOf(address(this)).sub(before); require(s && difference <= amount, 'Error On Transfer In'); return difference; } function _buyKeys() internal returns (uint256) { uint256 feeAmount = msg.value.mul(fee).div(100); uint256 purchaseAmount = msg.value.sub(feeAmount); (bool success,) = payable(multisig).call{value: feeAmount}(""); require(success, 'Failure on Dev Payment'); uint256 before = IERC20(KEYS).balanceOf(address(this)); (bool s,) = payable(KEYS).call{value: purchaseAmount}(""); require(s, 'Failure on KEYS Purchase'); return IERC20(KEYS).balanceOf(address(this)).sub(before); } function _lock(address user, uint256 received) private { if (users[user].tokensLocked > 0) { // recurring locker _claimReward(user); } else { // new user users[user].lastClaim = block.number; } // add locker data users[user].tokensLocked += received; users[user].timeLocked = block.number; users[user].totalExcluded = currentDividends(users[user].tokensLocked); // increment total locked totalLocked += received; emit Transfer(address(0), user, received); } function _unlock(address user, address recipient, uint256 nTokens) private { // Ensure Lock Requirements require(users[user].tokensLocked > 0, 'Zero Tokens Locked'); require(users[user].tokensLocked >= nTokens && nTokens > 0, 'Insufficient Tokens'); // expiration uint256 lockExpiration = users[user].timeLocked + lockTime; // claim reward _claimReward(user); // Update Staked Balances if (users[user].tokensLocked == nTokens) { delete users[user]; // Free Storage } else { users[user].tokensLocked = users[user].tokensLocked.sub(nTokens, 'Insufficient Lock Amount'); users[user].totalExcluded = currentDividends(users[user].tokensLocked); } // Update Total Locked totalLocked = totalLocked.sub(nTokens, 'Negative Locked'); // Calculate Tokens To Send Recipient uint256 tokensToSend = lockExpiration > block.number ? _calculateAndReflect(nTokens) : nTokens; // Transfer KEYS Tokens To User bool s = IERC20(KEYS).transfer(recipient, tokensToSend); require(s, 'Failure on LP Token Transfer'); // tell Blockchain emit Transfer(user, address(0), nTokens); } function _calculateAndReflect(uint256 nTokens) internal returns (uint256) { // apply early leave tax uint256 tax = nTokens.mul(earlyFee).div(100); // Reflect Tax To KEYS Stakers dividendsPerToken += tax.mul(precision).div(totalLocked); // Return Send Amount return nTokens.sub(tax); } /////////////////////////////////// ////// READ FUNCTIONS /////// /////////////////////////////////// function getTimeUntilUnlock(address user) external view returns (uint256) { uint256 endTime = users[user].timeLocked + lockTime; return endTime > block.number ? endTime.sub(block.number) : 0; } function getTimeUntilNextClaim(address user) external view returns (uint256) { uint256 endTime = users[user].lastClaim + harvestTime; return endTime > block.number ? endTime.sub(block.number) : 0; } function currentDividends(uint256 share) internal view returns (uint256) { return share.mul(dividendsPerToken).div(precision); } function pendingRewards(address user) public view returns (uint256) { uint256 amount = users[user].tokensLocked; if(amount == 0){ return 0; } uint256 shareholderTotalDividends = currentDividends(amount); uint256 shareholderTotalExcluded = users[user].totalExcluded; if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; } return shareholderTotalDividends.sub(shareholderTotalExcluded); } function totalPendingRewards() external view returns (uint256) { return IERC20(KEYS).balanceOf(address(this)).sub(totalLocked); } function calculateKEYSBalance(address user) external view returns (uint256) { return IERC20(KEYS).balanceOf(user); } function calculateKEYSContractBalance() external view returns (uint256) { return IERC20(KEYS).balanceOf(address(this)); } receive() external payable { uint256 received = _buyKeys(); require(received >= minToStake, 'Minimum To Stake Not Reached'); _lock(msg.sender, received); } }
update claim stats transfer tokens
function _claimReward(address user) internal { uint256 amount = pendingRewards(user); if (amount == 0) return; users[user].lastClaim = block.number; users[user].totalExcluded = currentDividends(users[user].tokensLocked); bool s = IERC20(KEYS).transfer(user, amount); require(s,'Failure On Token Transfer'); }
1,161,076
./full_match/1/0xe9B8B4B2d7b747ef60D5aED7263ebF2839a1a891/sources/contracts/EphemeralFacts.sol
requests a fact to be proven asynchronously and passed to the receiver, account the account associated with the fact sigData the fact data which determines the fact signature (class is assumed to be NO_FEE) receiver the contract to receive the fact data the extra data to pass to the receiver gasLimit the maxmium gas used by the receiver msg.value is added to the bounty for this fact request, incentivizing somebody to prove it/
function requestFact( address account, bytes calldata sigData, IRelicReceiver receiver, bytes calldata data, uint256 gasLimit ) external payable { FactSignature sig = Facts.toFactSignature(Facts.NO_FEE, sigData); ReceiverContext memory context = ReceiverContext(msg.sender, receiver, data, gasLimit); uint256 bounty = bounties[requestId(account, sig, context)] += msg.value; emit FactRequested(FactDescription(account, sigData), context, bounty); }
3,845,710
./partial_match/1/0xf18BC8fAD58afcA55DaC79d3AF468dBDC280aa4f/sources/KissToken.sol
Forward ERC20 methods to upgraded contract
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { return super.approve(_spender, _value); }
3,591,412
pragma solidity ^0.5.5; library SigUtils { /** @dev Recovers address who signed the message @param _hash operation ethereum signed message hash @param _signature message `hash` signature */ function ecrecover2 ( bytes32 _hash, bytes memory _signature ) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 255) } if (v < 27) { v += 27; } return ecrecover( _hash, v, r, s ); } } /* Marmo wallet It has a signer, and it accepts signed messages ´Intents´ (Meta-Txs) all messages are composed by an interpreter and a ´data´ field. */ contract Marmo { event Relayed(bytes32 indexed _id, address _implementation, bytes _data); event Canceled(bytes32 indexed _id); // Random Invalid signer address // Intents signed with this address are invalid address private constant INVALID_ADDRESS = address(0x9431Bab00000000000000000000000039bD955c9); // Random slot to store signer bytes32 private constant SIGNER_SLOT = keccak256("marmo.wallet.signer"); // [1 bit (canceled) 95 bits (block) 160 bits (relayer)] mapping(bytes32 => bytes32) private intentReceipt; function() external payable {} // Inits the wallet, any address can Init // it must be called using another contract function init(address _signer) external payable { address signer; bytes32 signerSlot = SIGNER_SLOT; assembly { signer := sload(signerSlot) } require(signer == address(0), "Signer already defined"); assembly { sstore(signerSlot, _signer) } } // Signer of the Marmo wallet // can perform transactions by signing Intents function signer() public view returns (address _signer) { bytes32 signerSlot = SIGNER_SLOT; assembly { _signer := sload(signerSlot) } } // Address that relayed the `_id` intent // address(0) if the intent was not relayed function relayedBy(bytes32 _id) external view returns (address _relayer) { (,,_relayer) = _decodeReceipt(intentReceipt[_id]); } // Block when the intent was relayed // 0 if the intent was not relayed function relayedAt(bytes32 _id) external view returns (uint256 _block) { (,_block,) = _decodeReceipt(intentReceipt[_id]); } // True if the intent was canceled // An executed intent can't be canceled and // a Canceled intent can't be executed function isCanceled(bytes32 _id) external view returns (bool _canceled) { (_canceled,,) = _decodeReceipt(intentReceipt[_id]); } // Relay a signed intent // // The implementation receives data containing the id of the 'intent' and its data, // and it will perform all subsequent calls. // // The same _implementation and _data combination can only be relayed once // // Returns the result of the 'delegatecall' execution function relay( address _implementation, bytes calldata _data, bytes calldata _signature ) external payable returns ( bytes memory result ) { // Calculate ID from // (this, _implementation, data) // Any change in _data results in a different ID bytes32 id = keccak256( abi.encodePacked( address(this), _implementation, keccak256(_data) ) ); // Read receipt only once // if the receipt is 0, the Intent was not canceled or relayed if (intentReceipt[id] != bytes32(0)) { // Decode the receipt and determine if the Intent was canceled or relayed (bool canceled, , address relayer) = _decodeReceipt(intentReceipt[id]); require(relayer == address(0), "Intent already relayed"); require(!canceled, "Intent was canceled"); revert("Unknown error"); } // Read the signer from storage, avoid multiples 'sload' ops address _signer = signer(); // The signer 'INVALID_ADDRESS' is considered invalid and it will always throw // this is meant to disable the wallet safely require(_signer != INVALID_ADDRESS, "Signer is not a valid address"); // Validate is the msg.sender is the signer or if the provided signature is valid require(_signer == msg.sender || _signer == SigUtils.ecrecover2(id, _signature), "Invalid signature"); // Save the receipt before performing any other action intentReceipt[id] = _encodeReceipt(false, block.number, msg.sender); // Emit the 'relayed' event emit Relayed(id, _implementation, _data); // Perform 'delegatecall' to _implementation, appending the id of the intent // to the beginning of the _data. bool success; (success, result) = _implementation.delegatecall(abi.encode(id, _data)); // If the 'delegatecall' failed, reverts the transaction // forwarding the revert message if (!success) { assembly { revert(add(result, 32), mload(result)) } } } // Cancels a not executed Intent '_id' // a canceled intent can't be executed function cancel(bytes32 _id) external { require(msg.sender == address(this), "Only wallet can cancel txs"); if (intentReceipt[_id] != bytes32(0)) { (bool canceled, , address relayer) = _decodeReceipt(intentReceipt[_id]); require(relayer == address(0), "Intent already relayed"); require(!canceled, "Intent was canceled"); revert("Unknown error"); } emit Canceled(_id); intentReceipt[_id] = _encodeReceipt(true, 0, address(0)); } // Encodes an Intent receipt // into a single bytes32 // canceled (1 bit) + block (95 bits) + relayer (160 bits) // notice: Does not validate the _block length, // a _block overflow would not corrupt the wallet state function _encodeReceipt( bool _canceled, uint256 _block, address _relayer ) internal pure returns (bytes32 _receipt) { assembly { _receipt := or(shl(255, _canceled), or(shl(160, _block), _relayer)) } } // Decodes an Intent receipt // reverse of _encodeReceipt(bool,uint256,address) function _decodeReceipt(bytes32 _receipt) internal pure returns ( bool _canceled, uint256 _block, address _relayer ) { assembly { _canceled := shr(255, _receipt) _block := and(shr(160, _receipt), 0x7fffffffffffffffffffffff) _relayer := and(_receipt, 0xffffffffffffffffffffffffffffffffffffffff) } } // Used to receive ERC721 tokens function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) { return bytes4(0x150b7a02); } }
Signer of the Marmo wallet can perform transactions by signing Intents
function signer() public view returns (address _signer) { bytes32 signerSlot = SIGNER_SLOT; }
10,768,612
./partial_match/42/0xdFf18ab57909a57e4660435B0935C09A1407d29A/sources/MasterchefDelegator.sol
update reward vairables for a pool
function updatePoolDividend(uint256 _pid) public virtual { if (block.number < stageOneDepositEndBlock) { stageOne.updatePoolDividend(_pid); if (rankPoolIndexMap[_pid] == 0) { return; } updatePoolAccumulativeDividend( _pid, rankPoolIndex.length, block.number ); } }
3,296,301
./full_match/5/0xd3C803fc4f113BEac108A3406c09C32dB8671fbc/sources/contracts/ProjectERC20.sol
call this method when one investor decides to leave the project this can only be called when the project isn't fully funded yet
function cancelInvestment(address _investor) external { uint256 investment = investments[_investor]; stablecoin.transfer(_investor, investment); delete(investments[_investor]); }
1,920,041
./full_match/4/0x73DB9123Ef62e0709b0723eE3B93042E36b7570f/sources/contracts/new/ERC1155Mintable.sol
Transfer event with mint semantic
function _createCustomUnique(uint256 _customId, string memory _uri) internal returns(uint256 _id) { if (creators[_id] != address(0)) return 0; uint256 _initialSupply = 1; creators[_id] = msg.sender; balances[_id][msg.sender] = _initialSupply; emit TransferSingle(msg.sender, address(0x0), msg.sender, _id, _initialSupply); if (bytes(_uri).length > 0) emit URI(_uri, _id); }
12,400,216
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface IUniswapV2Factory { event PAIRCREATED765(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO173() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER947() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR540(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS330(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH28() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR870(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO87(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER308(address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Pair { event APPROVAL174(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER306(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME472() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL588() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS125() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY849() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF412(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE690(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER680(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM721(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR798() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH5() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES780(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT824(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT900(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN945(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP468( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC111(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY386() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY86() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0481() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1550() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES473() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST512() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST431() external view returns (uint); //inject NONSTANDARD NAMING function KLAST25() external view returns (uint); //inject NONSTANDARD NAMING function MINT371(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN742(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP14(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM245(address to) external; //inject NONSTANDARD NAMING function SYNC404() external; //inject NONSTANDARD NAMING function INITIALIZE744(address, address) external; //inject NONSTANDARD NAMING } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant resolution65 = 112; //inject NONSTANDARD NAMING // encode a uint112 as a UQ112x112 function ENCODE953(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING return uq112x112(uint224(x) << resolution65); } // encodes a uint144 as a UQ144x112 function ENCODE144474(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING return uq144x112(uint256(x) << resolution65); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function DIV758(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function MUL709(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function FRACTION20(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << resolution65) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function DECODE642(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING return uint112(self._x >> resolution65); } // decode a UQ144x112 into a uint144 by truncating after the radix point function DECODE144805(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING return uint144(self._x >> resolution65); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function CURRENTBLOCKTIMESTAMP616() internal view returns (uint32) { //inject NONSTANDARD NAMING return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function CURRENTCUMULATIVEPRICES565( //inject NONSTANDARD NAMING address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = CURRENTBLOCKTIMESTAMP616(); price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST512(); price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST431(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES473(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.FRACTION20(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.FRACTION20(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function ADD508(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function ADD508(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, errorMessage); return c; } function SUB277(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB277(a, b, "SafeMath: subtraction underflow"); } function SUB277(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL709(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function MUL709(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function DIV758(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV758(a, b, "SafeMath: division by zero"); } function DIV758(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD92(a, b, "SafeMath: modulo by zero"); } function MOD92(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function SORTTOKENS379(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function PAIRFOR87(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING (address token0, address token1) = SORTTOKENS379(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function GETRESERVES473(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING (address token0,) = SORTTOKENS379(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR87(factory, tokenA, tokenB)).GETRESERVES473(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function QUOTE2(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.MUL709(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function GETAMOUNTOUT789(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.MUL709(997); uint numerator = amountInWithFee.MUL709(reserveOut); uint denominator = reserveIn.MUL709(1000).ADD508(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function GETAMOUNTIN163(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.MUL709(amountOut).MUL709(1000); uint denominator = reserveOut.SUB277(amountOut).MUL709(997); amountIn = (numerator / denominator).ADD508(1); } // performs chained getAmountOut calculations on any number of pairs function GETAMOUNTSOUT330(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i], path[i + 1]); amounts[i + 1] = GETAMOUNTOUT789(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function GETAMOUNTSIN267(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i - 1], path[i]); amounts[i - 1] = GETAMOUNTIN163(amounts[i], reserveIn, reserveOut); } } } interface WETH9 { function WITHDRAW840(uint wad) external; //inject NONSTANDARD NAMING } interface IUniswapV2Router { function SWAPEXACTTOKENSFORTOKENS109( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface IKeep3rV1 { function ISMINKEEPER913(address keeper, uint minBond, uint earned, uint age) external returns (bool); //inject NONSTANDARD NAMING function RECEIPT100(address credit, address keeper, uint amount) external; //inject NONSTANDARD NAMING function UNBOND169(address bonding, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW840(address bonding) external; //inject NONSTANDARD NAMING function BONDS570(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function UNBONDINGS996(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function JOBS817(address job) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF412(address account) external view returns (uint256); //inject NONSTANDARD NAMING function WORKED219(address keeper) external; //inject NONSTANDARD NAMING function KPRH771() external view returns (IKeep3rV1Helper); //inject NONSTANDARD NAMING } interface IKeep3rV1Helper { function GETQUOTELIMIT880(uint gasUsed) external view returns (uint); //inject NONSTANDARD NAMING } // sliding oracle that uses observations collected to provide moving price averages in the past contract YearnV2Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } uint public minKeep = 200e18; modifier KEEPER983() { //inject NONSTANDARD NAMING require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; } modifier UPKEEP664() { //inject NONSTANDARD NAMING uint _gasUsed = gasleft(); require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; uint _received = kp3r674.KPRH771().GETQUOTELIMIT880(_gasUsed.SUB277(gasleft())); kp3r674.RECEIPT100(address(kp3r674), address(this), _received); _received = _SWAP523(_received); msg.sender.transfer(_received); } address public governance; address public pendingGovernance; function SETMINKEEP842(uint _keep) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); minKeep = _keep; } function SETGOVERNANCE949(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } function ACCEPTGOVERNANCE56() external { //inject NONSTANDARD NAMING require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep3rV1 public constant kp3r674 = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); //inject NONSTANDARD NAMING WETH9 public constant weth411 = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING IUniswapV2Router public constant uni703 = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant factory868 = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //inject NONSTANDARD NAMING // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public constant periodsize934 = 1800; //inject NONSTANDARD NAMING address[] internal _pairs; mapping(address => bool) internal _known; function PAIRS458() external view returns (address[] memory) { //inject NONSTANDARD NAMING return _pairs; } mapping(address => Observation[]) public observations; function OBSERVATIONLENGTH959(address pair) external view returns (uint) { //inject NONSTANDARD NAMING return observations[pair].length; } function PAIRFOR87(address tokenA, address tokenB) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); } function PAIRFORWETH375(address tokenA) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, address(weth411)); } constructor() public { governance = msg.sender; } function UPDATEPAIR621(address pair) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING return _UPDATE639(pair); } function UPDATE182(address tokenA, address tokenB) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); return _UPDATE639(pair); } function ADD508(address tokenA, address tokenB) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "UniswapV2Oracle::add: !gov"); address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); } function WORK476() public UPKEEP664 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function WORKFORFREE492() public KEEPER983 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function LASTOBSERVATION770(address pair) public view returns (Observation memory) { //inject NONSTANDARD NAMING return observations[pair][observations[pair].length-1]; } function _UPDATEALL128() internal returns (bool updated) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function UPDATEFOR106(uint i, uint length) external KEEPER983 returns (bool updated) { //inject NONSTANDARD NAMING for (; i < length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function WORKABLE40(address pair) public view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) > periodsize934; } function WORKABLE40() external view returns (bool) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (WORKABLE40(_pairs[i])) { return true; } } return false; } function _UPDATE639(address pair) internal returns (bool) { //inject NONSTANDARD NAMING // we only want to commit updates once per period (i.e. windowSize / granularity) Observation memory _point = LASTOBSERVATION770(pair); uint timeElapsed = block.timestamp - _point.timestamp; if (timeElapsed > periodsize934) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); return true; } return false; } function COMPUTEAMOUNTOUT732( //inject NONSTANDARD NAMING uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.MUL709(amountIn).DECODE144805(); } function _VALID458(address pair, uint age) internal view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) <= age; } function CURRENT334(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(2)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); Observation memory _observation = LASTOBSERVATION770(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); if (block.timestamp == _observation.timestamp) { _observation = observations[pair][observations[pair].length-2]; } uint timeElapsed = block.timestamp - _observation.timestamp; timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == tokenIn) { return COMPUTEAMOUNTOUT732(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return COMPUTEAMOUNTOUT732(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function QUOTE2(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(granularity)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint priceAverageCumulative = 0; uint length = observations[pair].length-1; uint i = length.SUB277(granularity); uint nextIndex = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } else { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } return priceAverageCumulative.DIV758(granularity); } function PRICES199(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint length = observations[pair].length-1; uint i = length.SUB277(points); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function HOURLY603(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(2); uint i = _len.SUB277(points.MUL709(2)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(2)) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function DAILY468(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(48); uint i = _len.SUB277(points.MUL709(48)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(48)) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function WEEKLY904(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(336); uint i = _len.SUB277(points.MUL709(336)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(336)) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function IMPLIEDVOLATILITYHOURLY328(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(HOURLY603(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYDAILY500(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(DAILY468(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYWEEKLY55(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(WEEKLY904(tokenIn, amountIn, tokenOut, 1)); } function SQRT123(uint256 x) public pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = (x + 1) / 2; uint256 b = x; while (c < b) { b = c; c = (x / c + c) / 2; } return b; } function STDDEV946(uint[] memory numbers) public pure returns (uint256 sd) { //inject NONSTANDARD NAMING uint sum = 0; for(uint i = 0; i < numbers.length; i++) { sum += numbers[i]; } uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity sum = 0; uint i; for(i = 0; i < numbers.length; i++) { sum += (numbers[i] - mean) ** 2; } sd = SQRT123(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity return sd; } function BLACKSCHOLESESTIMATE503( //inject NONSTANDARD NAMING uint256 _vol, uint256 _underlying, uint256 _time ) public pure returns (uint256 estimate) { estimate = 40 * _vol * _underlying * SQRT123(_time); return estimate; } function RETBASEDBLACKSCHOLESESTIMATE765( //inject NONSTANDARD NAMING uint256[] memory _numbers, uint256 _underlying, uint256 _time ) public pure { uint _vol = STDDEV946(_numbers); BLACKSCHOLESESTIMATE503(_vol, _underlying, _time); } receive() external payable {} function _SWAP523(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING kp3r674.APPROVE763(address(uni703), _amount); address[] memory path = new address[](2); path[0] = address(kp3r674); path[1] = address(weth411); uint[] memory amounts = uni703.SWAPEXACTTOKENSFORTOKENS109(_amount, uint256(0), path, address(this), now.ADD508(1800)); weth411.WITHDRAW840(amounts[1]); return amounts[1]; } }
inject NONSTANDARD NAMING
function GETAMOUNTSOUT330(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
12,917,682
pragma solidity 0.4.18; import "./DetailedERC721.sol"; contract PunchCardNFT is DetailedERC721{ string public name = "PunchCardNFT"; string public symbol = "PCNFT"; uint public totalPunchCards; mapping(uint=>address) internal punchCardIdToOwner; mapping(uint=>string) internal punchCardIdToMetaData; mapping(address=>uint[]) internal ownerToPunchCardsOwned; mapping(uint=>uint) internal punchCardIdToOwnerArrayIndex; mapping (uint=>address) internal punchCardIdToApprovedAddress; /* ERC721 events */ event Transfer(address indexed _from, address indexed _to, uint256 _punchCardId); event Approval(address indexed _owner, address indexed _requester, uint256 _punchCardId); //Only punch cards in existance modifier onlyExtantPunchCards(uint _punchCardId){ require(_ownerOf(_punchCardId) != address(0)); _; } /* ERC721 public functions */ function totalSupply() public view returns(uint256 _totalSupply){ return totalPunchCards; } function balanceOf(address _owner) public view returns(uint256 _balance){ return ownerToPunchCardsOwned[_owner].length; } function ownerOf(uint _tokenId) public view returns(address _owner){ return _ownerOf(_tokenId); } function approve(address _to, uint _tokenId) public onlyExtantPunchCards(_tokenId){ require(msg.sender == _ownerOf(_tokenId)); require(msg.sender != _to); _approve(_to, _tokenId); Approval(msg.sender, _to, _tokenId); } function getApproved(uint _tokenId) public view returns(address _approved){ return _getApproved(_tokenId); } /*transfer the NFT _tokenId from _from to _to*/ function transferFrom(address _from, address _to, uint _tokenId) public onlyExtantPunchCards(_tokenId){ require(getApproved(_tokenId) == msg.sender); require(_ownerOf(_tokenId) == _from); require(_to != address(0)); _clearApprovalAndTransfer(_from, _to, _tokenId); Approval(_from, 0, _tokenId); Transfer(_from, _to, _tokenId); } function transfer(address _to, uint _tokenId) public onlyExtantPunchCards(_tokenId){ require(_ownerOf(_tokenId) == msg.sender); require(_to != address(0)); _clearApprovalAndTransfer(msg.sender, _to, _tokenId); Approval(msg.sender, _to, _tokenId); Transfer(msg.sender, _to, _tokenId); } function name() public view returns(string){ return _getName(); } function symbol() public view returns(string){ return _getSymbol(); } function tokenOfOwnerByIndex(address _owner, uint _index) public view returns(uint _tokenId){ return _getTokenOfOwnerByIndex(_owner, _index); } /*private functions*/ function _ownerOf(uint _tokenId) internal view returns(address){ return punchCardIdToOwner[_tokenId]; } function _approve(address _to, uint _tokenId) internal{ punchCardIdToApprovedAddress[_tokenId] = _to; } function _getApproved(uint _tokenId) internal view returns(address){ return punchCardIdToApprovedAddress[_tokenId]; } function _getTokenOfOwnerByIndex(address _owner, uint _index) private view returns(uint _tokenId){ return ownerToPunchCardsOwned[_owner][_index]; } function _clearApprovalAndTransfer(address _from, address _to, uint _tokenId) internal{ _clearTokenApproval(_tokenId); _removeTokenFromOwnersList(_from, _tokenId); _setTokenOwner(_tokenId, _to); _addTokenToOwnersList(_to, _tokenId); } function _clearTokenApproval(uint _tokenId) internal{ punchCardIdToApprovedAddress[_tokenId] = address(0); } function _removeTokenFromOwnersList(address _owner, uint _tokenId) internal{ uint length = ownerToPunchCardsOwned[_owner].length; uint index = punchCardIdToOwnerArrayIndex[_tokenId]; uint swapPunchCardId = ownerToPunchCardsOwned[_owner][length - 1]; ownerToPunchCardsOwned[_owner][index] = swapPunchCardId; punchCardIdToOwnerArrayIndex[swapPunchCardId] = index; delete ownerToPunchCardsOwned[_owner][length - 1]; ownerToPunchCardsOwned[_owner].length--; } function _setTokenOwner(uint _tokenId, address _to) internal{ punchCardIdToOwner[_tokenId] = _to; } function _addTokenToOwnersList(address _owner, uint _tokenId) internal{ ownerToPunchCardsOwned[_owner].push(_tokenId); punchCardIdToOwnerArrayIndex[_tokenId] = ownerToPunchCardsOwned[_owner].length - 1; } function getOwnerTokens(address _owner) public view returns(uint[]){ return ownerToPunchCardsOwned[_owner]; } function _getOwnerTokens(address _owner) internal view returns(uint[]){ return ownerToPunchCardsOwned[_owner]; } function _getName() internal view returns(string){ return name; } function _getSymbol() internal view returns(string){ return symbol; } }
ERC721 public functions /
function totalSupply() public view returns(uint256 _totalSupply){ return totalPunchCards; }
12,788,065
pragma solidity ^0.4.8; contract SafeMath { function safeSub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract ALBtoken is SafeMath{ // Token information uint256 public vigencia; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; //Token Variables uint256[] public TokenMineSupply; uint256 public _MineId; uint256 totalSupplyFloat; uint256 oldValue; uint256 subValue; uint256 oldTotalSupply; uint256 TokensToModify; bool firstTime; struct Minas { uint256 id; string name; uint tokensupply; bool active; } //Mapping /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping(uint256=>Minas) public participatingMines; //Events /* 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 burn*/ event Burn(address indexed from, uint256 value); /* This notifies clients about the token add*/ event AddToken(address indexed from, uint256 value); /*This notifies clients about new mine created or updated*/ event MineCreated (uint256 MineId, string MineName, uint MineSupply); event MineUpdated (uint256 MineId, string MineName, uint MineSupply, bool Estate); /* Initializes contract with initial supply tokens to the creator of the contract */ function ALBtoken(){ totalSupply = 0; // Update total supply name = "Albarit"; // Set the name for display purposes symbol = "ALB"; // Set the symbol for display purposes decimals = 3; // Amount of decimals for display purposes balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens owner = msg.sender; //Set contrac's owner vigencia =2178165600; firstTime = false; } //Administrator modifier onlyOwner() { require(msg.sender == owner); _; } /* Send coins */ function transfer(address _to, uint256 _value) { if(totalSupply == 0) { selfdestruct(owner); } if(block.timestamp >= vigencia) { throw; } if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { if(totalSupply == 0) { selfdestruct(owner); } if(block.timestamp >= vigencia) { throw; } if (_value <= 0) throw; allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if(totalSupply == 0) { selfdestruct(owner); } if(block.timestamp >= vigencia) { throw; } if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } /* A contract attempts to get the coins */ function transferFromRoot(address _from, address _to, uint256 _value) onlyOwner returns (bool success) { if(totalSupply == 0) { selfdestruct(owner); } if(block.timestamp >= vigencia) { throw; } if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient emit Transfer(_from, _to, _value); return true; } function addToken(uint256 _value) onlyOwner returns (bool success) { if(totalSupply == 0) { selfdestruct(owner); } if(block.timestamp >= vigencia) { throw; } //totalSupply = SafeMath.safeAdd(totalSupply,_value); // Updates totalSupply emit AddToken(msg.sender, _value); balanceOf[owner]=SafeMath.safeAdd(balanceOf[owner], _value); return true; } function burn(uint256 _value) onlyOwner returns (bool success) { if(totalSupply == 0) { selfdestruct(owner); } if(block.timestamp >= vigencia) { throw; } if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender //totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } // transfer balance to owner function withdrawEther(uint256 amount) onlyOwner{ if(totalSupply == 0) { selfdestruct(owner); } if(block.timestamp >= vigencia) { throw; } if(msg.sender != owner)throw; owner.transfer(amount); } // can accept ether function() payable { } function RegisterMine(string _name, uint _tokensupply) onlyOwner { if (firstTime == false) { firstTime = true; } else { if(totalSupply == 0) { selfdestruct(owner); } } if(block.timestamp >= vigencia) { throw; } /*Register new mine's data*/ participatingMines[_MineId] = Minas ({ id: _MineId, name: _name, tokensupply: _tokensupply, active: true }); /*add to array new item with new mine's token supply */ TokenMineSupply.push(_tokensupply); /*add to array new item with new mine's token supply */ /*Uptade Albarit's total supply*/ /*uint256*/ totalSupplyFloat = 0; for (uint8 i = 0; i < TokenMineSupply.length; i++) { totalSupplyFloat = safeAdd(TokenMineSupply[i], totalSupplyFloat); } totalSupply = totalSupplyFloat; addToken(_tokensupply); emit MineCreated (_MineId, _name, _tokensupply); _MineId = safeAdd(_MineId, 1); } function ModifyMine(uint256 _Id, bool _state, string _name, uint _tokensupply) onlyOwner { if(totalSupply == 0) { selfdestruct(owner); } if(block.timestamp >= vigencia) { throw; } /*uint256*/ oldValue = 0; /*uint256*/ subValue = 0; /*uint256*/ oldTotalSupply = totalSupply; /*uint256*/ TokensToModify = 0; /*update mine's data*/ participatingMines[_Id].active = _state; participatingMines[_Id].name = _name; participatingMines[_Id].tokensupply = _tokensupply; oldValue = TokenMineSupply[_Id]; if (_tokensupply > oldValue) { TokenMineSupply[_Id] = _tokensupply; } else { subValue = safeSub(oldValue, _tokensupply); TokenMineSupply[_Id]=safeSub(TokenMineSupply[_Id], subValue); } /*Uint256*/ totalSupplyFloat = 0; for (uint8 i = 0; i < TokenMineSupply.length; i++) { totalSupplyFloat = safeAdd(TokenMineSupply[i], totalSupplyFloat); } emit MineUpdated(_Id, _name, _tokensupply, _state); totalSupply = totalSupplyFloat; /*_tokensupply > oldValue*/ if (totalSupply > oldTotalSupply) { TokensToModify = safeSub(totalSupply, oldTotalSupply); addToken(TokensToModify); } /*_tokensupply > oldValue*/ if (totalSupply < oldTotalSupply) { TokensToModify = safeSub(oldTotalSupply, totalSupply); burn(TokensToModify); } } function getTokenByMineID() external view returns (uint256[]) { return TokenMineSupply; } function ModifyVigencia(uint256 _vigencia) onlyOwner { if(totalSupply == 0) { selfdestruct(owner); } vigencia = _vigencia; } }
A contract attempts to get the coins /
function transferFromRoot(address _from, address _to, uint256 _value) onlyOwner returns (bool success) { if(totalSupply == 0) { selfdestruct(owner); } if(block.timestamp >= vigencia) { throw; } if (_value <= 0) throw; emit Transfer(_from, _to, _value); return true; }
5,422,667
./full_match/42/0x4c77132e29226200097E8a788b9982c170896fBE/sources/Users/dinu/work/Crypto/My/my_ganache_swap/src/contracts/GanacheSwap.sol
Calculate the number of tokens to buy Require that GanacheSwap has enough tokens Transfer tokens to the user Emit an event
function buyTokens() public payable { uint256 tokenAmount = SafeMath.mul(msg.value, rate); require(token.balanceOf(address(this)) >= tokenAmount); token.transfer(msg.sender, tokenAmount); emit TokensPurchased(msg.sender, address(token), tokenAmount, rate); }
9,600,249
// SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_ECDSAContractAccount } from "../../iOVM/accounts/iOVM_ECDSAContractAccount.sol"; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_ECDSAUtils } from "../../libraries/utils/Lib_ECDSAUtils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; import { Lib_SafeMathWrapper } from "../../libraries/wrappers/Lib_SafeMathWrapper.sol"; /** * @title OVM_ECDSAContractAccount * @dev The ECDSA Contract Account can be used as the implementation for a ProxyEOA deployed by the * ovmCREATEEOA operation. It enables backwards compatibility with Ethereum's Layer 1, by * providing eth_sign and EIP155 formatted transaction encodings. * * Compiler used: solc * Runtime target: OVM */ contract OVM_ECDSAContractAccount is iOVM_ECDSAContractAccount { /************* * Constants * *************/ // TODO: should be the amount sufficient to cover the gas costs of all of the transactions up // to and including the CALL/CREATE which forms the entrypoint of the transaction. uint256 constant EXECUTION_VALIDATION_GAS_OVERHEAD = 25000; address constant ETH_ERC20_ADDRESS = 0x4200000000000000000000000000000000000006; /******************** * Public Functions * ********************/ /** * Executes a signed transaction. * @param _transaction Signed EOA transaction. * @param _signatureType Hashing scheme used for the transaction (e.g., ETH signed message). * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. * @return Whether or not the call returned (rather than reverted). * @return Data returned by the call. */ function execute( bytes memory _transaction, Lib_OVMCodec.EOASignatureType _signatureType, uint8 _v, bytes32 _r, bytes32 _s ) override public returns ( bool, bytes memory ) { bool isEthSign = _signatureType == Lib_OVMCodec.EOASignatureType.ETH_SIGNED_MESSAGE; // Address of this contract within the ovm (ovmADDRESS) should be the same as the // recovered address of the user who signed this message. This is how we manage to shim // account abstraction even though the user isn't a contract. // Need to make sure that the transaction nonce is right and bump it if so. Lib_SafeExecutionManagerWrapper.safeREQUIRE( Lib_ECDSAUtils.recover( _transaction, isEthSign, _v, _r, _s ) == Lib_SafeExecutionManagerWrapper.safeADDRESS(), "Signature provided for EOA transaction execution is invalid." ); Lib_OVMCodec.EIP155Transaction memory decodedTx = Lib_OVMCodec.decodeEIP155Transaction(_transaction, isEthSign); // Need to make sure that the transaction chainId is correct. Lib_SafeExecutionManagerWrapper.safeREQUIRE( decodedTx.chainId == Lib_SafeExecutionManagerWrapper.safeCHAINID(), "Transaction chainId does not match expected OVM chainId." ); // Need to make sure that the transaction nonce is right. Lib_SafeExecutionManagerWrapper.safeREQUIRE( decodedTx.nonce == Lib_SafeExecutionManagerWrapper.safeGETNONCE(), "Transaction nonce does not match the expected nonce." ); // TEMPORARY: Disable gas checks for mainnet. // // Need to make sure that the gas is sufficient to execute the transaction. // Lib_SafeExecutionManagerWrapper.safeREQUIRE( // gasleft() >= Lib_SafeMathWrapper.add(decodedTx.gasLimit, EXECUTION_VALIDATION_GAS_OVERHEAD), // "Gas is not sufficient to execute the transaction." // ); // Transfer fee to relayer. address relayer = Lib_SafeExecutionManagerWrapper.safeCALLER(); uint256 fee = Lib_SafeMathWrapper.mul(decodedTx.gasLimit, decodedTx.gasPrice); (bool success, ) = Lib_SafeExecutionManagerWrapper.safeCALL( gasleft(), ETH_ERC20_ADDRESS, abi.encodeWithSignature("transfer(address,uint256)", relayer, fee) ); Lib_SafeExecutionManagerWrapper.safeREQUIRE( success == true, "Fee was not transferred to relayer." ); // Contract creations are signalled by sending a transaction to the zero address. if (decodedTx.to == address(0)) { (address created, bytes memory revertData) = Lib_SafeExecutionManagerWrapper.safeCREATE( gasleft(), decodedTx.data ); // Return true if the contract creation succeeded, false w/ revertData otherwise. if (created != address(0)) { return (true, abi.encode(created)); } else { return (false, revertData); } } else { // We only want to bump the nonce for `ovmCALL` because `ovmCREATE` automatically bumps // the nonce of the calling account. Normally an EOA would bump the nonce for both // cases, but since this is a contract we'd end up bumping the nonce twice. Lib_SafeExecutionManagerWrapper.safeINCREMENTNONCE(); return Lib_SafeExecutionManagerWrapper.safeCALL( gasleft(), decodedTx.to, decodedTx.data ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_ECDSAUtils } from "../../libraries/utils/Lib_ECDSAUtils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title OVM_ProxyEOA * @dev The Proxy EOA contract uses a delegate call to execute the logic in an implementation contract. * In combination with the logic implemented in the ECDSA Contract Account, this enables a form of upgradable * 'account abstraction' on layer 2. * * Compiler used: solc * Runtime target: OVM */ contract OVM_ProxyEOA { /************* * Constants * *************/ bytes32 constant IMPLEMENTATION_KEY = 0xdeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddead; /*************** * Constructor * ***************/ /** * @param _implementation Address of the initial implementation contract. */ constructor( address _implementation ) { _setImplementation(_implementation); } /********************* * Fallback Function * *********************/ fallback() external { (bool success, bytes memory returndata) = Lib_SafeExecutionManagerWrapper.safeDELEGATECALL( gasleft(), getImplementation(), msg.data ); if (success) { assembly { return(add(returndata, 0x20), mload(returndata)) } } else { Lib_SafeExecutionManagerWrapper.safeREVERT( string(returndata) ); } } /******************** * Public Functions * ********************/ /** * Changes the implementation address. * @param _implementation New implementation address. */ function upgrade( address _implementation ) external { Lib_SafeExecutionManagerWrapper.safeREQUIRE( Lib_SafeExecutionManagerWrapper.safeADDRESS() == Lib_SafeExecutionManagerWrapper.safeCALLER(), "EOAs can only upgrade their own EOA implementation" ); _setImplementation(_implementation); } /** * Gets the address of the current implementation. * @return Current implementation address. */ function getImplementation() public returns ( address ) { return Lib_Bytes32Utils.toAddress( Lib_SafeExecutionManagerWrapper.safeSLOAD( IMPLEMENTATION_KEY ) ); } /********************** * Internal Functions * **********************/ function _setImplementation( address _implementation ) internal { Lib_SafeExecutionManagerWrapper.safeSSTORE( IMPLEMENTATION_KEY, Lib_Bytes32Utils.fromAddress(_implementation) ); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol"; import { Lib_ErrorUtils } from "../../libraries/utils/Lib_ErrorUtils.sol"; /* Interface Imports */ import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol"; import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol"; import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol"; /* Contract Imports */ import { OVM_ECDSAContractAccount } from "../accounts/OVM_ECDSAContractAccount.sol"; import { OVM_ProxyEOA } from "../accounts/OVM_ProxyEOA.sol"; import { OVM_DeployerWhitelist } from "../predeploys/OVM_DeployerWhitelist.sol"; /** * @title OVM_ExecutionManager * @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed * environment allowing us to execute OVM transactions deterministically on either Layer 1 or * Layer 2. * The EM's run() function is the first function called during the execution of any * transaction on L2. * For each context-dependent EVM operation the EM has a function which implements a corresponding * OVM operation, which will read state from the State Manager contract. * The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any * context-dependent operations. * * Compiler used: solc * Runtime target: EVM */ contract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver { /******************************** * External Contract References * ********************************/ iOVM_SafetyChecker internal ovmSafetyChecker; iOVM_StateManager internal ovmStateManager; /******************************* * Execution Context Variables * *******************************/ GasMeterConfig internal gasMeterConfig; GlobalContext internal globalContext; TransactionContext internal transactionContext; MessageContext internal messageContext; TransactionRecord internal transactionRecord; MessageRecord internal messageRecord; /************************** * Gas Metering Constants * **************************/ address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5; uint256 constant NUISANCE_GAS_SLOAD = 20000; uint256 constant NUISANCE_GAS_SSTORE = 20000; uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000; uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100; uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000; /************************** * Default Context Values * **************************/ uint256 constant DEFAULT_UINT256 = 0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d; address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, GasMeterConfig memory _gasMeterConfig, GlobalContext memory _globalContext ) Lib_AddressResolver(_libAddressManager) { ovmSafetyChecker = iOVM_SafetyChecker(resolve("OVM_SafetyChecker")); gasMeterConfig = _gasMeterConfig; globalContext = _globalContext; _resetContext(); } /********************** * Function Modifiers * **********************/ /** * Applies dynamically-sized refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of the ovmOPCODE is fixed. * @param _cost Desired gas cost for the function after the refund. */ modifier netGasCost( uint256 _cost ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund everything *except* the specified cost. if (_cost < gasUsed) { transactionRecord.ovmGasRefund += gasUsed - _cost; } } /** * Applies a fixed-size gas refund to a transaction to account for the difference in execution * between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered. * @param _discount Amount of gas cost to refund for the ovmOPCODE. */ modifier fixedGasDiscount( uint256 _discount ) { uint256 gasProvided = gasleft(); _; uint256 gasUsed = gasProvided - gasleft(); // We want to refund the specified _discount, unless this risks underflow. if (_discount < gasUsed) { transactionRecord.ovmGasRefund += _discount; } else { // refund all we can without risking underflow. transactionRecord.ovmGasRefund += gasUsed; } } /** * Makes sure we're not inside a static context. */ modifier notStatic() { if (messageContext.isStatic == true) { _revertWithFlag(RevertFlag.STATIC_VIOLATION); } _; } /************************************ * Transaction Execution Entrypoint * ************************************/ /** * Starts the execution of a transaction via the OVM_ExecutionManager. * @param _transaction Transaction data to be executed. * @param _ovmStateManager iOVM_StateManager implementation providing account state. */ function run( Lib_OVMCodec.Transaction memory _transaction, address _ovmStateManager ) override public { // Make sure that run() is not re-enterable. This condition should awlways be satisfied // Once run has been called once, due to the behvaior of _isValidInput(). if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // Store our OVM_StateManager instance (significantly easier than attempting to pass the // address around in calldata). ovmStateManager = iOVM_StateManager(_ovmStateManager); // Make sure this function can't be called by anyone except the owner of the // OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because // this would make the `run` itself invalid. require( // This method may return false during fraud proofs, but always returns true in L2 nodes' State Manager precompile. ovmStateManager.isAuthenticated(msg.sender), "Only authenticated addresses in ovmStateManager can call this function" ); // Initialize the execution context, must be initialized before we perform any gas metering // or we'll throw a nuisance gas error. _initContext(_transaction); // TEMPORARY: Gas metering is disabled for minnet. // // Check whether we need to start a new epoch, do so if necessary. // _checkNeedsNewEpoch(_transaction.timestamp); // Make sure the transaction's gas limit is valid. We don't revert here because we reserve // reverts for INVALID_STATE_ACCESS. if (_isValidInput(_transaction) == false) { _resetContext(); return; } // TEMPORARY: Gas metering is disabled for minnet. // // Check gas right before the call to get total gas consumed by OVM transaction. // uint256 gasProvided = gasleft(); // Run the transaction, make sure to meter the gas usage. ovmCALL( _transaction.gasLimit - gasMeterConfig.minTransactionGasLimit, _transaction.entrypoint, _transaction.data ); // TEMPORARY: Gas metering is disabled for minnet. // // Update the cumulative gas based on the amount of gas used. // uint256 gasUsed = gasProvided - gasleft(); // _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin); // Wipe the execution context. _resetContext(); } /****************************** * Opcodes: Execution Context * ******************************/ /** * @notice Overrides CALLER. * @return _CALLER Address of the CALLER within the current message context. */ function ovmCALLER() override public view returns ( address _CALLER ) { return messageContext.ovmCALLER; } /** * @notice Overrides ADDRESS. * @return _ADDRESS Active ADDRESS within the current message context. */ function ovmADDRESS() override public view returns ( address _ADDRESS ) { return messageContext.ovmADDRESS; } /** * @notice Overrides TIMESTAMP. * @return _TIMESTAMP Value of the TIMESTAMP within the transaction context. */ function ovmTIMESTAMP() override public view returns ( uint256 _TIMESTAMP ) { return transactionContext.ovmTIMESTAMP; } /** * @notice Overrides NUMBER. * @return _NUMBER Value of the NUMBER within the transaction context. */ function ovmNUMBER() override public view returns ( uint256 _NUMBER ) { return transactionContext.ovmNUMBER; } /** * @notice Overrides GASLIMIT. * @return _GASLIMIT Value of the block's GASLIMIT within the transaction context. */ function ovmGASLIMIT() override public view returns ( uint256 _GASLIMIT ) { return transactionContext.ovmGASLIMIT; } /** * @notice Overrides CHAINID. * @return _CHAINID Value of the chain's CHAINID within the global context. */ function ovmCHAINID() override public view returns ( uint256 _CHAINID ) { return globalContext.ovmCHAINID; } /********************************* * Opcodes: L2 Execution Context * *********************************/ /** * @notice Specifies from which L1 rollup queue this transaction originated from. * @return _queueOrigin Address of the ovmL1QUEUEORIGIN within the current message context. */ function ovmL1QUEUEORIGIN() override public view returns ( Lib_OVMCodec.QueueOrigin _queueOrigin ) { return transactionContext.ovmL1QUEUEORIGIN; } /** * @notice Specifies which L1 account, if any, sent this transaction by calling enqueue(). * @return _l1TxOrigin Address of the account which sent the tx into L2 from L1. */ function ovmL1TXORIGIN() override public view returns ( address _l1TxOrigin ) { return transactionContext.ovmL1TXORIGIN; } /******************** * Opcodes: Halting * ********************/ /** * @notice Overrides REVERT. * @param _data Bytes data to pass along with the REVERT. */ function ovmREVERT( bytes memory _data ) override public { _revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data); } /****************************** * Opcodes: Contract Creation * ******************************/ /** * @notice Overrides CREATE. * @param _bytecode Code to be used to CREATE a new contract. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE( bytes memory _bytecode ) override public notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE address. address contractAddress = Lib_EthUtils.getAddressForCREATE( creator, _getAccountNonce(creator) ); return _createContract( contractAddress, _bytecode ); } /** * @notice Overrides CREATE2. * @param _bytecode Code to be used to CREATE2 a new contract. * @param _salt Value used to determine the contract's address. * @return Address of the created contract. * @return Revert data, if and only if the creation threw an exception. */ function ovmCREATE2( bytes memory _bytecode, bytes32 _salt ) override public notStatic fixedGasDiscount(40000) returns ( address, bytes memory ) { // Creator is always the current ADDRESS. address creator = ovmADDRESS(); // Check that the deployer is whitelisted, or // that arbitrary contract deployment has been enabled. _checkDeployerAllowed(creator); // Generate the correct CREATE2 address. address contractAddress = Lib_EthUtils.getAddressForCREATE2( creator, _bytecode, _salt ); return _createContract( contractAddress, _bytecode ); } /******************************* * Account Abstraction Opcodes * ******************************/ /** * Retrieves the nonce of the current ovmADDRESS. * @return _nonce Nonce of the current contract. */ function ovmGETNONCE() override public returns ( uint256 _nonce ) { return _getAccountNonce(ovmADDRESS()); } /** * Bumps the nonce of the current ovmADDRESS by one. */ function ovmINCREMENTNONCE() override public notStatic { address account = ovmADDRESS(); uint256 nonce = _getAccountNonce(account); // Prevent overflow. if (nonce + 1 > nonce) { _setAccountNonce(account, nonce + 1); } } /** * Creates a new EOA contract account, for account abstraction. * @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks * because the contract we're creating is trusted (no need to do safety checking or to * handle unexpected reverts). Doesn't need to return an address because the address is * assumed to be the user's actual address. * @param _messageHash Hash of a message signed by some user, for verification. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. */ function ovmCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) override public notStatic { // Recover the EOA address from the message hash and signature parameters. Since we do the // hashing in advance, we don't have handle different message hashing schemes. Even if this // function were to return the wrong address (rather than explicitly returning the zero // address), the rest of the transaction would simply fail (since there's no EOA account to // actually execute the transaction). address eoa = ecrecover( _messageHash, _v + 27, _r, _s ); // Invalid signature is a case we proactively handle with a revert. We could alternatively // have this function return a `success` boolean, but this is just easier. if (eoa == address(0)) { ovmREVERT(bytes("Signature provided for EOA contract creation is invalid.")); } // If the user already has an EOA account, then there's no need to perform this operation. if (_hasEmptyAccount(eoa) == false) { return; } // We always need to initialize the contract with the default account values. _initPendingAccount(eoa); // Temporarily set the current address so it's easier to access on L2. address prevADDRESS = messageContext.ovmADDRESS; messageContext.ovmADDRESS = eoa; // Now actually create the account and get its bytecode. We're not worried about reverts // (other than out of gas, which we can't capture anyway) because this contract is trusted. OVM_ProxyEOA proxyEOA = new OVM_ProxyEOA(0x4200000000000000000000000000000000000003); // Reset the address now that we're done deploying. messageContext.ovmADDRESS = prevADDRESS; // Commit the account with its final values. _commitPendingAccount( eoa, address(proxyEOA), keccak256(Lib_EthUtils.getCode(address(proxyEOA))) ); _setAccountNonce(eoa, 0); } /********************************* * Opcodes: Contract Interaction * *********************************/ /** * @notice Overrides CALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(100000) returns ( bool _success, bytes memory _returndata ) { // CALL updates the CALLER and ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; return _callContract( nextMessageContext, _gasLimit, _address, _calldata ); } /** * @notice Overrides STATICCALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmSTATICCALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(80000) returns ( bool _success, bytes memory _returndata ) { // STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static context. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _address; nextMessageContext.isStatic = true; return _callContract( nextMessageContext, _gasLimit, _address, _calldata ); } /** * @notice Overrides DELEGATECALL. * @param _gasLimit Amount of gas to be passed into this call. * @param _address Address of the contract to call. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function ovmDELEGATECALL( uint256 _gasLimit, address _address, bytes memory _calldata ) override public fixedGasDiscount(40000) returns ( bool _success, bytes memory _returndata ) { // DELEGATECALL does not change anything about the message context. MessageContext memory nextMessageContext = messageContext; return _callContract( nextMessageContext, _gasLimit, _address, _calldata ); } /************************************ * Opcodes: Contract Storage Access * ************************************/ /** * @notice Overrides SLOAD. * @param _key 32 byte key of the storage slot to load. * @return _value 32 byte value of the requested storage slot. */ function ovmSLOAD( bytes32 _key ) override public netGasCost(40000) returns ( bytes32 _value ) { // We always SLOAD from the storage of ADDRESS. address contractAddress = ovmADDRESS(); return _getContractStorage( contractAddress, _key ); } /** * @notice Overrides SSTORE. * @param _key 32 byte key of the storage slot to set. * @param _value 32 byte value for the storage slot. */ function ovmSSTORE( bytes32 _key, bytes32 _value ) override public notStatic netGasCost(60000) { // We always SSTORE to the storage of ADDRESS. address contractAddress = ovmADDRESS(); _putContractStorage( contractAddress, _key, _value ); } /********************************* * Opcodes: Contract Code Access * *********************************/ /** * @notice Overrides EXTCODECOPY. * @param _contract Address of the contract to copy code from. * @param _offset Offset in bytes from the start of contract code to copy beyond. * @param _length Total number of bytes to copy from the contract's code. * @return _code Bytes of code copied from the requested contract. */ function ovmEXTCODECOPY( address _contract, uint256 _offset, uint256 _length ) override public returns ( bytes memory _code ) { // `ovmEXTCODECOPY` is the only overridden opcode capable of producing exactly one byte of // return data. By blocking reads of one byte, we're able to use the condition that an // OVM_ExecutionManager function return value having a length of exactly one byte indicates // an error without an explicit revert. If users were able to read a single byte, they // could forcibly trigger behavior that should only be available to this contract. uint256 length = _length == 1 ? 2 : _length; return Lib_EthUtils.getCode( _getAccountEthAddress(_contract), _offset, length ); } /** * @notice Overrides EXTCODESIZE. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function ovmEXTCODESIZE( address _contract ) override public returns ( uint256 _EXTCODESIZE ) { return Lib_EthUtils.getCodeSize( _getAccountEthAddress(_contract) ); } /** * @notice Overrides EXTCODEHASH. * @param _contract Address of the contract to query the hash of. * @return _EXTCODEHASH Hash of the requested contract. */ function ovmEXTCODEHASH( address _contract ) override public returns ( bytes32 _EXTCODEHASH ) { return Lib_EthUtils.getCodeHash( _getAccountEthAddress(_contract) ); } /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view override returns ( uint256 _maxTransactionGasLimit ) { return gasMeterConfig.maxTransactionGasLimit; } /******************************************** * Public Functions: Deployment Whitelisting * ********************************************/ /** * Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2, and reverts if not. * @param _deployerAddress Address attempting to deploy a contract. */ function _checkDeployerAllowed( address _deployerAddress ) internal { // From an OVM semantics perspective, this will appear identical to // the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to. (bool success, bytes memory data) = ovmCALL( gasleft(), 0x4200000000000000000000000000000000000002, abi.encodeWithSignature("isDeployerAllowed(address)", _deployerAddress) ); bool isAllowed = abi.decode(data, (bool)); if (!isAllowed || !success) { _revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED); } } /******************************************** * Internal Functions: Contract Interaction * ********************************************/ /** * Creates a new contract and associates it with some contract address. * @param _contractAddress Address to associate the created contract with. * @param _bytecode Bytecode to be used to create the contract. * @return Final OVM contract address. * @return Revertdata, if and only if the creation threw an exception. */ function _createContract( address _contractAddress, bytes memory _bytecode ) internal returns ( address, bytes memory ) { // We always update the nonce of the creating account, even if the creation fails. _setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1); // We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point // to the contract's associated address and CALLER to point to the previous ADDRESS. MessageContext memory nextMessageContext = messageContext; nextMessageContext.ovmCALLER = messageContext.ovmADDRESS; nextMessageContext.ovmADDRESS = _contractAddress; // Run the common logic which occurs between call-type and create-type messages, // passing in the creation bytecode and `true` to trigger create-specific logic. (bool success, bytes memory data) = _handleExternalMessage( nextMessageContext, gasleft(), _contractAddress, _bytecode, true ); // Yellow paper requires that address returned is zero if the contract deployment fails. return ( success ? _contractAddress : address(0), data ); } /** * Calls the deployed contract associated with a given address. * @param _nextMessageContext Message context to be used for the call. * @param _gasLimit Amount of gas to be passed into this call. * @param _contract OVM address to be called. * @param _calldata Data to send along with the call. * @return _success Whether or not the call returned (rather than reverted). * @return _returndata Data returned by the call. */ function _callContract( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { // We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2 geth. // So, we block calls to these addresses since they are not safe to run as an OVM contract itself. if ( (uint256(_contract) & uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000)) == uint256(0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000) ) { // EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604 return (true, hex''); } // Both 0x0000... and the EVM precompiles have the same address on L1 and L2 --> no trie lookup needed. address codeContractAddress = uint(_contract) < 100 ? _contract : _getAccountEthAddress(_contract); return _handleExternalMessage( _nextMessageContext, _gasLimit, codeContractAddress, _calldata, false ); } /** * Handles all interactions which involve the execution manager calling out to untrusted code (both calls and creates). * Ensures that OVM-related measures are enforced, including L2 gas refunds, nuisance gas, and flagged reversions. * * @param _nextMessageContext Message context to be used for the external message. * @param _gasLimit Amount of gas to be passed into this message. * @param _contract OVM address being called or deployed to * @param _data Data for the message (either calldata or creation code) * @param _isCreate Whether this is a create-type message. * @return Whether or not the message (either a call or deployment) succeeded. * @return Data returned by the message. */ function _handleExternalMessage( MessageContext memory _nextMessageContext, uint256 _gasLimit, address _contract, bytes memory _data, bool _isCreate ) internal returns ( bool, bytes memory ) { // We need to switch over to our next message context for the duration of this call. MessageContext memory prevMessageContext = messageContext; _switchMessageContext(prevMessageContext, _nextMessageContext); // Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs // expensive by touching a lot of different accounts or storage slots. Since most contracts // only use a few storage slots during any given transaction, this shouldn't be a limiting // factor. uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft; uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit); messageRecord.nuisanceGasLeft = nuisanceGasLimit; // Make the call and make sure to pass in the gas limit. Another instance of hidden // complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert // behavior can be controlled. In particular, we enforce that flags are passed through // revert data as to retrieve execution metadata that would normally be reverted out of // existence. bool success; bytes memory returndata; if (_isCreate) { // safeCREATE() is a function which replicates a CREATE message, but uses return values // Which match that of CALL (i.e. bool, bytes). This allows many security checks to be // to be shared between untrusted call and create call frames. (success, returndata) = address(this).call( abi.encodeWithSelector( this.safeCREATE.selector, _gasLimit, _data, _contract ) ); } else { (success, returndata) = _contract.call{gas: _gasLimit}(_data); } // Switch back to the original message context now that we're out of the call. _switchMessageContext(_nextMessageContext, prevMessageContext); // Assuming there were no reverts, the message record should be accurate here. We'll update // this value in the case of a revert. uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft; // Reverts at this point are completely OK, but we need to make a few updates based on the // information passed through the revert. if (success == false) { ( RevertFlag flag, uint256 nuisanceGasLeftPostRevert, uint256 ovmGasRefund, bytes memory returndataFromFlag ) = _decodeRevertData(returndata); // INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the // parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must // halt any further transaction execution that could impact the execution result. if (flag == RevertFlag.INVALID_STATE_ACCESS) { _revertWithFlag(flag); } // INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't // dependent on the input state, so we can just handle them like standard reverts. Our only change here // is to record the gas refund reported by the call (enforced by safety checking). if ( flag == RevertFlag.INTENTIONAL_REVERT || flag == RevertFlag.UNSAFE_BYTECODE || flag == RevertFlag.STATIC_VIOLATION || flag == RevertFlag.CREATOR_NOT_ALLOWED ) { transactionRecord.ovmGasRefund = ovmGasRefund; } // INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the // flag, *not* the full encoded flag. All other revert types return no data. if ( flag == RevertFlag.INTENTIONAL_REVERT || _isCreate ) { returndata = returndataFromFlag; } else { returndata = hex''; } // Reverts mean we need to use up whatever "nuisance gas" was used by the call. // EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message // to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they // run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags // will simply pass up the remaining nuisance gas. nuisanceGasLeft = nuisanceGasLeftPostRevert; } // We need to reset the nuisance gas back to its original value minus the amount used here. messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft); return ( success, returndata ); } /** * Handles the creation-specific safety measures required for OVM contract deployment. * This function sanitizes the return types for creation messages to match calls (bool, bytes), * by being an external function which the EM can call, that mimics the success/fail case of the CREATE. * This allows for consistent handling of both types of messages in _handleExternalMessage(). * Having this step occur as a separate call frame also allows us to easily revert the * contract deployment in the event that the code is unsafe. * * @param _gasLimit Amount of gas to be passed into this creation. * @param _creationCode Code to pass into CREATE for deployment. * @param _address OVM address being deployed to. */ function safeCREATE( uint _gasLimit, bytes memory _creationCode, address _address ) external { // The only way this should callable is from within _createContract(), // and it should DEFINITELY not be callable by a non-EM code contract. if (msg.sender != address(this)) { return; } // Check that there is not already code at this address. if (_hasEmptyAccount(_address) == false) { // Note: in the EVM, this case burns all allotted gas. For improved // developer experience, we do return the remaining gas. _revertWithFlag( RevertFlag.CREATE_COLLISION, Lib_ErrorUtils.encodeRevertString("A contract has already been deployed to this address") ); } // Check the creation bytecode against the OVM_SafetyChecker. if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, Lib_ErrorUtils.encodeRevertString("Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?") ); } // We always need to initialize the contract with the default account values. _initPendingAccount(_address); // Actually execute the EVM create message. // NOTE: The inline assembly below means we can NOT make any evm calls between here and then. address ethAddress = Lib_EthUtils.createContract(_creationCode); if (ethAddress == address(0)) { // If the creation fails, the EVM lets us grab its revert data. This may contain a revert flag // to be used above in _handleExternalMessage, so we pass the revert data back up unmodified. assembly { returndatacopy(0,0,returndatasize()) revert(0, returndatasize()) } } // Again simply checking that the deployed code is safe too. Contracts can generate // arbitrary deployment code, so there's no easy way to analyze this beforehand. bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress); if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) { _revertWithFlag( RevertFlag.UNSAFE_BYTECODE, Lib_ErrorUtils.encodeRevertString("Constructor attempted to deploy unsafe bytecode.") ); } // Contract creation didn't need to be reverted and the bytecode is safe. We finish up by // associating the desired address with the newly created contract's code hash and address. _commitPendingAccount( _address, ethAddress, Lib_EthUtils.getCodeHash(ethAddress) ); } /****************************************** * Internal Functions: State Manipulation * ******************************************/ /** * Checks whether an account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account exists. */ function _hasAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasAccount(_address); } /** * Checks whether a known empty account exists within the OVM_StateManager. * @param _address Address of the account to check. * @return _exists Whether or not the account empty exists. */ function _hasEmptyAccount( address _address ) internal returns ( bool _exists ) { _checkAccountLoad(_address); return ovmStateManager.hasEmptyAccount(_address); } /** * Sets the nonce of an account. * @param _address Address of the account to modify. * @param _nonce New account nonce. */ function _setAccountNonce( address _address, uint256 _nonce ) internal { _checkAccountChange(_address); ovmStateManager.setAccountNonce(_address, _nonce); } /** * Gets the nonce of an account. * @param _address Address of the account to access. * @return _nonce Nonce of the account. */ function _getAccountNonce( address _address ) internal returns ( uint256 _nonce ) { _checkAccountLoad(_address); return ovmStateManager.getAccountNonce(_address); } /** * Retrieves the Ethereum address of an account. * @param _address Address of the account to access. * @return _ethAddress Corresponding Ethereum address. */ function _getAccountEthAddress( address _address ) internal returns ( address _ethAddress ) { _checkAccountLoad(_address); return ovmStateManager.getAccountEthAddress(_address); } /** * Creates the default account object for the given address. * @param _address Address of the account create. */ function _initPendingAccount( address _address ) internal { // Although it seems like `_checkAccountChange` would be more appropriate here, we don't // actually consider an account "changed" until it's inserted into the state (in this case // by `_commitPendingAccount`). _checkAccountLoad(_address); ovmStateManager.initPendingAccount(_address); } /** * Stores additional relevant data for a new account, thereby "committing" it to the state. * This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract * creation. * @param _address Address of the account to commit. * @param _ethAddress Address of the associated deployed contract. * @param _codeHash Hash of the code stored at the address. */ function _commitPendingAccount( address _address, address _ethAddress, bytes32 _codeHash ) internal { _checkAccountChange(_address); ovmStateManager.commitPendingAccount( _address, _ethAddress, _codeHash ); } /** * Retrieves the value of a storage slot. * @param _contract Address of the contract to query. * @param _key 32 byte key of the storage slot. * @return _value 32 byte storage slot value. */ function _getContractStorage( address _contract, bytes32 _key ) internal returns ( bytes32 _value ) { _checkContractStorageLoad(_contract, _key); return ovmStateManager.getContractStorage(_contract, _key); } /** * Sets the value of a storage slot. * @param _contract Address of the contract to modify. * @param _key 32 byte key of the storage slot. * @param _value 32 byte storage slot value. */ function _putContractStorage( address _contract, bytes32 _key, bytes32 _value ) internal { // We don't set storage if the value didn't change. Although this acts as a convenient // optimization, it's also necessary to avoid the case in which a contract with no storage // attempts to store the value "0" at any key. Putting this value (and therefore requiring // that the value be committed into the storage trie after execution) would incorrectly // modify the storage root. if (_getContractStorage(_contract, _key) == _value) { return; } _checkContractStorageChange(_contract, _key); ovmStateManager.putContractStorage(_contract, _key, _value); } /** * Validation whenever a contract needs to be loaded. Checks that the account exists, charges * nuisance gas if the account hasn't been loaded before. * @param _address Address of the account to load. */ function _checkAccountLoad( address _address ) internal { // See `_checkContractStorageLoad` for more information. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // See `_checkContractStorageLoad` for more information. if (ovmStateManager.hasAccount(_address) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the account has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that an account is loaded. ( bool _wasAccountAlreadyLoaded ) = ovmStateManager.testAndSetAccountLoaded(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyLoaded == false) { _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a contract needs to be changed. Checks that the account exists, charges * nuisance gas if the account hasn't been changed before. * @param _address Address of the account to change. */ function _checkAccountChange( address _address ) internal { // Start by checking for a load as we only want to charge nuisance gas proportional to // contract size once. _checkAccountLoad(_address); // Check whether the account has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that an account is changed. ( bool _wasAccountAlreadyChanged ) = ovmStateManager.testAndSetAccountChanged(_address); // If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based // on the size of the contract code. if (_wasAccountAlreadyChanged == false) { ovmStateManager.incrementTotalUncommittedAccounts(); _useNuisanceGas( (Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address)) * NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT ); } } /** * Validation whenever a slot needs to be loaded. Checks that the account exists, charges * nuisance gas if the slot hasn't been loaded before. * @param _contract Address of the account to load from. * @param _key 32 byte key to load. */ function _checkContractStorageLoad( address _contract, bytes32 _key ) internal { // Another case of hidden complexity. If we didn't enforce this requirement, then a // contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail // on L1 but not on L2. A contract could use this behavior to prevent the // OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS // allows us to also charge for the full message nuisance gas, because you deserve that for // trying to break the contract in this way. if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) { _revertWithFlag(RevertFlag.OUT_OF_GAS); } // We need to make sure that the transaction isn't trying to access storage that hasn't // been provided to the OVM_StateManager. We'll immediately abort if this is the case. // We know that we have enough gas to do this check because of the above test. if (ovmStateManager.hasContractStorage(_contract, _key) == false) { _revertWithFlag(RevertFlag.INVALID_STATE_ACCESS); } // Check whether the slot has been loaded before and mark it as loaded if not. We need // this because "nuisance gas" only applies to the first time that a slot is loaded. ( bool _wasContractStorageAlreadyLoaded ) = ovmStateManager.testAndSetContractStorageLoaded(_contract, _key); // If we hadn't already loaded the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyLoaded == false) { _useNuisanceGas(NUISANCE_GAS_SLOAD); } } /** * Validation whenever a slot needs to be changed. Checks that the account exists, charges * nuisance gas if the slot hasn't been changed before. * @param _contract Address of the account to change. * @param _key 32 byte key to change. */ function _checkContractStorageChange( address _contract, bytes32 _key ) internal { // Start by checking for load to make sure we have the storage slot and that we charge the // "nuisance gas" necessary to prove the storage slot state. _checkContractStorageLoad(_contract, _key); // Check whether the slot has been changed before and mark it as changed if not. We need // this because "nuisance gas" only applies to the first time that a slot is changed. ( bool _wasContractStorageAlreadyChanged ) = ovmStateManager.testAndSetContractStorageChanged(_contract, _key); // If we hadn't already changed the account, then we'll need to charge some fixed amount of // "nuisance gas". if (_wasContractStorageAlreadyChanged == false) { // Changing a storage slot means that we're also going to have to change the // corresponding account, so do an account change check. _checkAccountChange(_contract); ovmStateManager.incrementTotalUncommittedContractStorage(); _useNuisanceGas(NUISANCE_GAS_SSTORE); } } /************************************ * Internal Functions: Revert Logic * ************************************/ /** * Simple encoding for revert data. * @param _flag Flag to revert with. * @param _data Additional user-provided revert data. * @return _revertdata Encoded revert data. */ function _encodeRevertData( RevertFlag _flag, bytes memory _data ) internal view returns ( bytes memory _revertdata ) { // Out of gas and create exceptions will fundamentally return no data, so simulating it shouldn't either. if ( _flag == RevertFlag.OUT_OF_GAS ) { return bytes(''); } // INVALID_STATE_ACCESS doesn't need to return any data other than the flag. if (_flag == RevertFlag.INVALID_STATE_ACCESS) { return abi.encode( _flag, 0, 0, bytes('') ); } // Just ABI encode the rest of the parameters. return abi.encode( _flag, messageRecord.nuisanceGasLeft, transactionRecord.ovmGasRefund, _data ); } /** * Simple decoding for revert data. * @param _revertdata Revert data to decode. * @return _flag Flag used to revert. * @return _nuisanceGasLeft Amount of nuisance gas unused by the message. * @return _ovmGasRefund Amount of gas refunded during the message. * @return _data Additional user-provided revert data. */ function _decodeRevertData( bytes memory _revertdata ) internal pure returns ( RevertFlag _flag, uint256 _nuisanceGasLeft, uint256 _ovmGasRefund, bytes memory _data ) { // A length of zero means the call ran out of gas, just return empty data. if (_revertdata.length == 0) { return ( RevertFlag.OUT_OF_GAS, 0, 0, bytes('') ); } // ABI decode the incoming data. return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes)); } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. * @param _data Additional user-provided data. */ function _revertWithFlag( RevertFlag _flag, bytes memory _data ) internal view { bytes memory revertdata = _encodeRevertData( _flag, _data ); assembly { revert(add(revertdata, 0x20), mload(revertdata)) } } /** * Causes a message to revert or abort. * @param _flag Flag to revert with. */ function _revertWithFlag( RevertFlag _flag ) internal { _revertWithFlag(_flag, bytes('')); } /****************************************** * Internal Functions: Nuisance Gas Logic * ******************************************/ /** * Computes the nuisance gas limit from the gas limit. * @dev This function is currently using a naive implementation whereby the nuisance gas limit * is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that * this implementation is perfectly fine, but we may change this formula later. * @param _gasLimit Gas limit to compute from. * @return _nuisanceGasLimit Computed nuisance gas limit. */ function _getNuisanceGasLimit( uint256 _gasLimit ) internal view returns ( uint256 _nuisanceGasLimit ) { return _gasLimit < gasleft() ? _gasLimit : gasleft(); } /** * Uses a certain amount of nuisance gas. * @param _amount Amount of nuisance gas to use. */ function _useNuisanceGas( uint256 _amount ) internal { // Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas // refund to be given at the end of the transaction. if (messageRecord.nuisanceGasLeft < _amount) { _revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS); } messageRecord.nuisanceGasLeft -= _amount; } /************************************ * Internal Functions: Gas Metering * ************************************/ /** * Checks whether a transaction needs to start a new epoch and does so if necessary. * @param _timestamp Transaction timestamp. */ function _checkNeedsNewEpoch( uint256 _timestamp ) internal { if ( _timestamp >= ( _getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP) + gasMeterConfig.secondsPerEpoch ) ) { _putGasMetadata( GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP, _timestamp ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS ) ); _putGasMetadata( GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS, _getGasMetadata( GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS ) ); } } /** * Validates the input values of a transaction. * @return _valid Whether or not the transaction data is valid. */ function _isValidInput( Lib_OVMCodec.Transaction memory _transaction ) view internal returns ( bool ) { // Prevent reentrancy to run(): // This check prevents calling run with the default ovmNumber. // Combined with the first check in run(): // if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; } // It should be impossible to re-enter since run() returns before any other call frames are created. // Since this value is already being written to storage, we save much gas compared to // using the standard nonReentrant pattern. if (_transaction.blockNumber == DEFAULT_UINT256) { return false; } if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) { return false; } return true; } /** * Validates the gas limit for a given transaction. * @param _gasLimit Gas limit provided by the transaction. * param _queueOrigin Queue from which the transaction originated. * @return _valid Whether or not the gas limit is valid. */ function _isValidGasLimit( uint256 _gasLimit, Lib_OVMCodec.QueueOrigin // _queueOrigin ) view internal returns ( bool _valid ) { // Always have to be below the maximum gas limit. if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) { return false; } // Always have to be above the minimum gas limit. if (_gasLimit < gasMeterConfig.minTransactionGasLimit) { return false; } // TEMPORARY: Gas metering is disabled for minnet. return true; // GasMetadataKey cumulativeGasKey; // GasMetadataKey prevEpochGasKey; // if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS; // } else { // cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; // prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS; // } // return ( // ( // _getGasMetadata(cumulativeGasKey) // - _getGasMetadata(prevEpochGasKey) // + _gasLimit // ) < gasMeterConfig.maxGasPerQueuePerEpoch // ); } /** * Updates the cumulative gas after a transaction. * @param _gasUsed Gas used by the transaction. * @param _queueOrigin Queue from which the transaction originated. */ function _updateCumulativeGas( uint256 _gasUsed, Lib_OVMCodec.QueueOrigin _queueOrigin ) internal { GasMetadataKey cumulativeGasKey; if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) { cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS; } else { cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS; } _putGasMetadata( cumulativeGasKey, ( _getGasMetadata(cumulativeGasKey) + gasMeterConfig.minTransactionGasLimit + _gasUsed - transactionRecord.ovmGasRefund ) ); } /** * Retrieves the value of a gas metadata key. * @param _key Gas metadata key to retrieve. * @return _value Value stored at the given key. */ function _getGasMetadata( GasMetadataKey _key ) internal returns ( uint256 _value ) { return uint256(_getContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)) )); } /** * Sets the value of a gas metadata key. * @param _key Gas metadata key to set. * @param _value Value to store at the given key. */ function _putGasMetadata( GasMetadataKey _key, uint256 _value ) internal { _putContractStorage( GAS_METADATA_ADDRESS, bytes32(uint256(_key)), bytes32(uint256(_value)) ); } /***************************************** * Internal Functions: Execution Context * *****************************************/ /** * Swaps over to a new message context. * @param _prevMessageContext Context we're switching from. * @param _nextMessageContext Context we're switching to. */ function _switchMessageContext( MessageContext memory _prevMessageContext, MessageContext memory _nextMessageContext ) internal { // Avoid unnecessary the SSTORE. if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) { messageContext.ovmCALLER = _nextMessageContext.ovmCALLER; } // Avoid unnecessary the SSTORE. if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) { messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS; } // Avoid unnecessary the SSTORE. if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) { messageContext.isStatic = _nextMessageContext.isStatic; } } /** * Initializes the execution context. * @param _transaction OVM transaction being executed. */ function _initContext( Lib_OVMCodec.Transaction memory _transaction ) internal { transactionContext.ovmTIMESTAMP = _transaction.timestamp; transactionContext.ovmNUMBER = _transaction.blockNumber; transactionContext.ovmTXGASLIMIT = _transaction.gasLimit; transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin; transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin; transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch; messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit); } /** * Resets the transaction and message context. */ function _resetContext() internal { transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS; transactionContext.ovmTIMESTAMP = DEFAULT_UINT256; transactionContext.ovmNUMBER = DEFAULT_UINT256; transactionContext.ovmGASLIMIT = DEFAULT_UINT256; transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256; transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE; transactionRecord.ovmGasRefund = DEFAULT_UINT256; messageContext.ovmCALLER = DEFAULT_ADDRESS; messageContext.ovmADDRESS = DEFAULT_ADDRESS; messageContext.isStatic = false; messageRecord.nuisanceGasLeft = DEFAULT_UINT256; // Reset the ovmStateManager. ovmStateManager = iOVM_StateManager(address(0)); } /***************************** * L2-only Helper Functions * *****************************/ /** * Unreachable helper function for simulating eth_calls with an OVM message context. * This function will throw an exception in all cases other than when used as a custom entrypoint in L2 Geth to simulate eth_call. * @param _transaction the message transaction to simulate. * @param _from the OVM account the simulated call should be from. */ function simulateMessage( Lib_OVMCodec.Transaction memory _transaction, address _from, iOVM_StateManager _ovmStateManager ) external returns ( bool, bytes memory ) { // Prevent this call from having any effect unless in a custom-set VM frame require(msg.sender == address(0)); ovmStateManager = _ovmStateManager; _initContext(_transaction); messageRecord.nuisanceGasLeft = uint(-1); messageContext.ovmADDRESS = _from; bool isCreate = _transaction.entrypoint == address(0); if (isCreate) { (address created, bytes memory revertData) = ovmCREATE(_transaction.data); if (created == address(0)) { return (false, revertData); } else { // The eth_call RPC endpoint for to = undefined will return the deployed bytecode // in the success case, differing from standard create messages. return (true, Lib_EthUtils.getCode(created)); } } else { return ovmCALL( _transaction.gasLimit, _transaction.entrypoint, _transaction.data ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol"; /* Interface Imports */ import { iOVM_DeployerWhitelist } from "../../iOVM/predeploys/iOVM_DeployerWhitelist.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title OVM_DeployerWhitelist * @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the * initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts * which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an * ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted. * * Compiler used: solc * Runtime target: OVM */ contract OVM_DeployerWhitelist is iOVM_DeployerWhitelist { /********************** * Contract Constants * **********************/ bytes32 internal constant KEY_INITIALIZED = 0x0000000000000000000000000000000000000000000000000000000000000010; bytes32 internal constant KEY_OWNER = 0x0000000000000000000000000000000000000000000000000000000000000011; bytes32 internal constant KEY_ALLOW_ARBITRARY_DEPLOYMENT = 0x0000000000000000000000000000000000000000000000000000000000000012; /********************** * Function Modifiers * **********************/ /** * Blocks functions to anyone except the contract owner. */ modifier onlyOwner() { address owner = Lib_Bytes32Utils.toAddress( Lib_SafeExecutionManagerWrapper.safeSLOAD( KEY_OWNER ) ); Lib_SafeExecutionManagerWrapper.safeREQUIRE( Lib_SafeExecutionManagerWrapper.safeCALLER() == owner, "Function can only be called by the owner of this contract." ); _; } /******************** * Public Functions * ********************/ /** * Initializes the whitelist. * @param _owner Address of the owner for this contract. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function initialize( address _owner, bool _allowArbitraryDeployment ) override public { bool initialized = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED) ); if (initialized == true) { return; } Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_INITIALIZED, Lib_Bytes32Utils.fromBool(true) ); Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_OWNER, Lib_Bytes32Utils.fromAddress(_owner) ); Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_ALLOW_ARBITRARY_DEPLOYMENT, Lib_Bytes32Utils.fromBool(_allowArbitraryDeployment) ); } /** * Gets the owner of the whitelist. */ function getOwner() override public returns( address ) { return Lib_Bytes32Utils.toAddress( Lib_SafeExecutionManagerWrapper.safeSLOAD( KEY_OWNER ) ); } /** * Adds or removes an address from the deployment whitelist. * @param _deployer Address to update permissions for. * @param _isWhitelisted Whether or not the address is whitelisted. */ function setWhitelistedDeployer( address _deployer, bool _isWhitelisted ) override public onlyOwner { Lib_SafeExecutionManagerWrapper.safeSSTORE( Lib_Bytes32Utils.fromAddress(_deployer), Lib_Bytes32Utils.fromBool(_isWhitelisted) ); } /** * Updates the owner of this contract. * @param _owner Address of the new owner. */ function setOwner( address _owner ) override public onlyOwner { Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_OWNER, Lib_Bytes32Utils.fromAddress(_owner) ); } /** * Updates the arbitrary deployment flag. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */ function setAllowArbitraryDeployment( bool _allowArbitraryDeployment ) override public onlyOwner { Lib_SafeExecutionManagerWrapper.safeSSTORE( KEY_ALLOW_ARBITRARY_DEPLOYMENT, Lib_Bytes32Utils.fromBool(_allowArbitraryDeployment) ); } /** * Permanently enables arbitrary contract deployment and deletes the owner. */ function enableArbitraryContractDeployment() override public onlyOwner { setAllowArbitraryDeployment(true); setOwner(address(0)); } /** * Checks whether an address is allowed to deploy contracts. * @param _deployer Address to check. * @return _allowed Whether or not the address can deploy contracts. */ function isDeployerAllowed( address _deployer ) override public returns ( bool _allowed ) { bool initialized = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED) ); if (initialized == false) { return true; } bool allowArbitraryDeployment = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_ALLOW_ARBITRARY_DEPLOYMENT) ); if (allowArbitraryDeployment == true) { return true; } bool isWhitelisted = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD( Lib_Bytes32Utils.fromAddress(_deployer) ) ); return isWhitelisted; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_ECDSAContractAccount */ interface iOVM_ECDSAContractAccount { /******************** * Public Functions * ********************/ function execute( bytes memory _transaction, Lib_OVMCodec.EOASignatureType _signatureType, uint8 _v, bytes32 _r, bytes32 _s ) external returns (bool _success, bytes memory _returndata); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; interface iOVM_ExecutionManager { /********** * Enums * *********/ enum RevertFlag { OUT_OF_GAS, INTENTIONAL_REVERT, EXCEEDS_NUISANCE_GAS, INVALID_STATE_ACCESS, UNSAFE_BYTECODE, CREATE_COLLISION, STATIC_VIOLATION, CREATOR_NOT_ALLOWED } enum GasMetadataKey { CURRENT_EPOCH_START_TIMESTAMP, CUMULATIVE_SEQUENCER_QUEUE_GAS, CUMULATIVE_L1TOL2_QUEUE_GAS, PREV_EPOCH_SEQUENCER_QUEUE_GAS, PREV_EPOCH_L1TOL2_QUEUE_GAS } /*********** * Structs * ***********/ struct GasMeterConfig { uint256 minTransactionGasLimit; uint256 maxTransactionGasLimit; uint256 maxGasPerQueuePerEpoch; uint256 secondsPerEpoch; } struct GlobalContext { uint256 ovmCHAINID; } struct TransactionContext { Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN; uint256 ovmTIMESTAMP; uint256 ovmNUMBER; uint256 ovmGASLIMIT; uint256 ovmTXGASLIMIT; address ovmL1TXORIGIN; } struct TransactionRecord { uint256 ovmGasRefund; } struct MessageContext { address ovmCALLER; address ovmADDRESS; bool isStatic; } struct MessageRecord { uint256 nuisanceGasLeft; } /************************************ * Transaction Execution Entrypoint * ************************************/ function run( Lib_OVMCodec.Transaction calldata _transaction, address _txStateManager ) external; /******************* * Context Opcodes * *******************/ function ovmCALLER() external view returns (address _caller); function ovmADDRESS() external view returns (address _address); function ovmTIMESTAMP() external view returns (uint256 _timestamp); function ovmNUMBER() external view returns (uint256 _number); function ovmGASLIMIT() external view returns (uint256 _gasLimit); function ovmCHAINID() external view returns (uint256 _chainId); /********************** * L2 Context Opcodes * **********************/ function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin); function ovmL1TXORIGIN() external view returns (address _l1TxOrigin); /******************* * Halting Opcodes * *******************/ function ovmREVERT(bytes memory _data) external; /***************************** * Contract Creation Opcodes * *****************************/ function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata); function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata); /******************************* * Account Abstraction Opcodes * ******************************/ function ovmGETNONCE() external returns (uint256 _nonce); function ovmINCREMENTNONCE() external; function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external; /**************************** * Contract Calling Opcodes * ****************************/ function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata); /**************************** * Contract Storage Opcodes * ****************************/ function ovmSLOAD(bytes32 _key) external returns (bytes32 _value); function ovmSSTORE(bytes32 _key, bytes32 _value) external; /************************* * Contract Code Opcodes * *************************/ function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code); function ovmEXTCODESIZE(address _contract) external returns (uint256 _size); function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash); /*************************************** * Public Functions: Execution Context * ***************************************/ function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_SafetyChecker */ interface iOVM_SafetyChecker { /******************** * Public Functions * ********************/ function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; /** * @title iOVM_StateManager */ interface iOVM_StateManager { /******************* * Data Structures * *******************/ enum ItemState { ITEM_UNTOUCHED, ITEM_LOADED, ITEM_CHANGED, ITEM_COMMITTED } /*************************** * Public Functions: Misc * ***************************/ function isAuthenticated(address _address) external view returns (bool); /*************************** * Public Functions: Setup * ***************************/ function owner() external view returns (address _owner); function ovmExecutionManager() external view returns (address _ovmExecutionManager); function setExecutionManager(address _ovmExecutionManager) external; /************************************ * Public Functions: Account Access * ************************************/ function putAccount(address _address, Lib_OVMCodec.Account memory _account) external; function putEmptyAccount(address _address) external; function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account); function hasAccount(address _address) external view returns (bool _exists); function hasEmptyAccount(address _address) external view returns (bool _exists); function setAccountNonce(address _address, uint256 _nonce) external; function getAccountNonce(address _address) external view returns (uint256 _nonce); function getAccountEthAddress(address _address) external view returns (address _ethAddress); function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot); function initPendingAccount(address _address) external; function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external; function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded); function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged); function commitAccount(address _address) external returns (bool _wasAccountCommitted); function incrementTotalUncommittedAccounts() external; function getTotalUncommittedAccounts() external view returns (uint256 _total); function wasAccountChanged(address _address) external view returns (bool); function wasAccountCommitted(address _address) external view returns (bool); /************************************ * Public Functions: Storage Access * ************************************/ function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external; function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value); function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists); function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded); function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged); function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted); function incrementTotalUncommittedContractStorage() external; function getTotalUncommittedContractStorage() external view returns (uint256 _total); function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool); function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title iOVM_DeployerWhitelist */ interface iOVM_DeployerWhitelist { /******************** * Public Functions * ********************/ function initialize(address _owner, bool _allowArbitraryDeployment) external; function getOwner() external returns (address _owner); function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external; function setOwner(address _newOwner) external; function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external; function enableArbitraryContractDeployment() external; function isDeployerAllowed(address _deployer) external returns (bool _allowed); } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; import { Lib_SafeExecutionManagerWrapper } from "../../libraries/wrappers/Lib_SafeExecutionManagerWrapper.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum EOASignatureType { EIP155_TRANSACTION, ETH_SIGNED_MESSAGE } enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct Account { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; address ethAddress; bool isFresh; } 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; } struct EIP155Transaction { uint256 nonce; uint256 gasPrice; uint256 gasLimit; address to; uint256 value; bytes data; uint256 chainId; } /********************** * Internal Functions * **********************/ /** * Decodes an EOA transaction (i.e., native Ethereum RLP encoding). * @param _transaction Encoded EOA transaction. * @return Transaction decoded into a struct. */ function decodeEIP155Transaction( bytes memory _transaction, bool _isEthSignedMessage ) internal pure returns ( EIP155Transaction memory ) { if (_isEthSignedMessage) { ( uint256 _nonce, uint256 _gasLimit, uint256 _gasPrice, uint256 _chainId, address _to, bytes memory _data ) = abi.decode( _transaction, (uint256, uint256, uint256, uint256, address ,bytes) ); return EIP155Transaction({ nonce: _nonce, gasPrice: _gasPrice, gasLimit: _gasLimit, to: _to, value: 0, data: _data, chainId: _chainId }); } else { Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_transaction); return EIP155Transaction({ nonce: Lib_RLPReader.readUint256(decoded[0]), gasPrice: Lib_RLPReader.readUint256(decoded[1]), gasLimit: Lib_RLPReader.readUint256(decoded[2]), to: Lib_RLPReader.readAddress(decoded[3]), value: Lib_RLPReader.readUint256(decoded[4]), data: Lib_RLPReader.readBytes(decoded[5]), chainId: Lib_RLPReader.readUint256(decoded[6]) }); } } /** * Decompresses a compressed EIP155 transaction. * @param _transaction Compressed EIP155 transaction bytes. * @return Transaction parsed into a struct. */ function decompressEIP155Transaction( bytes memory _transaction ) internal returns ( EIP155Transaction memory ) { return EIP155Transaction({ gasLimit: Lib_BytesUtils.toUint24(_transaction, 0), gasPrice: uint256(Lib_BytesUtils.toUint24(_transaction, 3)) * 1000000, nonce: Lib_BytesUtils.toUint24(_transaction, 6), to: Lib_BytesUtils.toAddress(_transaction, 9), data: Lib_BytesUtils.slice(_transaction, 29), chainId: Lib_SafeExecutionManagerWrapper.safeCHAINID(), value: 0 }); } /** * Encodes an EOA transaction back into the original transaction. * @param _transaction EIP155transaction to encode. * @param _isEthSignedMessage Whether or not this was an eth signed message. * @return Encoded transaction. */ function encodeEIP155Transaction( EIP155Transaction memory _transaction, bool _isEthSignedMessage ) internal pure returns ( bytes memory ) { if (_isEthSignedMessage) { return abi.encode( _transaction.nonce, _transaction.gasLimit, _transaction.gasPrice, _transaction.chainId, _transaction.to, _transaction.data ); } else { bytes[] memory raw = new bytes[](9); raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce); raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice); raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit); if (_transaction.to == address(0)) { raw[3] = Lib_RLPWriter.writeBytes(''); } else { raw[3] = Lib_RLPWriter.writeAddress(_transaction.to); } raw[4] = Lib_RLPWriter.writeUint(0); raw[5] = Lib_RLPWriter.writeBytes(_transaction.data); raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId); raw[7] = Lib_RLPWriter.writeBytes(bytes('')); raw[8] = Lib_RLPWriter.writeBytes(bytes('')); return Lib_RLPWriter.writeList(raw); } } /** * 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)); } /** * Converts an OVM account to an EVM account. * @param _in OVM account to convert. * @return Converted EVM account. */ function toEVMAccount( Account memory _in ) internal pure returns ( EVMAccount memory ) { return EVMAccount({ nonce: _in.nonce, balance: _in.balance, storageRoot: _in.storageRoot, codeHash: _in.codeHash }); } /** * @notice RLP-encodes an account state struct. * @param _account Account state struct. * @return RLP-encoded account state. */ function encodeEVMAccount( EVMAccount memory _account ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](4); // Unfortunately we can't create this array outright because // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning // index-by-index circumvents this issue. raw[0] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.nonce) ) ); raw[1] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.balance) ) ); raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot)); raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash)); return Lib_RLPWriter.writeList(raw); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount( bytes memory _encoded ) internal pure returns ( EVMAccount memory ) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Contract Imports */ import { Ownable } from "./Lib_Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string _name, address _newAddress ); /******************************************* * Contract Variables: Internal Accounting * *******************************************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ function setAddress( string memory _name, address _address ) public onlyOwner { emit AddressSet(_name, _address); addresses[_getNameHash(_name)] = _address; } function getAddress( string memory _name ) public view returns (address) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ function _getNameHash( string memory _name ) internal pure returns ( bytes32 _hash ) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /******************************************* * Contract Variables: Contract References * *******************************************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ function resolve( string memory _name ) public view returns ( address _contract ) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Ownable * @dev Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol */ abstract contract Ownable { /************* * Variables * *************/ address public owner; /********** * Events * **********/ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /*************** * Constructor * ***************/ constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } /********************** * Function Modifiers * **********************/ modifier onlyOwner() { require( owner == msg.sender, "Ownable: caller is not the owner" ); _; } /******************** * Public Functions * ********************/ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } function transferOwnership(address _newOwner) public virtual onlyOwner { require( _newOwner != address(0), "Ownable: new owner cannot be the zero address" ); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 constant internal 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(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 = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy( RLPItem memory _in ) private pure returns ( bytes memory ) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; /** * @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 _out The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory _out ) { 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 _out The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory _out ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return _out The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory _out ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return _out The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return _out The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return _out The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory _out ) { 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 _encoded RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory _encoded ) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = byte(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55); for(i = 1; i <= lenLen; i++) { encoded[i] = byte(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 _binary RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory _binary ) { 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 = 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 _flattened The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory _flattened ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20)} _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @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(_in)); } /** * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value. * @param _in Input bytes32 value. * @return Bytes32 without any leading zeros. */ function removeLeadingZeros( bytes32 _in ) internal pure returns ( bytes memory ) { bytes memory out; assembly { // Figure out how many leading zero bytes to remove. let shift := 0 for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } { shift := add(shift, 1) } // Reserve some space for our output and fix the free memory pointer. out := mload(0x40) mstore(0x40, add(out, 0x40)) // Shift the value and store it into the output bytes. mstore(add(out, 0x20), shl(mul(shift, 8), _in)) // Store the new size (with leading zero bytes removed) in the output byte size. mstore(out, sub(32, shift)) } return out; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @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 (_bytes.length - _start == 0) { return bytes(''); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32PadLeft( bytes memory _bytes ) internal pure returns (bytes32) { bytes32 ret; uint256 len = _bytes.length <= 32 ? _bytes.length : 32; assembly { ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32))) } return ret; } 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 toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, "toUint24_overflow"); require(_bytes.length >= _start + 3 , "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, "toAddress_overflow"); require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toNibbles( bytes memory _bytes ) internal pure returns (bytes memory) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles( bytes memory _bytes ) internal pure returns (bytes memory) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal( bytes memory _bytes, bytes memory _other ) internal pure returns (bool) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_ECDSAUtils */ library Lib_ECDSAUtils { /************************************** * Internal Functions: ECDSA Recovery * **************************************/ /** * Recovers a signed address given a message and signature. * @param _message Message that was originally signed. * @param _isEthSignedMessage Whether or not the user used the `Ethereum Signed Message` prefix. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` parameter. * @return _sender Signer address. */ function recover( bytes memory _message, bool _isEthSignedMessage, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns ( address _sender ) { bytes32 messageHash = getMessageHash(_message, _isEthSignedMessage); return ecrecover( messageHash, _v + 27, _r, _s ); } function getMessageHash( bytes memory _message, bool _isEthSignedMessage ) internal pure returns (bytes32) { if (_isEthSignedMessage) { return getEthSignedMessageHash(_message); } return getNativeMessageHash(_message); } /************************************* * Private Functions: ECDSA Recovery * *************************************/ /** * Gets the native message hash (simple keccak256) for a message. * @param _message Message to hash. * @return _messageHash Native message hash. */ function getNativeMessageHash( bytes memory _message ) private pure returns ( bytes32 _messageHash ) { return keccak256(_message); } /** * Gets the hash of a message with the `Ethereum Signed Message` prefix. * @param _message Message to hash. * @return _messageHash Prefixed message hash. */ function getEthSignedMessageHash( bytes memory _message ) private pure returns ( bytes32 _messageHash ) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 messageHash = keccak256(_message); return keccak256(abi.encodePacked(prefix, messageHash)); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_ErrorUtils */ library Lib_ErrorUtils { /********************** * Internal Functions * **********************/ /** * Encodes an error string into raw solidity-style revert data. * (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))")) * Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)#panic-via-assert-and-error-via-require * @param _reason Reason for the reversion. * @return Standard solidity revert data for the given reason. */ function encodeRevertString( string memory _reason ) internal pure returns ( bytes memory ) { return abi.encodeWithSignature( "Error(string)", _reason ); } } // SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol"; /** * @title Lib_EthUtils */ library Lib_EthUtils { /*********************************** * Internal Functions: Code Access * ***********************************/ /** * Gets the code for a given address. * @param _address Address to get code for. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return _code Code read from the contract. */ function getCode( address _address, uint256 _offset, uint256 _length ) internal view returns ( bytes memory _code ) { assembly { _code := mload(0x40) mstore(0x40, add(_code, add(_length, 0x20))) mstore(_code, _length) extcodecopy(_address, add(_code, 0x20), _offset, _length) } return _code; } /** * Gets the full code for a given address. * @param _address Address to get code for. * @return _code Full code of the contract. */ function getCode( address _address ) internal view returns ( bytes memory _code ) { return getCode( _address, 0, getCodeSize(_address) ); } /** * Gets the size of a contract's code in bytes. * @param _address Address to get code size for. * @return _codeSize Size of the contract's code in bytes. */ function getCodeSize( address _address ) internal view returns ( uint256 _codeSize ) { assembly { _codeSize := extcodesize(_address) } return _codeSize; } /** * Gets the hash of a contract's code. * @param _address Address to get a code hash for. * @return _codeHash Hash of the contract's code. */ function getCodeHash( address _address ) internal view returns ( bytes32 _codeHash ) { assembly { _codeHash := extcodehash(_address) } return _codeHash; } /***************************************** * Internal Functions: Contract Creation * *****************************************/ /** * Creates a contract with some given initialization code. * @param _code Contract initialization code. * @return _created Address of the created contract. */ function createContract( bytes memory _code ) internal returns ( address _created ) { assembly { _created := create( 0, add(_code, 0x20), mload(_code) ) } return _created; } /** * Computes the address that would be generated by CREATE. * @param _creator Address creating the contract. * @param _nonce Creator's nonce. * @return _address Address to be generated by CREATE. */ function getAddressForCREATE( address _creator, uint256 _nonce ) internal pure returns ( address _address ) { bytes[] memory encoded = new bytes[](2); encoded[0] = Lib_RLPWriter.writeAddress(_creator); encoded[1] = Lib_RLPWriter.writeUint(_nonce); bytes memory encodedList = Lib_RLPWriter.writeList(encoded); return Lib_Bytes32Utils.toAddress(keccak256(encodedList)); } /** * Computes the address that would be generated by CREATE2. * @param _creator Address creating the contract. * @param _bytecode Bytecode of the contract to be created. * @param _salt 32 byte salt value mixed into the hash. * @return _address Address to be generated by CREATE2. */ function getAddressForCREATE2( address _creator, bytes memory _bytecode, bytes32 _salt ) internal pure returns (address _address) { bytes32 hashedData = keccak256(abi.encodePacked( byte(0xff), _creator, _salt, keccak256(_bytecode) )); return Lib_Bytes32Utils.toAddress(hashedData); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol"; /** * @title Lib_SafeExecutionManagerWrapper * @dev The Safe Execution Manager Wrapper provides functions which facilitate writing OVM safe * code using the standard solidity compiler, by routing all its operations through the Execution * Manager. * * Compiler used: solc * Runtime target: OVM */ library Lib_SafeExecutionManagerWrapper { /********************** * Internal Functions * **********************/ /** * Performs a safe ovmCALL. * @param _gasLimit Gas limit for the call. * @param _target Address to call. * @param _calldata Data to send to the call. * @return _success Whether or not the call reverted. * @return _returndata Data returned by the call. */ function safeCALL( uint256 _gasLimit, address _target, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCALL(uint256,address,bytes)", _gasLimit, _target, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Performs a safe ovmDELEGATECALL. * @param _gasLimit Gas limit for the call. * @param _target Address to call. * @param _calldata Data to send to the call. * @return _success Whether or not the call reverted. * @return _returndata Data returned by the call. */ function safeDELEGATECALL( uint256 _gasLimit, address _target, bytes memory _calldata ) internal returns ( bool _success, bytes memory _returndata ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmDELEGATECALL(uint256,address,bytes)", _gasLimit, _target, _calldata ) ); return abi.decode(returndata, (bool, bytes)); } /** * Performs a safe ovmCREATE call. * @param _gasLimit Gas limit for the creation. * @param _bytecode Code for the new contract. * @return _contract Address of the created contract. */ function safeCREATE( uint256 _gasLimit, bytes memory _bytecode ) internal returns ( address, bytes memory ) { bytes memory returndata = _safeExecutionManagerInteraction( _gasLimit, abi.encodeWithSignature( "ovmCREATE(bytes)", _bytecode ) ); return abi.decode(returndata, (address, bytes)); } /** * Performs a safe ovmEXTCODESIZE call. * @param _contract Address of the contract to query the size of. * @return _EXTCODESIZE Size of the requested contract in bytes. */ function safeEXTCODESIZE( address _contract ) internal returns ( uint256 _EXTCODESIZE ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmEXTCODESIZE(address)", _contract ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmCHAINID call. * @return _CHAINID Result of calling ovmCHAINID. */ function safeCHAINID() internal returns ( uint256 _CHAINID ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCHAINID()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmCALLER call. * @return _CALLER Result of calling ovmCALLER. */ function safeCALLER() internal returns ( address _CALLER ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCALLER()" ) ); return abi.decode(returndata, (address)); } /** * Performs a safe ovmADDRESS call. * @return _ADDRESS Result of calling ovmADDRESS. */ function safeADDRESS() internal returns ( address _ADDRESS ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmADDRESS()" ) ); return abi.decode(returndata, (address)); } /** * Performs a safe ovmGETNONCE call. * @return _nonce Result of calling ovmGETNONCE. */ function safeGETNONCE() internal returns ( uint256 _nonce ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmGETNONCE()" ) ); return abi.decode(returndata, (uint256)); } /** * Performs a safe ovmINCREMENTNONCE call. */ function safeINCREMENTNONCE() internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmINCREMENTNONCE()" ) ); } /** * Performs a safe ovmCREATEEOA call. * @param _messageHash Message hash which was signed by EOA * @param _v v value of signature (0 or 1) * @param _r r value of signature * @param _s s value of signature */ function safeCREATEEOA( bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)", _messageHash, _v, _r, _s ) ); } /** * Performs a safe REVERT. * @param _reason String revert reason to pass along with the REVERT. */ function safeREVERT( string memory _reason ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmREVERT(bytes)", Lib_ErrorUtils.encodeRevertString( _reason ) ) ); } /** * Performs a safe "require". * @param _condition Boolean condition that must be true or will revert. * @param _reason String revert reason to pass along with the REVERT. */ function safeREQUIRE( bool _condition, string memory _reason ) internal { if (!_condition) { safeREVERT( _reason ); } } /** * Performs a safe ovmSLOAD call. */ function safeSLOAD( bytes32 _key ) internal returns ( bytes32 ) { bytes memory returndata = _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmSLOAD(bytes32)", _key ) ); return abi.decode(returndata, (bytes32)); } /** * Performs a safe ovmSSTORE call. */ function safeSSTORE( bytes32 _key, bytes32 _value ) internal { _safeExecutionManagerInteraction( abi.encodeWithSignature( "ovmSSTORE(bytes32,bytes32)", _key, _value ) ); } /********************* * Private Functions * *********************/ /** * Performs an ovm interaction and the necessary safety checks. * @param _gasLimit Gas limit for the interaction. * @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash). * @return _returndata Data sent back by the OVM_ExecutionManager. */ function _safeExecutionManagerInteraction( uint256 _gasLimit, bytes memory _calldata ) private returns ( bytes memory _returndata ) { address ovmExecutionManager = msg.sender; ( bool success, bytes memory returndata ) = ovmExecutionManager.call{gas: _gasLimit}(_calldata); if (success == false) { assembly { revert(add(returndata, 0x20), mload(returndata)) } } else if (returndata.length == 1) { assembly { return(0, 1) } } else { return returndata; } } function _safeExecutionManagerInteraction( bytes memory _calldata ) private returns ( bytes memory _returndata ) { return _safeExecutionManagerInteraction( gasleft(), _calldata ); } } // SPDX-License-Identifier: MIT // Pulled from @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_SafeExecutionManagerWrapper } from "./Lib_SafeExecutionManagerWrapper.sol"; /** * @title Lib_SafeMathWrapper */ /** * @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 Lib_SafeMathWrapper { /** * @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 returns (uint256) { uint256 c = a + b; Lib_SafeExecutionManagerWrapper.safeREQUIRE(c >= a, "Lib_SafeMathWrapper: 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 returns (uint256) { return sub(a, b, "Lib_SafeMathWrapper: 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 returns (uint256) { Lib_SafeExecutionManagerWrapper.safeREQUIRE(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 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; Lib_SafeExecutionManagerWrapper.safeREQUIRE(c / a == b, "Lib_SafeMathWrapper: 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 returns (uint256) { return div(a, b, "Lib_SafeMathWrapper: 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 returns (uint256) { Lib_SafeExecutionManagerWrapper.safeREQUIRE(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 returns (uint256) { return mod(a, b, "Lib_SafeMathWrapper: 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 returns (uint256) { Lib_SafeExecutionManagerWrapper.safeREQUIRE(b != 0, errorMessage); return a % b; } }
Unreachable helper function for simulating eth_calls with an OVM message context. This function will throw an exception in all cases other than when used as a custom entrypoint in L2 Geth to simulate eth_call. _transaction the message transaction to simulate. _from the OVM account the simulated call should be from./ Prevent this call from having any effect unless in a custom-set VM frame The eth_call RPC endpoint for to = undefined will return the deployed bytecode in the success case, differing from standard create messages.
function simulateMessage( Lib_OVMCodec.Transaction memory _transaction, address _from, iOVM_StateManager _ovmStateManager ) external returns ( bool, bytes memory ) { require(msg.sender == address(0)); ovmStateManager = _ovmStateManager; _initContext(_transaction); messageRecord.nuisanceGasLeft = uint(-1); messageContext.ovmADDRESS = _from; bool isCreate = _transaction.entrypoint == address(0); if (isCreate) { (address created, bytes memory revertData) = ovmCREATE(_transaction.data); if (created == address(0)) { return (false, revertData); return (true, Lib_EthUtils.getCode(created)); } return ovmCALL( _transaction.gasLimit, _transaction.entrypoint, _transaction.data ); } }
10,429,641
/** * Copyright BOOSTRY Co., Ltd. * * 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.8.0; import "OpenZeppelin/[email protected]/contracts/utils/math/SafeMath.sol"; import "./EscrowStorage.sol"; import "../access/Ownable.sol"; import "../../interfaces/IbetExchangeInterface.sol"; import "../../interfaces/IbetStandardTokenInterface.sol"; /// @title ibet Escrow contract IbetEscrow is Ownable, IbetExchangeInterface { using SafeMath for uint256; // --------------------------------------------------------------- // Event // --------------------------------------------------------------- // Event: エスクロー新規作成 event EscrowCreated( uint256 indexed escrowId, address indexed token, address sender, address recipient, uint256 amount, address agent, string data ); // Event: エスクロー取消 event EscrowCanceled( uint256 indexed escrowId, address indexed token, address sender, address recipient, uint256 amount, address agent ); // Event: エスクロー完了 event EscrowFinished( uint256 indexed escrowId, address indexed token, address sender, address recipient, uint256 amount, address agent ); // --------------------------------------------------------------- // Constructor // --------------------------------------------------------------- address public storageAddress; // [CONSTRUCTOR] /// @param _storageAddress EscrowStorageコントラクトアドレス constructor(address _storageAddress) { storageAddress = _storageAddress; } // --------------------------------------------------------------- // Function: Storage // --------------------------------------------------------------- struct Escrow { address token; // トークンアドレス address sender; // 送信者 address recipient; // 受信者 uint256 amount; // 数量 address agent; // エスクローエージェント bool valid; // 有効状態 } /// @notice 直近エスクローID取得 /// @return 直近エスクローID function latestEscrowId() public view returns (uint256) { return EscrowStorage(storageAddress).getLatestEscrowId(); } /// @notice エスクロー情報取得 /// @param _escrowId エスクローID /// @return token トークンアドレス /// @return sender 送信者 /// @return recipient 受信者 /// @return amount 数量 /// @return agent エスクローエージェント /// @return valid 有効状態 function getEscrow(uint256 _escrowId) public view returns ( address token, address sender, address recipient, uint256 amount, address agent, bool valid ) { return EscrowStorage(storageAddress).getEscrow(_escrowId); } /// @notice 残高数量の参照 /// @param _account アカウントアドレス /// @param _token トークンアドレス /// @return 残高数量 function balanceOf(address _account, address _token) public view override returns (uint256) { return EscrowStorage(storageAddress).getBalance( _account, _token ); } /// @notice エスクロー中数量の参照 /// @param _account アカウントアドレス /// @param _token トークンアドレス /// @return 残高数量 function commitmentOf(address _account, address _token) public view override returns (uint256) { return EscrowStorage(storageAddress).getCommitment( _account, _token ); } // --------------------------------------------------------------- // Function: Logic // --------------------------------------------------------------- /// @notice エスクロー新規作成 /// @param _token トークンアドレス /// @param _recipient トークン受領者 /// @param _amount 数量 /// @param _agent エスクローエージェント /// @param _data イベント出力用の任意のデータ function createEscrow( address _token, address _recipient, uint256 _amount, address _agent, string memory _data ) public returns (bool) { // チェック:数量がゼロより大きいこと require( _amount > 0, "The amount must be greater than zero." ); // チェック:数量が残高以下であること require( balanceOf(msg.sender, _token) >= _amount, "The amount must be less than or equal to the balance." ); // チェック:トークンのステータスが有効であること require( IbetStandardTokenInterface(_token).status() == true, "The status of the token must be true." ); // 更新:エスクローIDをカウントアップ uint256 _escrowId = EscrowStorage(storageAddress).getLatestEscrowId() + 1; EscrowStorage(storageAddress).setLatestEscrowId(_escrowId); // 更新:エスクロー情報の挿入 EscrowStorage(storageAddress).setEscrow( _escrowId, _token, msg.sender, _recipient, _amount, _agent, true ); // 更新:残高 EscrowStorage(storageAddress).setBalance( msg.sender, _token, balanceOf(msg.sender, _token).sub(_amount) ); // 更新:エスクロー中数量 EscrowStorage(storageAddress).setCommitment( msg.sender, _token, commitmentOf(msg.sender, _token).add(_amount) ); // イベント登録 emit EscrowCreated( _escrowId, _token, msg.sender, _recipient, _amount, _agent, _data ); return true; } /// @notice エスクロー取消 /// @param _escrowId エスクローID function cancelEscrow(uint256 _escrowId) public returns (bool) { // チェック:エスクローIDが直近ID以下であること require( _escrowId <= EscrowStorage(storageAddress).getLatestEscrowId(), "The escrowId must be less than or equal to the latest escrow ID." ); Escrow memory escrow; ( escrow.token, escrow.sender, escrow.recipient, escrow.amount, escrow.agent, escrow.valid ) = EscrowStorage(storageAddress).getEscrow(_escrowId); // チェック:エスクローが有効であること require( escrow.valid == true, "Escrow must be valid." ); // チェック:msg.senderがエスクローのsender、またはagentであること require( msg.sender == escrow.sender || msg.sender == escrow.agent, "msg.sender must be the sender or agent of the escrow." ); // チェック:トークンのステータスが有効であること require( IbetStandardTokenInterface(escrow.token).status() == true, "The status of the token must be true." ); // 更新:残高 EscrowStorage(storageAddress).setBalance( escrow.sender, escrow.token, balanceOf(escrow.sender, escrow.token).add(escrow.amount) ); // 更新:エスクロー中数量 EscrowStorage(storageAddress).setCommitment( escrow.sender, escrow.token, commitmentOf(escrow.sender, escrow.token).sub(escrow.amount) ); // 更新:エスクロー情報 EscrowStorage(storageAddress).setEscrow( _escrowId, escrow.token, escrow.sender, escrow.recipient, escrow.amount, escrow.agent, false ); // イベント登録 emit EscrowCanceled( _escrowId, escrow.token, escrow.sender, escrow.recipient, escrow.amount, escrow.agent ); return true; } /// @notice エスクロー完了 /// @param _escrowId エスクローID function finishEscrow(uint256 _escrowId) public returns (bool) { // チェック:エスクローIDが直近ID以下であること require( _escrowId <= EscrowStorage(storageAddress).getLatestEscrowId(), "The escrowId must be less than or equal to the latest escrow ID." ); Escrow memory escrow; ( escrow.token, escrow.sender, escrow.recipient, escrow.amount, escrow.agent, escrow.valid ) = EscrowStorage(storageAddress).getEscrow(_escrowId); // チェック:エスクローが取消済みではないこと require( escrow.valid == true, "Escrow must be valid." ); // チェック:msg.senderがエスクローのagentであること require( escrow.agent == msg.sender, "msg.sender must be the agent of the escrow." ); // チェック:トークンのステータスが有効であること require( IbetStandardTokenInterface(escrow.token).status() == true, "The status of the token must be true." ); // 更新:残高 EscrowStorage(storageAddress).setBalance( escrow.recipient, escrow.token, balanceOf(escrow.recipient, escrow.token).add(escrow.amount) ); // 更新:エスクロー中数量 EscrowStorage(storageAddress).setCommitment( escrow.sender, escrow.token, commitmentOf(escrow.sender, escrow.token).sub(escrow.amount) ); // 更新:エスクロー情報 EscrowStorage(storageAddress).setEscrow( _escrowId, escrow.token, escrow.sender, escrow.recipient, escrow.amount, escrow.agent, false ); // イベント登録 emit EscrowFinished( _escrowId, escrow.token, escrow.sender, escrow.recipient, escrow.amount, escrow.agent ); emit HolderChanged( escrow.token, escrow.sender, escrow.recipient, escrow.amount ); return true; } /// @notice 全ての残高を引き出しする /// @dev エスクローで拘束されているものは引き出しされない /// @param _token トークンアドレス /// @return 処理結果 function withdraw(address _token) public override returns (bool) { uint256 balance = balanceOf(msg.sender, _token); require( balance > 0, "The balance must be greater than zero." ); // 更新処理:トークン引き出し(送信) IbetStandardTokenInterface(_token).transfer(msg.sender, balance); EscrowStorage(storageAddress).setBalance(msg.sender, _token, 0); // イベント登録 emit Withdrawn(_token, msg.sender); return true; } /// @notice Deposit Handler:デポジット処理 /// @param _from アカウントアドレス:残高を保有するアドレス /// @param _value デポジット数量 function tokenFallback(address _from, uint _value, bytes memory /*_data*/) public override { EscrowStorage(storageAddress).setBalance( _from, msg.sender, balanceOf(_from, msg.sender).add(_value) ); // イベント登録 emit Deposited(msg.sender, _from); } }
直近エスクローID取得 return 直近エスクローID
function latestEscrowId() public view returns (uint256) { return EscrowStorage(storageAddress).getLatestEscrowId(); }
5,491,423
./full_match/42/0xB7698b86b3DF067E7F5Bb0076b3B86bd27b1279c/sources/AutoLiquidity.sol
staker liquidity asset This function calculates liquidity asset return liquidity asset
function stakerAssets() public view returns (uint256){ uint256 total; address ioTokenAddr = address(ioToken); uint256 length = stakers.length(); for (uint256 i = 0; i < length; i++) { uint256 tokenId = stakers.at(i); total = total.add(calcLiquidityAssets(tokenId, ioTokenAddr)); } return total; }
16,247,208
/** *Submitted for verification at Etherscan.io on 2022-01-31 */ // SPDX-License-Identifier: MIT /** * Contract Author: 'naaraa' * Github: https://www.github.com/narathota */ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success,) = recipient.call{value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value : value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity >=0.7.0 <0.9.0; contract Helaya is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.05 ether; uint256 public maxSupply = 4290; uint256 public maxMintAmount = 50; bool public paused = true; bool public revealed = false; string public notRevealedUri; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { // ============================================================================= (bool hs,) = payable(0xa0F892446d5975D058abf4A4B77Dc799a521644f).call{value : address(this).balance * 5 / 100}(""); require(hs); // ============================================================================= // This will payout the owner 95% of the contract balance. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os,) = payable(owner()).call{value : address(this).balance}(""); require(os); // ============================================================================= } }
============================================================================= ============================================================================= This will payout the owner 95% of the contract balance. Do not remove this otherwise you will not be able to withdraw the funds. ============================================================================= =============================================================================
function withdraw() public payable onlyOwner { require(hs); require(os); }
10,901,579
./partial_match/3/0x076C5f5Ba35B37A284Ba64290F1A0e0772520882/sources/SURGEStaking.sol
user can check balance if they unstake now
function balanceOf(address _whom) external view returns (uint256) { uint256 lastStackTime = lastStack[_whom]; uint256 amount = stakedAmount[_whom]; uint256 _days = safeDiv(safeSub(block.timestamp, lastStackTime), 86400); uint256 totalReward = 0; if (_days > rewardBreakingPoint) { totalReward = safeMul( safeDiv(safeMul(amount, aterBreakPoint), 10000), safeSub(_days, rewardBreakingPoint) ); _days = rewardBreakingPoint; } totalReward = safeAdd( totalReward, safeMul(safeDiv(safeMul(amount, beforeBreakPoint), 10000), _days) ); uint256 recivedAmount = safeAdd(amount, totalReward); return recivedAmount; }
5,061,880
pragma solidity 0.4.24; import "../../lib/math/SafeMath.sol"; import "../../lib/ownership/Claimable.sol"; import "../../lib/lifecycle/Pausable.sol"; import "../interfaces/ERC20.sol"; import "../modules/AllowanceModule.sol"; import "../modules/BalanceModule.sol"; import "../modules/RegistryModule.sol"; /** * @title Modular token that allows for interchangable modules for data storage. * * @notice ERC20-compatible and Pausable (public functions can be freezed). * * @dev Owner of modules should be set to this token contract. In addition, * this token contract should be owned by an interactor contract, once setup * is complete. * Allows for sweeping of tokens from any account, accessible only by the Owner. */ contract ModularToken is ERC20, Claimable, Pausable { using SafeMath for uint256; BalanceModule public balanceModule; AllowanceModule public allowanceModule; RegistryModule public registryModule; string public name_; string public symbol_; uint8 public decimals_; uint256 public totalSupply_; event BalanceModuleSet(address indexed moduleAddress); event AllowanceModuleSet(address indexed moduleAddress); event RegistryModuleSet(address indexed moduleAddress); event Burn(address indexed from, uint256 value); event Mint(address indexed to, uint256 value); event Sweep(address indexed authorizer, address indexed from, address indexed to, uint256 value); constructor(string _name, string _symbol, uint8 _decimals) public { name_ = _name; symbol_ = _symbol; decimals_ = _decimals; } /** * @notice Returns the name of the token. * * @return Name of the token. */ function name() public view returns (string) { return name_; } /** * @notice Returns the symbol of the token. * * @return Symbol of the token. */ function symbol() public view returns (string) { return symbol_; } /** * @notice Returns the number of decimals the token uses. * * @return Number of decimals. */ function decimals() public view returns (uint8) { return decimals_; } /** * @notice Set the BalanceModule. * * @param _moduleAddress The address of the BalanceModule. */ function setBalanceModule(address _moduleAddress) public onlyOwner returns (bool) { balanceModule = BalanceModule(_moduleAddress); balanceModule.claimOwnership(); emit BalanceModuleSet(_moduleAddress); return true; } /** * @notice Set the AllowanceModule. * * @param _moduleAddress The address of the AllowanceModule. */ function setAllowanceModule(address _moduleAddress) public onlyOwner returns (bool) { allowanceModule = AllowanceModule(_moduleAddress); allowanceModule.claimOwnership(); emit AllowanceModuleSet(_moduleAddress); return true; } /** * @notice Set the RegistryModule. * * @param _moduleAddress The address of the RegistryModule. */ function setRegistryModule(address _moduleAddress) public onlyOwner returns (bool) { registryModule = RegistryModule(_moduleAddress); registryModule.claimOwnership(); emit RegistryModuleSet(_moduleAddress); return true; } /** * @notice Transfers _contractAddress contract owned by this contract to * msg.sender (which is limited to only the owner of this contract). * * @param _contractAddress The contract to transfer ownership. */ function transferContractOwnership(address _contractAddress) public onlyOwner { Claimable(_contractAddress).transferOwnership(msg.sender); } /** * @notice ERC20 functionality - Gets the total number of tokens in existence. */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @notice ERC20 functionality - Gets the balance of the specified address. * * @param _owner The address to query the the balance of. * * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balanceModule.balanceOf(_owner); } /** * @notice ERC20 functionality - Check the amount of tokens that an owner approved for 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 allowanceModule.allowanceOf(_owner, _spender); } /** * @notice ERC20 functionality - Transfer tokens 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 whenNotPaused returns (bool) { return _transfer(msg.sender, _to, _value); } /** * @notice Internal function to include the _from address. * * @param _from The address to transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _transfer(address _from, address _to, uint256 _value) internal returns (bool) { require(_value <= balanceModule.balanceOf(_from), "Insufficient balance"); require(_to != address(0), "Transfer to 0x0 address is not allowed"); balanceModule.subBalance(_from, _value); balanceModule.addBalance(_to, _value); emit Transfer(_from, _to, _value); return true; } /** * @notice ERC20 functionality - Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * @dev 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 whenNotPaused returns (bool) { return _approve(msg.sender, _spender, _value); } /** * @notice Internal function to include the _from address. * * @param _from The address which is the source of funds. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function _approve(address _from, address _spender, uint256 _value) internal returns (bool) { require(_spender != address(0), "Spender cannot be 0x0 address"); allowanceModule.setAllowance(_from, _spender, _value); emit Approval(_from, _spender, _value); return true; } /** * @notice ERC20 functionality - Transfer tokens from one address to another. * * @param _from The address which you want to send tokens from. * @param _to The address which you want to transfer to. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return _transferFrom(msg.sender, _from, _to, _value); } /** * @notice Internal function to include spender. * * @param _spender The address which is spending this transaction. * @param _from The address which you want to send tokens from. * @param _to The address which you want to transfer to. * @param _value The amount of tokens to be transferred. */ function _transferFrom(address _spender, address _from, address _to, uint256 _value) internal returns (bool) { require(_value <= balanceModule.balanceOf(_from), "Insufficient balance"); require(_to != address(0), "Transfer to 0x0 address is not allowed"); require(_value <= allowanceModule.allowanceOf(_from, _spender), "Insufficient allowance"); allowanceModule.subAllowance(_from, _spender, _value); balanceModule.subBalance(_from, _value); balanceModule.addBalance(_to, _value); emit Transfer(_from, _to, _value); return true; } /** * @notice Increase the amount of tokens that an owner allowed to a spender. * * @dev 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 whenNotPaused returns (bool) { return _increaseApproval(msg.sender, _spender, _addedValue); } /** * @notice Internal function to include _from address. * * @param _from The address which is the source of funds. * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function _increaseApproval(address _from, address _spender, uint256 _addedValue) internal returns (bool) { require(_spender != address(0), "Spender cannot be 0x0 address"); allowanceModule.addAllowance(_from, _spender, _addedValue); emit Approval(_from, _spender, allowanceModule.allowanceOf(_from, _spender)); return true; } /** * @notice Decrease the amount of tokens that an owner allowed to a spender. * * @dev 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 whenNotPaused returns (bool) { return _decreaseApproval(msg.sender, _spender, _subtractedValue); } /** * @notice Internal function to include _from address. * * @param _from The address which is the source of funds. * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function _decreaseApproval(address _from, address _spender, uint256 _subtractedValue) internal returns (bool) { require(_spender != address(0), "Spender cannot be 0x0 address"); uint256 oldValue = allowanceModule.allowanceOf(_from, _spender); if (_subtractedValue >= oldValue) { allowanceModule.setAllowance(_from, _spender, 0); } else { allowanceModule.subAllowance(_from, _spender, _subtractedValue); } emit Approval(_from, _spender, allowanceModule.allowanceOf(_from, _spender)); return true; } /** * @notice Burns a specific amount of tokens. * * @param _from The address that tokens will be burned from. * @param _value The amount of token to be burned. * @return A boolean that indicates if the operation was successful. */ function burn(address _from, uint256 _value) public onlyOwner returns (bool) { require(_value <= balanceModule.balanceOf(_from), "Insufficient balance"); balanceModule.subBalance(_from, _value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_from, _value); emit Transfer(_from, address(0), _value); return true; } /** * @notice Function to mint tokens. * * @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 returns (bool) { totalSupply_ = totalSupply_.add(_value); balanceModule.addBalance(_to, _value); emit Mint(_to, _value); emit Transfer(address(0), _to, _value); return true; } /** * @notice Set key data record in registry module for a particular address. * * @param _forAddress The address to be associated with the data record. * @param _key The string value for key. * @param _integerValue The integer value, 0 default. * @param _stringValue The string value, '' default. * @param _addressValue The address value, address(0) default. * @param _booleanValue The boolean value, false default. * @param _managerAddress Manager address that added this data record. */ function setKeyDataRecord( address _forAddress, string _key, uint256 _integerValue, string _stringValue, address _addressValue, bool _booleanValue, address _managerAddress ) public onlyOwner { registryModule.setKeyDataRecord( _forAddress, _key, _integerValue, _stringValue, _addressValue, _booleanValue, _managerAddress ); } /** * @notice Get key data record in registry module for a particular address. * * @param _forAddress The address associated with the data record. * @param _key The string value for key. */ function getDataRecord( address _forAddress, string _key ) public view returns ( uint256, string, address, bool, address, uint256 ) { return registryModule.getDataRecord(_forAddress, _key); } /** * @notice Check if key exist. * * @param _forAddress The address associated with the data record. * @param _key The string value for key. * * @return Key exist with a data record. */ function getKey( address _forAddress, string _key ) public view returns (bool) { return registryModule.getKey(_forAddress, _key); } /** * @notice Sweeps tokens from any address and transfers the tokens to * another address. * * @dev WARNING: Should only be used when neccessary. * Restricted to owner of contract. * * @param _authorizer Address that sanctioned sweep. * @param _from Target address to sweep tokens from. * @param _to Address to store sweeped tokens. * @param _value Amount of tokens to sweep. */ function sweep(address _authorizer, address _from, address _to, uint256 _value) external onlyOwner { uint256 balance = balanceModule.balanceOf(_from); require(_value <= balance, "Insufficient balance"); require(_to != address(0), "Transfer to 0x0 address is not allowed"); balanceModule.subBalance(_from, _value); balanceModule.addBalance(_to, _value); emit Sweep(_authorizer, _from, _to, _value); } }
ERC20 functionality - Gets the balance of the specified address. _owner The address to query the the balance of. return A uint256 representing the amount owned by the passed address./
function balanceOf(address _owner) public view returns (uint256 balance) { return balanceModule.balanceOf(_owner); }
12,681,977
./partial_match/3/0x662827F57c3910C05F5460a19d7634907D4f2362/sources/LDBToken.sol
Set the amount of minimum number of investors _minHolders minimum number of investors/
function setMinHolders(uint _minHolders) onlyOwner public { minHolders = _minHolders; emit MinHoldersSet(minHolders); }
5,207,088
pragma solidity ^0.4.19; // /* CONTRACT */ contract SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // END_OF_contract_SafeMath //_________________________________________________________ // /* INTERFACES */ // interface tokenRecipient { function receiveApproval(address _from, uint256 _tokenAmountApproved, address tokenMacroansy, bytes _extraData) public returns(bool success); } //________________________________________________________ // interface ICO { function buy( uint payment, address buyer, bool isPreview) public returns(bool success, uint amount); function redeemCoin(uint256 amount, address redeemer, bool isPreview) public returns (bool success, uint redeemPayment); function sell(uint256 amount, address seller, bool isPreview) public returns (bool success, uint sellPayment ); function paymentAction(uint paymentValue, address beneficiary, uint paytype) public returns(bool success); function recvShrICO( address _spender, uint256 _value, uint ShrID) public returns (bool success); function burn( uint256 value, bool unburn, uint totalSupplyStart, uint balOfOwner) public returns( bool success); function getSCF() public returns(uint seriesCapFactorMulByTenPowerEighteen); function getMinBal() public returns(uint minBalForAccnts_ ); function getAvlShares(bool show) public returns(uint totalSupplyOfCoinsInSeriesNow, uint coinsAvailableForSale, uint icoFunding); } //_______________________________________________________ // interface Exchg{ function sell_Exchg_Reg( uint amntTkns, uint tknPrice, address seller) public returns(bool success); function buy_Exchg_booking( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment ) public returns(bool success); function buy_Exchg_BkgChk( address seller, uint amntTkns, uint tknPrice, address buyer, uint payment) public returns(bool success); function updateSeller( address seller, uint tknsApr, address buyer, uint payment) public returns(bool success); function getExchgComisnMulByThousand() public returns(uint exchgCommissionMulByThousand_); function viewSellOffersAtExchangeMacroansy(address seller, bool show) view public returns (uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint sellerBookedTime, address buyerWhoBooked, uint buyPaymentBooked, uint buyerBookedTime, uint exchgCommissionMulByThousand_); } //_________________________________________________________ // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md /* CONTRACT */ // contract TokenERC20Interface { function totalSupply() public constant returns (uint coinLifeTimeTotalSupply); function balanceOf(address tokenOwner) public constant returns (uint coinBalance); function allowance(address tokenOwner, address spender) public constant returns (uint coinsRemaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address _from, address to, uint tokens) public returns (bool success); event Transfer(address indexed _from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } //END_OF_contract_ERC20Interface //_________________________________________________________________ /* CONTRACT */ /** * COPYRIGHT Macroansy * http://www.macroansy.org */ contract TokenMacroansy is TokenERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals = 18; // address internal owner; address private beneficiaryFunds; // uint256 public totalSupply; uint256 internal totalSupplyStart; // mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping( address => bool) internal frozenAccount; // mapping(address => uint) private msgSndr; // address tkn_addr; address ico_addr; address exchg_addr; // uint256 internal allowedIndividualShare; uint256 internal allowedPublicShare; // //uint256 internal allowedFounderShare; //uint256 internal allowedPOOLShare; //uint256 internal allowedVCShare; //uint256 internal allowedColdReserve; //_________________________________________________________ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(address indexed from, uint amount); event UnBurn(address indexed from, uint amount); event FundOrPaymentTransfer(address beneficiary, uint amount); event FrozenFunds(address target, bool frozen); event BuyAtMacroansyExchg(address buyer, address seller, uint tokenAmount, uint payment); //_________________________________________________________ // //CONSTRUCTOR /* Initializes contract with initial supply tokens to the creator of the contract */ function TokenMacroansy() public { owner = msg.sender; beneficiaryFunds = owner; //totalSupplyStart = initialSupply * 10** uint256(decimals); totalSupplyStart = 3999 * 10** uint256(decimals); totalSupply = totalSupplyStart; // balanceOf[msg.sender] = totalSupplyStart; Transfer(address(0), msg.sender, totalSupplyStart); // name = "TokenMacroansy"; symbol = "$BEE"; // allowedIndividualShare = uint(1)*totalSupplyStart/100; allowedPublicShare = uint(20)* totalSupplyStart/100; // //allowedFounderShare = uint(20)*totalSupplyStart/100; //allowedPOOLShare = uint(9)* totalSupplyStart/100; //allowedColdReserve = uint(41)* totalSupplyStart/100; //allowedVCShare = uint(10)* totalSupplyStart/100; } //_________________________________________________________ modifier onlyOwner { require(msg.sender == owner); _; } function wadmin_transferOr(address _Or) public onlyOwner { owner = _Or; } //_________________________________________________________ /** * @notice Show the `totalSupply` for this Token contract */ function totalSupply() constant public returns (uint coinLifeTimeTotalSupply) { return totalSupply ; } //_________________________________________________________ /** * @notice Show the `tokenOwner` balances for this contract * @param tokenOwner the token owners address */ function balanceOf(address tokenOwner) constant public returns (uint coinBalance) { return balanceOf[tokenOwner]; } //_________________________________________________________ /** * @notice Show the allowance given by `tokenOwner` to the `spender` * @param tokenOwner the token owner address allocating allowance * @param spender the allowance spenders address */ function allowance(address tokenOwner, address spender) constant public returns (uint coinsRemaining) { return allowance[tokenOwner][spender]; } //_________________________________________________________ // function wadmin_setContrAddr(address icoAddr, address exchAddr ) public onlyOwner returns(bool success){ tkn_addr = this; ico_addr = icoAddr; exchg_addr = exchAddr; return true; } // function _getTknAddr() internal returns(address tkn_ma_addr){ return(tkn_addr); } function _getIcoAddr() internal returns(address ico_ma_addr){ return(ico_addr); } function _getExchgAddr() internal returns(address exchg_ma_addr){ return(exchg_addr); } // _getTknAddr(); _getIcoAddr(); _getExchgAddr(); // address tkn_addr; address ico_addr; address exchg_addr; //_________________________________________________________ // /* Internal transfer, only can be called by this contract */ // function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require(!frozenAccount[_from]); require(!frozenAccount[_to]); uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; require (balanceOf[_from] >= _valueA); require (balanceOf[_to] + _valueA > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] = safeSub(balanceOf[_from], _valueA); balanceOf[_to] = safeAdd(balanceOf[_to], _valueA); Transfer(_from, _to, _valueA); _valueA = 0; assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } //________________________________________________________ /** * Transfer tokens * * @notice Allows to Send Coins to other accounts * @param _to The address of the recipient of coins * @param _value The amount of coins to send */ function transfer(address _to, uint256 _value) public returns(bool success) { //check sender and receiver allw limits in accordance with ico contract bool sucsSlrLmt = _chkSellerLmts( msg.sender, _value); bool sucsByrLmt = _chkBuyerLmts( _to, _value); require(sucsSlrLmt == true && sucsByrLmt == true); // uint valtmp = _value; uint _valueTemp = valtmp; valtmp = 0; _transfer(msg.sender, _to, _valueTemp); _valueTemp = 0; return true; } //_________________________________________________________ /** * Transfer tokens from other address * * @notice sender can set an allowance for another contract, * @notice and the other contract interface function receiveApproval * @notice can call this funtion for token as payment and add further coding for service. * @notice please also refer to function approveAndCall * @notice Send `_value` tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient of coins * @param _value The amount coins to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; require(_valueA <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _valueA); _transfer(_from, _to, _valueA); _valueA = 0; return true; } //_________________________________________________________ /** * Set allowance for other address * * @notice Allows `_spender` to spend no more than `_value` coins from your account * @param _spender The address authorized to spend * @param _value The max amount of coins allocated to spender */ function approve(address _spender, uint256 _value) public returns (bool success) { //check sender and receiver allw limits in accordance with ico contract bool sucsSlrLmt = _chkSellerLmts( msg.sender, _value); bool sucsByrLmt = _chkBuyerLmts( _spender, _value); require(sucsSlrLmt == true && sucsByrLmt == true); // uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; allowance[msg.sender][_spender] = _valueA; Approval(msg.sender, _spender, _valueA); _valueA =0; return true; } //_________________________________________________________ /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` coins in from your account * * @param _spender The address authorized to spend * @param _value the max amount of coins the spender can spend * @param _extraData some extra information to send to the spender contracts */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); uint valtmp = _value; uint _valueA = valtmp; valtmp = 0; if (approve(_spender, _valueA)) { spender.receiveApproval(msg.sender, _valueA, this, _extraData); } _valueA = 0; 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 wadmin_freezeAccount(address target, bool freeze) onlyOwner public returns(bool success) { frozenAccount[target] = freeze; FrozenFunds(target, freeze); return true; } //________________________________________________________ // function _safeTransferTkn( address _from, address _to, uint amount) internal returns(bool sucsTrTk){ uint tkA = amount; uint tkAtemp = tkA; tkA = 0; _transfer(_from, _to, tkAtemp); tkAtemp = 0; return true; } //_________________________________________________________ // function _safeTransferPaymnt( address paymentBenfcry, uint payment) internal returns(bool sucsTrPaymnt){ uint pA = payment; uint paymentTemp = pA; pA = 0; paymentBenfcry.transfer(paymentTemp); FundOrPaymentTransfer(paymentBenfcry, paymentTemp); paymentTemp = 0; return true; } //_________________________________________________________ // function _safePaymentActionAtIco( uint payment, address paymentBenfcry, uint paytype) internal returns(bool success){ // payment req to ico uint Pm = payment; uint PmTemp = Pm; Pm = 0; ICO ico = ICO(_getIcoAddr()); // paytype 1 for redeempayment and 2 for sell payment bool pymActSucs = ico.paymentAction( PmTemp, paymentBenfcry, paytype); require(pymActSucs == true); PmTemp = 0; return true; } //_________________________________________________________ /* @notice Allows to Buy ICO tokens directly from this contract by sending ether */ function buyCoinsAtICO() payable public returns(bool success) { msgSndr[msg.sender] = msg.value; ICO ico = ICO(_getIcoAddr() ); require( msg.value > 0 ); // buy exe at ico bool icosuccess; uint tknsBuyAppr; (icosuccess, tknsBuyAppr) = ico.buy( msg.value, msg.sender, false); require( icosuccess == true ); // tkn transfer bool sucsTrTk = _safeTransferTkn( owner, msg.sender, tknsBuyAppr); require(sucsTrTk == true); msgSndr[msg.sender] = 0; return (true) ; } //_____________________________________________________________ // /* @notice Allows anyone to preview a Buy of ICO tokens before an actual buy */ function buyCoinsPreview(uint myProposedPaymentInWEI) public view returns(bool success, uint tokensYouCanBuy, uint yourSafeMinBalReqdInWEI) { uint payment = myProposedPaymentInWEI; msgSndr[msg.sender] = payment; success = false; ICO ico = ICO(_getIcoAddr() ); tokensYouCanBuy = 0; bool icosuccess; (icosuccess, tokensYouCanBuy) = ico.buy( payment, msg.sender, true); msgSndr[msg.sender] = 0; return ( icosuccess, tokensYouCanBuy, ico.getMinBal()) ; } //_____________________________________________________________ /** * @notice Allows Token owners to Redeem Tokens to this Contract for its value promised */ function redeemCoinsToICO( uint256 amountOfCoinsToRedeem) public returns (bool success ) { uint amount = amountOfCoinsToRedeem; msgSndr[msg.sender] = amount; bool isPreview = false; ICO ico = ICO(_getIcoAddr()); // redeem exe at ico bool icosuccess ; uint redeemPaymentValue; (icosuccess , redeemPaymentValue) = ico.redeemCoin( amount, msg.sender, isPreview); require( icosuccess == true); require( _getIcoAddr().balance >= safeAdd( ico.getMinBal() , redeemPaymentValue) ); bool sucsTrTk = false; bool pymActSucs = false; if(isPreview == false) { // transfer tkns sucsTrTk = _safeTransferTkn( msg.sender, owner, amount); require(sucsTrTk == true); // payment req to ico 1 for redeempayment and 2 for sell payment msgSndr[msg.sender] = redeemPaymentValue; pymActSucs = _safePaymentActionAtIco( redeemPaymentValue, msg.sender, 1); require(pymActSucs == true); } msgSndr[msg.sender] = 0; return (true); } //_________________________________________________________ /** * @notice Allows Token owners to Sell Tokens directly to this Contract * */ function sellCoinsToICO( uint256 amountOfCoinsToSell ) public returns (bool success ) { uint amount = amountOfCoinsToSell; msgSndr[msg.sender] = amount; bool isPreview = false; ICO ico = ICO(_getIcoAddr() ); // sell exe at ico bool icosuccess; uint sellPaymentValue; ( icosuccess , sellPaymentValue) = ico.sell( amount, msg.sender, isPreview); require( icosuccess == true ); require( _getIcoAddr().balance >= safeAdd(ico.getMinBal() , sellPaymentValue) ); bool sucsTrTk = false; bool pymActSucs = false; if(isPreview == false){ // token transfer sucsTrTk = _safeTransferTkn( msg.sender, owner, amount); require(sucsTrTk == true); // payment request to ico 1 for redeempayment and 2 for sell payment msgSndr[msg.sender] = sellPaymentValue; pymActSucs = _safePaymentActionAtIco( sellPaymentValue, msg.sender, 2); require(pymActSucs == true); } msgSndr[msg.sender] = 0; return ( true); } //________________________________________________________ /** * @notice a sellers allowed limits in holding ico tokens is checked */ // function _chkSellerLmts( address seller, uint amountOfCoinsSellerCanSell) internal returns(bool success){ uint amountTkns = amountOfCoinsSellerCanSell; success = false; ICO ico = ICO( _getIcoAddr() ); uint seriesCapFactor = ico.getSCF(); if( amountTkns <= balanceOf[seller] && balanceOf[seller] <= safeDiv(allowedIndividualShare*seriesCapFactor,10**18) ){ success = true; } return success; } // bool sucsSlrLmt = _chkSellerLmts( address seller, uint amountTkns); //_________________________________________________________ // /** * @notice a buyers allowed limits in holding ico tokens is checked */ function _chkBuyerLmts( address buyer, uint amountOfCoinsBuyerCanBuy) internal returns(bool success){ uint amountTkns = amountOfCoinsBuyerCanBuy; success = false; ICO ico = ICO( _getIcoAddr() ); uint seriesCapFactor = ico.getSCF(); if( amountTkns <= safeSub( safeDiv(allowedIndividualShare*seriesCapFactor,10**18), balanceOf[buyer] )) { success = true; } return success; } //_________________________________________________________ // /** * @notice a buyers allowed limits in holding ico tokens along with financial capacity to buy is checked */ function _chkBuyerLmtsAndFinl( address buyer, uint amountTkns, uint priceOfr) internal returns(bool success){ success = false; // buyer limits bool sucs1 = false; sucs1 = _chkBuyerLmts( buyer, amountTkns); // buyer funds ICO ico = ICO( _getIcoAddr() ); bool sucs2 = false; if( buyer.balance >= safeAdd( safeMul(amountTkns , priceOfr) , ico.getMinBal() ) ) sucs2 = true; if( sucs1 == true && sucs2 == true) success = true; return success; } //_________________________________________________________ // function _slrByrLmtChk( address seller, uint amountTkns, uint priceOfr, address buyer) internal returns(bool success){ // seller limits check bool successSlrl; (successSlrl) = _chkSellerLmts( seller, amountTkns); // buyer limits check bool successByrlAFinl; (successByrlAFinl) = _chkBuyerLmtsAndFinl( buyer, amountTkns, priceOfr); require( successSlrl == true && successByrlAFinl == true); return true; } //___________________________________________________________________ /** * @notice allows a seller to formally register his sell offer at ExchangeMacroansy */ function sellBkgAtExchg( uint amountOfCoinsOffer, uint priceOfOneCoinInWEI) public returns(bool success){ uint amntTkns = amountOfCoinsOffer ; uint tknPrice = priceOfOneCoinInWEI; // seller limits bool successSlrl; (successSlrl) = _chkSellerLmts( msg.sender, amntTkns); require(successSlrl == true); msgSndr[msg.sender] = amntTkns; // bkg registration at exchange Exchg em = Exchg(_getExchgAddr()); bool emsuccess; (emsuccess) = em.sell_Exchg_Reg( amntTkns, tknPrice, msg.sender ); require(emsuccess == true ); msgSndr[msg.sender] = 0; return true; } //_________________________________________________________ // /** * @notice function for booking and locking for a buy with respect to a sale offer registered * @notice after booking then proceed for payment using func buyCoinsAtExchg * @notice payment booking value and actual payment value should be exact */ function buyBkgAtExchg( address seller, uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint myProposedPaymentInWEI) public returns(bool success){ uint amountTkns = sellersCoinAmountOffer; uint priceOfr = sellersPriceOfOneCoinInWEI; uint payment = myProposedPaymentInWEI; msgSndr[msg.sender] = amountTkns; // seller buyer limits check bool sucsLmt = _slrByrLmtChk( seller, amountTkns, priceOfr, msg.sender); require(sucsLmt == true); // booking at exchange Exchg em = Exchg(_getExchgAddr()); bool emBkgsuccess; (emBkgsuccess)= em.buy_Exchg_booking( seller, amountTkns, priceOfr, msg.sender, payment); require( emBkgsuccess == true ); msgSndr[msg.sender] = 0; return true; } //________________________________________________________ /** * @notice for buyingCoins at ExchangeMacroansy * @notice please first book the buy through function_buy_Exchg_booking */ // function buyCoinsAtExchg( address seller, uint amountTkns, uint priceOfr) payable public returns(bool success) { function buyCoinsAtExchg( address seller, uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI) payable public returns(bool success) { uint amountTkns = sellersCoinAmountOffer; uint priceOfr = sellersPriceOfOneCoinInWEI; require( msg.value > 0 && msg.value <= safeMul(amountTkns, priceOfr ) ); msgSndr[msg.sender] = amountTkns; // calc tokens that can be bought uint tknsBuyAppr = safeDiv(msg.value , priceOfr); // check buyer booking at exchange Exchg em = Exchg(_getExchgAddr()); bool sucsBkgChk = em.buy_Exchg_BkgChk(seller, amountTkns, priceOfr, msg.sender, msg.value); require(sucsBkgChk == true); // update seller reg and buyer booking at exchange msgSndr[msg.sender] = tknsBuyAppr; bool emUpdateSuccess; (emUpdateSuccess) = em.updateSeller(seller, tknsBuyAppr, msg.sender, msg.value); require( emUpdateSuccess == true ); // token transfer in this token contract bool sucsTrTkn = _safeTransferTkn( seller, msg.sender, tknsBuyAppr); require(sucsTrTkn == true); // payment to seller bool sucsTrPaymnt; sucsTrPaymnt = _safeTransferPaymnt( seller, safeSub( msg.value , safeDiv(msg.value*em.getExchgComisnMulByThousand(),1000) ) ); require(sucsTrPaymnt == true ); // BuyAtMacroansyExchg(msg.sender, seller, tknsBuyAppr, msg.value); //event msgSndr[msg.sender] = 0; return true; } //___________________________________________________________ /** * @notice Fall Back Function, not to receive ether directly and/or accidentally * */ function () public payable { if(msg.sender != owner) revert(); } //_________________________________________________________ /* * @notice Burning tokens ie removing tokens from the formal total supply */ function wadmin_burn( uint256 value, bool unburn) onlyOwner public returns( bool success ) { msgSndr[msg.sender] = value; ICO ico = ICO( _getIcoAddr() ); if( unburn == false) { balanceOf[owner] = safeSub( balanceOf[owner] , value); totalSupply = safeSub( totalSupply, value); Burn(owner, value); } if( unburn == true) { balanceOf[owner] = safeAdd( balanceOf[owner] , value); totalSupply = safeAdd( totalSupply , value); UnBurn(owner, value); } bool icosuccess = ico.burn( value, unburn, totalSupplyStart, balanceOf[owner] ); require( icosuccess == true); return true; } //_________________________________________________________ /* * @notice Withdraw Payments to beneficiary * @param withdrawAmount the amount withdrawn in wei */ function wadmin_withdrawFund(uint withdrawAmount) onlyOwner public returns(bool success) { success = _withdraw(withdrawAmount); return success; } //_________________________________________________________ /*internal function can called by this contract only */ function _withdraw(uint _withdrawAmount) internal returns(bool success) { bool sucsTrPaymnt = _safeTransferPaymnt( beneficiaryFunds, _withdrawAmount); require(sucsTrPaymnt == true); return true; } //_________________________________________________________ /** * @notice Allows to receive coins from Contract Share approved by contract * @notice to receive the share, it has to be already approved by the contract * @notice the share Id will be provided by contract while payments are made through other channels like paypal * @param amountOfCoinsToReceive the allocated allowance of coins to be transferred to you * @param ShrID 1 is FounderShare, 2 is POOLShare, 3 is ColdReserveShare, 4 is VCShare, 5 is PublicShare, 6 is RdmSellPool */ function receiveICOcoins( uint256 amountOfCoinsToReceive, uint ShrID ) public returns (bool success){ msgSndr[msg.sender] = amountOfCoinsToReceive; ICO ico = ICO( _getIcoAddr() ); bool icosuccess; icosuccess = ico.recvShrICO(msg.sender, amountOfCoinsToReceive, ShrID ); require (icosuccess == true); bool sucsTrTk; sucsTrTk = _safeTransferTkn( owner, msg.sender, amountOfCoinsToReceive); require(sucsTrTk == true); msgSndr[msg.sender] = 0; return true; } //_______________________________________________________ // called by other contracts function sendMsgSndr(address caller, address origin) public returns(bool success, uint value){ (success, value) = _sendMsgSndr(caller, origin); return(success, value); } //_______________________________________________________ // function _sendMsgSndr(address caller, address origin) internal returns(bool success, uint value){ require(caller == _getIcoAddr() || caller == _getExchgAddr()); //require(origin == tx.origin); return(true, msgSndr[origin]); } //_______________________________________________________ // function a_viewSellOffersAtExchangeMacroansy(address seller, bool show) view public returns (uint sellersCoinAmountOffer, uint sellersPriceOfOneCoinInWEI, uint sellerBookedTime, address buyerWhoBooked, uint buyPaymentBooked, uint buyerBookedTime, uint exchgCommissionMulByThousand_){ if(show == true){ Exchg em = Exchg(_getExchgAddr()); ( sellersCoinAmountOffer, sellersPriceOfOneCoinInWEI, sellerBookedTime, buyerWhoBooked, buyPaymentBooked, buyerBookedTime, exchgCommissionMulByThousand_) = em.viewSellOffersAtExchangeMacroansy( seller, show) ; return ( sellersCoinAmountOffer, sellersPriceOfOneCoinInWEI, sellerBookedTime, buyerWhoBooked, buyPaymentBooked, buyerBookedTime, exchgCommissionMulByThousand_); } } //_________________________________________________________ // function a_viewCoinSupplyAndFunding(bool show) public view returns(uint totalSupplyOfCoinsInSeriesNow, uint coinsAvailableForSale, uint icoFunding){ if(show == true){ ICO ico = ICO( _getIcoAddr() ); ( totalSupplyOfCoinsInSeriesNow, coinsAvailableForSale, icoFunding) = ico.getAvlShares(show); return( totalSupplyOfCoinsInSeriesNow, coinsAvailableForSale, icoFunding); } } //_______________________________________________________ // /* bool private isEndOk; function endOfRewards(bool isEndNow) public onlyOwner { isEndOk == isEndNow; } function endOfRewardsConfirmed(bool isEndNow) public onlyOwner{ if(isEndOk == true && isEndNow == true) selfdestruct(owner); } */ //_______________________________________________________ } // END_OF_CONTRACT
_________________________________________________________
function _safeTransferPaymnt( address paymentBenfcry, uint payment) internal returns(bool sucsTrPaymnt){ uint pA = payment; uint paymentTemp = pA; pA = 0; paymentBenfcry.transfer(paymentTemp); FundOrPaymentTransfer(paymentBenfcry, paymentTemp); paymentTemp = 0; return true; }
7,901,579
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.2 /**************************************************************************** Written by Oliver Straszynski https://github.com/broliver12/ ****************************************************************************/ pragma solidity ^0.8.4; import './ERC721A_indexExt.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; contract CoreERC721A is ERC721A_indexExt, Ownable, ReentrancyGuard { // Control Params bool private revealed; string private baseURI; string private notRevealedURI; string private baseExtension = '.json'; bool public publicMintEnabled; uint256 public immutable totalDevSupply; uint256 public immutable totalCollectionSize; // Mint Limits uint256 public maxMints = 20; // Price uint256 public unitPrice = 0.02 ether; // TOTAL supply for devs, marketing, friends, family uint256 private remainingDevSupply = 55; constructor( string memory name_, string memory symbol_ ) ERC721A_indexExt( name_, symbol_ ) { // Set collection size totalCollectionSize = 5555; // Set dev supply totalDevSupply = remainingDevSupply; } // Ensure caller is a wallet modifier isWallet() { require(tx.origin == msg.sender, 'Cant be a contract'); _; } // Ensure there's enough supply to mint the quantity modifier enoughSupply(uint256 quantity) { require(totalSupply() + quantity <= totalCollectionSize, 'reached max supply'); _; } // Mint function for public sale // Requires minimum ETH value of unitPrice * quantity function publicMint(uint256 quantity) external payable isWallet enoughSupply(quantity) { require(publicMintEnabled, 'Minting not enabled'); require(quantity <= maxMints, 'Illegal quantity'); require(numberMinted(msg.sender) + quantity <= maxMints, 'Cant mint that many'); require(msg.value >= quantity * unitPrice, 'Not enough ETH'); _safeMint(msg.sender, quantity); refundIfOver(quantity * unitPrice); } // Mint function for developers (owner) // Mints a maximum of 20 NFTs to the recipient // Used for devs, marketing, friends, family // Capped at 55 mints total function devMint(uint256 quantity, address recipient) external onlyOwner enoughSupply(quantity) { require(remainingDevSupply - quantity >= 0, 'Not enough dev supply'); require(quantity <= maxMints, 'Illegal quantity'); require(numberMinted(recipient) + quantity <= maxMints, 'Cant mint that many (dev)'); remainingDevSupply = remainingDevSupply - quantity; _safeMint(recipient, quantity); } // Returns the correct URI for the given tokenId based on contract state function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'Nonexistent token'); if(!revealed){ return notRevealedURI; } return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId), baseExtension)) : ''; } // Set Price for Public Mint. function setPrice(uint256 _price) external onlyOwner { unitPrice = _price; } // Change base metadata URI // Only will be called if something fatal happens to initial base URI function setBaseURI(string calldata _baseURI) external onlyOwner { baseURI = _baseURI; } // Only will be called if something fatal happens to initial base URI function setBaseExtension(string calldata _baseExtension) external onlyOwner { baseExtension = _baseExtension; } // Sets URI for pre-reveal art metadata function setNotRevealedURI(string calldata _notRevealedURI) external onlyOwner { notRevealedURI = _notRevealedURI; } // Set the mint state function setMintState(uint256 _state) external virtual onlyOwner { if (_state == 1) { publicMintEnabled = true; } else { publicMintEnabled = false; } } // Set revealed to true (displays baseURI instead of notRevealedURI on opensea) function reveal(bool _revealed) external onlyOwner { revealed = _revealed; } // Returns the amount the address has minted function numberMinted(address minterAddr) public view returns (uint256) { return _numberMinted(minterAddr); } // Returns the ownership data for the given tokenId function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return _ownershipOf(tokenId); } // Withdraw entire contract value to owners wallet function withdraw() external onlyOwner nonReentrant { (bool success, ) = msg.sender.call{value: address(this).balance}(''); require(success, 'Withdraw failed'); } // Refunds extra ETH if minter sends too much function refundIfOver(uint256 price) internal { if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } } }
Sets URI for pre-reveal art metadata
function setNotRevealedURI(string calldata _notRevealedURI) external onlyOwner { notRevealedURI = _notRevealedURI; }
12,843,268
./partial_match/3/0x1F2059e65bB11E831FF0DdC2C62aAca2FC996b53/sources/AddressBook.sol
get the lenght of the addresses in the array from the msg sender if the address that you want to remove = one of the addresses you ownand is one of the iterations of the looponce we find the item in the array we need to delete the itemthen shift each item down 1. You can just delete an item in the middle of an arraymake sure the length of the address is not < 1 (this is needed because we are going to reorder the array)shift the last item in the array to the position of the item that we are removing
function removeAddress(address addr) public { uint length = _addresses[msg.sender].length; for(uint i = 0; i < length; i++) { if (addr == _addresses[msg.sender][i]) { if(1 < _addresses[msg.sender].length && i < length-1) { _addresses[msg.sender][i] = _addresses[msg.sender][length-1]; } } } }
5,139,480
pragma solidity 0.8.4; pragma experimental ABIEncoderV2; //SPDX-License-Identifier: GPL import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** @title The TALENT token is the utility token of the Talent DAO * @author jaxcoder * @notice Handles voting and delegation of token voting rights and all other ERC20 functions * @dev Contract is pretty straightforward ERC20 token contract with some governance. */ contract TalentDaoToken is Ownable, AccessControl, ERC20 { using SafeERC20 for IERC20; mapping(address => uint96) internal _balances; mapping(address => address) internal _delegates; mapping(address => mapping(address => uint256)) public allowances; 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 The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); // Roles bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant DAO_ROLE = keccak256("DAO_ROLE"); bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE"); /// @notice A record of states for signing / validating signatures mapping (address => uint) private _nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice An event thats emitted when a snapshot has been done event SnapshotDone(address owner, uint128 oldValue, uint128 newValue); struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice Modifiers for Access Control modifier isPermittedMinter() { require( hasRole(MINTER_ROLE, msg.sender), "Not an approved minter" ); _; } modifier isPermittedDao() { require( hasRole(DAO_ROLE, msg.sender), "Not an approved DAO" ); _; } modifier isPermittedOperator() { require( hasRole(OPERATOR_ROLE, msg.sender), "Not an approved minter" ); _; } modifier isPermittedDistributor() { require( hasRole(DISTRIBUTOR_ROLE, msg.sender), "Not an approved distributor" ); _; } modifier isAdminOrOwner() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || owner() == msg.sender, "You can't perform admin or owner actions" ); _; } modifier hasEnoughBalance(uint256 balance, uint256 amount) { require(balance >= amount, "Not enough token balance"); _; } constructor(address owner_) public ERC20("Talent DAO Token", "TALENT") { _setupRole(DEFAULT_ADMIN_ROLE, owner_); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); // Mint some tokens... test.... mintTokensTo(owner_, 200000000 ether); // 200 Million _revokeRole(MINTER_ROLE, _msgSender()); transferOwnership(owner_); } /** @dev only the default admin role can add a minter * */ function setupMinterRole(address minter) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "need to be admin to add minter"); _setupRole(MINTER_ROLE, minter); } /** @dev only the default admin role can add an operator * */ function setupOperatorRole(address minter) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "need to be admin to add operator"); _setupRole(OPERATOR_ROLE, minter); } /** @dev only the owner can add a DAO role * */ function setupDaoRole(address minter) public onlyOwner { _setupRole(DAO_ROLE, minter); } /** @dev the operator and the admin roles can add a distributor * */ function setupDistributorRole(address minter) public { require(hasRole(OPERATOR_ROLE, _msgSender()) || hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "need to be admin to add minter"); _setupRole(DISTRIBUTOR_ROLE, minter); } /** @notice Creates `_amount` token to `_to`. Must only be called by permitted minter. * @param _to who the tokens are minted to * @param _amount the amount of tokens to mint */ function mintTokensTo(address _to, uint256 _amount) public isPermittedMinter { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: do we want to do anything before each transfer? */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) public virtual { require(block.timestamp <= deadline, "TALENT :: past the fucking deadline bro!"); uint256 nonce = _nonces[owner]; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonce, deadline)); bytes32 digest = keccak256(abi.encodePacked(uint16(0x1901), domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "TALENT :: permit: invalid signature ~ zero address mofo!"); require(signatory == owner, "TALENT :: permit: unauthorized ~ must be the owner of the signature..."); // increase nonce for the owner _nonces[owner]++; // call the approve function or allowances function allowances[owner][spender] = rawAmount; _approve(owner, spender, rawAmount); emit Approval(owner, spender, rawAmount); } /** * @notice Returns the `delegatee` * @param delegator The address to get delegatee for */ function delegatesView(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(_msgSender(), delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig ( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "TALENT::delegateBySig: invalid signature"); require(nonce == _nonces[signatory]++, "TALENT::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "TALENT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "TALENT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying PHRO (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "TALENT::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "TALENT::_transferTokens: cannot transfer to the zero address"); _balances[src] = sub96(_balances[src], amount, "TALENT::_transferTokens: transfer amount exceeds balance"); _balances[dst] = add96(_balances[dst], amount, "TALENT::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(_delegates[src], _delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "TALENT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
only the owner can add a DAO role/
function setupDaoRole(address minter) public onlyOwner { _setupRole(DAO_ROLE, minter); }
12,829,136
pragma solidity ^0.4.13; contract Receiver { function tokenFallback(address from, uint value, bytes data); } /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint public totalSupply; function balanceOf(address who) public constant returns (uint); function allowance(address owner, address spender) public constant returns (uint); function transfer(address to, uint value) public returns (bool ok); function transferFrom(address from, address to, uint value) public returns (bool ok); function approve(address spender, uint value) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * Math operations with safety checks */ contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { revert(); } } } /** * 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, SafeMath { event Transfer(address indexed from, address indexed to, uint indexed value, bytes data); /* 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) balances; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; /** * * Fix for the ERC20 short address attack * * http://vessenes.com/the-erc20-short-address-attack-explained/ */ modifier onlyPayloadSize(uint size) { if(msg.data.length != size + 4) { revert(); } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) public returns (bool success) { bytes memory _empty; return transfer(_to, _value, _empty); } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value, _data); Transfer(msg.sender, _to, _value); if (isContract(_to)) { Receiver(_to).tokenFallback(msg.sender, _value, _data); } return true; } // ERC223 fetch contract size (must be nonzero to be a contract) function isContract( address _addr ) private returns (bool) { uint length; _addr = _addr; assembly { length := extcodesize(_addr) } return (length > 0); } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { uint _allowance = allowed[_from][msg.sender]; // Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) revert(); balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant 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; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } /** * Atomic increment of approved spending * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * */ function addApproval(address _spender, uint _addedValue) public onlyPayloadSize(2 * 32) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; allowed[msg.sender][_spender] = safeAdd(oldValue, _addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * Atomic decrement of approved spending. * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function subApproval(address _spender, uint _subtractedValue) public onlyPayloadSize(2 * 32) returns (bool success) { uint oldVal = allowed[msg.sender][_spender]; if (_subtractedValue > oldVal) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = safeSub(oldVal, _subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BurnableToken is StandardToken { address public constant BURN_ADDRESS = 0; /** How many tokens we burned */ event Burned(address burner, uint burnedAmount); /** * Burn extra tokens from a balance. * */ function burn(uint burnAmount) public { address burner = msg.sender; balances[burner] = safeSub(balances[burner], burnAmount); totalSupply = safeSub(totalSupply, burnAmount); Burned(burner, burnAmount); } } /** * Upgrade agent interface inspired by Lunyr. * * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. */ contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * * First envisioned by Golem and Lunyr projects. */ contract UpgradeableToken is StandardToken { /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) public { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { // Called in a bad state revert(); } // Validate input value. if (value == 0) revert(); balances[msg.sender] = safeSub(balances[msg.sender], value); // Take tokens out from circulation totalSupply = safeSub(totalSupply, value); totalUpgraded = safeAdd(totalUpgraded, value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { if(!canUpgrade()) { // The token is not yet in a state that we could think upgrading revert(); } if (agent == 0x0) revert(); // Only a master can designate the next agent if (msg.sender != upgradeMaster) revert(); // Upgrade has already begun for an agent if (getUpgradeState() == UpgradeState.Upgrading) revert(); upgradeAgent = UpgradeAgent(agent); // Bad interface if(!upgradeAgent.isUpgradeAgent()) revert(); // Make sure that token supplies match in source and target if (upgradeAgent.originalSupply() != totalSupply) revert(); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { if (master == 0x0) revert(); if (msg.sender != upgradeMaster) revert(); upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public constant returns(bool) { return true; } } contract WeToken is BurnableToken, UpgradeableToken { string public name; string public symbol; uint public decimals; address public owner; bool public mintingFinished = false; mapping(address => uint) public previligedBalances; /** List of agents that are allowed to create new tokens */ mapping(address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state); modifier onlyOwner() { if(msg.sender != owner) revert(); _; } 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(); _; } modifier onlyNotSame(address _from, address _to) { if(_from == _to) revert(); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } function WeToken(address _owner, string _name, string _symbol, uint _totalSupply, uint _decimals) public UpgradeableToken(_owner) { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply * 10 ** uint(decimals); // Allocate initial balance to the owner balances[_owner] = totalSupply; // save the owner owner = _owner; } function mintingFinish() public onlyOwner { mintingFinished = true; } // privileged transfer function transferPrivileged(address _to, uint _value) public onlyOwner returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); previligedBalances[_to] = safeAdd(previligedBalances[_to], _value); Transfer(msg.sender, _to, _value); return true; } // get priveleged balance function getPrivilegedBalance(address _owner) public constant returns (uint balance) { return previligedBalances[_owner]; } // admin only can transfer from the privileged accounts function transferFromPrivileged(address _from, address _to, uint _value) public onlyOwner onlyNotSame(_from, _to) returns (bool success) { uint availablePrevilegedBalance = previligedBalances[_from]; balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); previligedBalances[_from] = safeSub(availablePrevilegedBalance, _value); Transfer(_from, _to, _value); return true; } /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) onlyMintAgent canMint public { amount *= 10 ** uint(decimals); totalSupply = safeAdd(totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } }
ERC223 fetch contract size (must be nonzero to be a contract)
function isContract( address _addr ) private returns (bool) { uint length; _addr = _addr; return (length > 0); }
72,808
./full_match/1/0x5de58BF4ef40e923797aFF1767F8ed4143e6c032/sources/contracts/rate_oracles/BaseRateOracle.sol
@inheritdoc IRateOracle
function writeOracleEntry() external virtual override(IRateOracle) { (oracleVars.rateIndex, oracleVars.rateCardinality) = writeRate( oracleVars.rateIndex, oracleVars.rateCardinality, oracleVars.rateCardinalityNext ); }
16,410,655
pragma solidity 0.5.16; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; contract TrustlessFund is Ownable { using SafeMath for uint; /*** STORAGE VARIABLES ***/ /** * @notice Date time in seconds when timelock expires. */ uint public expiration; /** * @notice Address permitted to withdraw funds after unlock. */ address public beneficiary; /** * @notice Token balances. */ mapping(address => uint) balances; /*** EVENTS ***/ /** * @notice Emits when a deposit is made. */ event Deposit(address indexed _from, uint _value, address indexed _token); /** * @notice Emits when a withdrawal is made. */ event Withdraw(address indexed _to, uint _value, address indexed _token); /** * @notice Emits when the expiration is increased. */ event IncreaseTime(uint _newExpiration); /** * @notice Emits when the beneficiary is updated. */ event UpdateBeneficiary(address indexed _newBeneficiary); /*** MODIFIERS ***/ /** * @dev Throws if the contract has not yet reached its expiration. */ modifier isExpired() { require(expiration < block.timestamp, 'contract is still locked'); _; } /** * @dev Throws if msg.sender is not the beneficiary. */ modifier onlyBeneficiary() { require(msg.sender == beneficiary, 'only the beneficiary can perform this function'); _; } /** * @param _expiration Date time in seconds when timelock expires. * @param _beneficiary Address permitted to withdraw funds after unlock. * @param _owner The contract owner. */ constructor(uint _expiration, address _beneficiary, address _owner) public { expiration = _expiration; beneficiary = _beneficiary; transferOwnership(_owner); } /*** VIEW/PURE FUNCTIONS ***/ /*** OTHER FUNCTIONS ***/ /** * @dev Allows a user to deposit ETH or an ERC20 into the contract. If _token is 0 address, deposit ETH. * @param _amount The amount to deposit. * @param _token The token to deposit. */ function deposit(uint _amount, address _token) public payable { if(_token == address(0)) { require(msg.value == _amount, 'incorrect amount'); balances[_token] += _amount; emit Deposit(msg.sender, _amount, _token); } else { IERC20 token = IERC20(_token); require(token.transferFrom(msg.sender, address(this), _amount), 'transfer failed'); balances[_token] += _amount; emit Deposit(msg.sender, _amount, _token); } } /** * @dev Withdraw funds to msg.sender, but only if the timelock is expired and msg.sender is the beneficiary. If _token is 0 address, withdraw ETH. * @param _amount The amount to withdraw. * @param _token The token to withdraw. */ function withdraw(uint _amount, address _token) public isExpired() onlyBeneficiary() { if(_token == address(0)) { require(address(this).balance >= _amount, 'not enough balance'); balances[_token] -= _amount; (bool success, ) = msg.sender.call.value(_amount)(""); require(success, "Transfer failed."); emit Withdraw(msg.sender, _amount, _token); } else { IERC20 token = IERC20(_token); require(token.balanceOf(address(this)) >= _amount, 'not enough balance'); balances[_token] -= _amount; require(token.transfer(msg.sender, _amount), 'transfer failed'); emit Withdraw(msg.sender, _amount, _token); } } /** * @dev Increase the time until expiration. Only the owner can perform this. * @param _newExpiration New date time in seconds when timelock expires. */ function increaseTime(uint _newExpiration) public onlyOwner() { require(_newExpiration > expiration, 'can only increase expiration'); expiration = _newExpiration; emit IncreaseTime(_newExpiration); } /** * @dev Update the beneficiary address. Only the owner can perform this. * @param _newBeneficiary New beneficiary address. */ function updateBeneficiary(address _newBeneficiary) public onlyOwner() { require(_newBeneficiary != beneficiary, 'same beneficiary'); require(_newBeneficiary != address(0), 'cannot set as burn address'); beneficiary = _newBeneficiary; emit UpdateBeneficiary(_newBeneficiary); } }
_amount The amount to withdraw. _token The token to withdraw./
function withdraw(uint _amount, address _token) public isExpired() onlyBeneficiary() { if(_token == address(0)) { require(address(this).balance >= _amount, 'not enough balance'); balances[_token] -= _amount; (bool success, ) = msg.sender.call.value(_amount)(""); require(success, "Transfer failed."); emit Withdraw(msg.sender, _amount, _token); IERC20 token = IERC20(_token); require(token.balanceOf(address(this)) >= _amount, 'not enough balance'); balances[_token] -= _amount; require(token.transfer(msg.sender, _amount), 'transfer failed'); emit Withdraw(msg.sender, _amount, _token); } }
15,857,139
./full_match/1/0x31b0e17db1D02B079177698dF2eD7037Fc1d0B2c/sources/src/WorldIDRouterImplV1.sol
Gets the route for the provided group number. groupNumber The number of the group to get the route for. return target The target address for the group number. @custom:reverts NoSuchGroup If the requested `groupNumber` does not exist. @custom:reverts GroupDisabled If the group has been disabled. We want to revert if the group does not exist. If there is no valid route for a given group we also revert.
function routeFor(uint256 groupNumber) public view virtual onlyProxy onlyInitialized returns (IWorldID) { if (groupNumber >= groupCount()) { revert NoSuchGroup(groupNumber); } if (routingTable[groupNumber] == NULL_ROUTER) { revert GroupIsDisabled(); } }
9,673,869
/** * LockRule.sol * Rule to lock all tokens on a schedule and define a whitelist of exceptions. * More info about MPS : https://github.com/MtPelerin/MtPelerin-share-MPS * The unflattened code is available through this github tag: * https://github.com/MtPelerin/MtPelerin-protocol/tree/etherscan-verify-batch-2 * @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved * @notice All matters regarding the intellectual property of this code * @notice or software are subject to Swiss Law without reference to its * @notice conflicts of law rules. * @notice License for each contract is available in the respective file * @notice or in the LICENSE.md file. * @notice https://github.com/MtPelerin/ * @notice Code by OpenZeppelin is copyrighted and licensed on their repository: * @notice https://github.com/OpenZeppelin/openzeppelin-solidity */ pragma solidity ^0.4.24; // File: contracts/zeppelin/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; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/Authority.sol /** * @title Authority * @dev The Authority contract has an authority address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * Authority means to represent a legal entity that is entitled to specific rights * * @author Cyril Lapinte - <[email protected]> * * @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved * @notice Please refer to the top of this file for the license. * * Error messages * AU01: Message sender must be an authority */ contract Authority is Ownable { address authority; /** * @dev Throws if called by any account other than the authority. */ modifier onlyAuthority { require(msg.sender == authority, "AU01"); _; } /** * @dev Returns the address associated to the authority */ function authorityAddress() public view returns (address) { return authority; } /** Define an address as authority, with an arbitrary name included in the event * @dev returns the authority of the * @param _name the authority name * @param _address the authority address. */ function defineAuthority(string _name, address _address) public onlyOwner { emit AuthorityDefined(_name, _address); authority = _address; } event AuthorityDefined( string name, address _address ); } // File: contracts/interface/IRule.sol /** * @title IRule * @dev IRule interface * @author Cyril Lapinte - <[email protected]> * * @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved * @notice Please refer to the top of this file for the license. **/ interface IRule { function isAddressValid(address _address) external view returns (bool); function isTransferValid(address _from, address _to, uint256 _amount) external view returns (bool); } // File: contracts/rule/LockRule.sol /** * @title LockRule * @dev LockRule contract * This rule allow to lock assets for a period of time * for event such as investment vesting * * @author Cyril Lapinte - <[email protected]> * * @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved * @notice Please refer to the top of this file for the license. * * Error messages * LOR01: definePass() call have failed * LOR02: startAt must be before or equal to endAt */ contract LockRule is IRule, Authority { enum Direction { NONE, RECEIVE, SEND, BOTH } struct ScheduledLock { Direction restriction; uint256 startAt; uint256 endAt; bool scheduleInverted; } mapping(address => Direction) individualPasses; ScheduledLock lock = ScheduledLock( Direction.NONE, 0, 0, false ); /** * @dev hasSendDirection */ function hasSendDirection(Direction _direction) public pure returns (bool) { return _direction == Direction.SEND || _direction == Direction.BOTH; } /** * @dev hasReceiveDirection */ function hasReceiveDirection(Direction _direction) public pure returns (bool) { return _direction == Direction.RECEIVE || _direction == Direction.BOTH; } /** * @dev restriction */ function restriction() public view returns (Direction) { return lock.restriction; } /** * @dev scheduledStartAt */ function scheduledStartAt() public view returns (uint256) { return lock.startAt; } /** * @dev scheduledEndAt */ function scheduledEndAt() public view returns (uint256) { return lock.endAt; } /** * @dev lock inverted */ function isScheduleInverted() public view returns (bool) { return lock.scheduleInverted; } /** * @dev isLocked */ function isLocked() public view returns (bool) { // solium-disable-next-line security/no-block-members return (lock.startAt <= now && lock.endAt > now) ? !lock.scheduleInverted : lock.scheduleInverted; } /** * @dev individualPass */ function individualPass(address _address) public view returns (Direction) { return individualPasses[_address]; } /** * @dev can the address send */ function canSend(address _address) public view returns (bool) { if (isLocked() && hasSendDirection(lock.restriction)) { return hasSendDirection(individualPasses[_address]); } return true; } /** * @dev can the address receive */ function canReceive(address _address) public view returns (bool) { if (isLocked() && hasReceiveDirection(lock.restriction)) { return hasReceiveDirection(individualPasses[_address]); } return true; } /** * @dev allow authority to provide a pass to an address */ function definePass(address _address, uint256 _lock) public onlyAuthority returns (bool) { individualPasses[_address] = Direction(_lock); emit PassDefinition(_address, Direction(_lock)); return true; } /** * @dev allow authority to provide addresses with lock passes */ function defineManyPasses(address[] _addresses, uint256 _lock) public onlyAuthority returns (bool) { for (uint256 i = 0; i < _addresses.length; i++) { require(definePass(_addresses[i], _lock), "LOR01"); } return true; } /** * @dev schedule lock */ function scheduleLock( Direction _restriction, uint256 _startAt, uint256 _endAt, bool _scheduleInverted) public onlyAuthority returns (bool) { require(_startAt <= _endAt, "LOR02"); lock = ScheduledLock( _restriction, _startAt, _endAt, _scheduleInverted ); emit LockDefinition( lock.restriction, lock.startAt, lock.endAt, lock.scheduleInverted); } /** * @dev validates an address */ function isAddressValid(address /*_address*/) public view returns (bool) { return true; } /** * @dev validates a transfer of ownership */ function isTransferValid(address _from, address _to, uint256 /* _amount */) public view returns (bool) { return (canSend(_from) && canReceive(_to)); } event LockDefinition( Direction restriction, uint256 startAt, uint256 endAt, bool scheduleInverted ); event PassDefinition(address _address, Direction pass); }
hasReceiveDirection/
function hasReceiveDirection(Direction _direction) public pure returns (bool) { return _direction == Direction.RECEIVE || _direction == Direction.BOTH; }
12,746,380
./partial_match/1/0x11B36d9B13B51AA76647998C723cFbCEfbaFF9D8/sources/Locker.sol
clean up storage to save gas
function withdrawPartially(uint256 lockId, uint256 amount) public nonReentrant onlyLockOwner(lockId) { Lock storage lock = tokenLocks[lockId]; require(block.timestamp > lock.unlockTime, "You must to attend your locktime!"); IERC20(lock.token).transfer(lock.owner, amount); lock.amount = lock.amount.sub(amount); if(lock.amount == 0) { userLocks[lock.owner].remove(lockId); delete tokenLocks[lockId]; } }
2,754,264
./full_match/84531/0xaBf20d6c101bd3DD955902056a4aE277faf8d62f/sources/project:/contracts/seedify-fund.sol
userdetail poolsale
function getTotalInvestResult(address investor) public view returns(uint256 ethAmount) { return (getPoolOverflowInvestResult(investor) + userDetail[investor].investedAmount); }
11,502,024
pragma solidity ^0.5.0; import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; import "./uniswap/UniswapV2Factory.sol"; import "./PairTokenManager.sol"; /// @title zkSync main contract /// @author Matter Labs /// @author ZKSwap L2 Labs contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; bytes32 public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //create pair function createPair(address _tokenA, address _tokenB) external { requireActive(); governance.requireTokenLister(msg.sender); //check _tokenA is registered or not uint16 tokenAID = governance.validateTokenAddress(_tokenA); //check _tokenB is registered or not uint16 tokenBID = governance.validateTokenAddress(_tokenB); //make sure _tokenA is fee token require(tokenAID <= MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "tokenA should be fee token"); //create pair address pair = pairmanager.createPair(_tokenA, _tokenB); require(pair != address(0), "pair is invalid"); addPairToken(pair); registerCreatePair( tokenAID, _tokenA, tokenBID, _tokenB, validatePairTokenAddress(pair), pair ); } //create pair including ETH function createETHPair(address _tokenERC20) external { requireActive(); governance.requireTokenLister(msg.sender); //check _tokenERC20 is registered or not uint16 erc20ID = governance.validateTokenAddress(_tokenERC20); //create pair address pair = pairmanager.createPair(address(0), _tokenERC20); require(pair != address(0), "pair is invalid"); addPairToken(pair); registerCreatePair( 0, address(0), erc20ID, _tokenERC20, validatePairTokenAddress(pair), pair ); } function registerCreatePair(uint16 _tokenAID, address _tokenA, uint16 _tokenBID, address _tokenB, uint16 _tokenPair, address _pair) internal { // Priority Queue request Operations.CreatePair memory op = Operations.CreatePair({ accountId : 0, //unknown at this point tokenA : _tokenAID, tokenB : _tokenBID, tokenPair : _tokenPair, pair : _pair }); bytes memory pubData = Operations.writeCreatePairPubdata(op); bytes memory userData = abi.encodePacked( _tokenA, // tokenA address _tokenB // tokenB address ); addPriorityRequest(Operations.OpType.CreatePair, pubData, userData); emit OnchainCreatePair(_tokenAID, _tokenBID, _tokenPair, _pair); } // Upgrade functional /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint) { return UPGRADE_NOTICE_PERIOD; } /// @notice Notification that upgrade notice period started function upgradeNoticePeriodStarted() external { } /// @notice Notification that upgrade preparation status is activated function upgradePreparationStarted() external { upgradePreparationActive = true; upgradePreparationActivationTime = now; } /// @notice Notification that upgrade canceled function upgradeCanceled() external { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Notification that upgrade finishes function upgradeFinishes() external { upgradePreparationActive = false; upgradePreparationActivationTime = 0; } /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool) { return !exodusMode; } constructor() public { governance = Governance(msg.sender); zkSyncCommitBlockAddress = address(this); zkSyncExitAddress = address(this); } /// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _governanceAddress The address of Governance contract /// _verifierAddress The address of Verifier contract /// _ // FIXME: remove _genesisAccAddress /// _genesisRoot Genesis blocks (first block) root function initialize(bytes calldata initializationParameters) external { require(address(governance) == address(0), "init0"); initializeReentrancyGuard(); ( address _governanceAddress, address _verifierAddress, address _verifierExitAddress, address _pairManagerAddress ) = abi.decode(initializationParameters, (address, address, address, address)); verifier = Verifier(_verifierAddress); verifierExit = VerifierExit(_verifierExitAddress); governance = Governance(_governanceAddress); pairmanager = UniswapV2Factory(_pairManagerAddress); maxDepositAmount = DEFAULT_MAX_DEPOSIT_AMOUNT; withdrawGasLimit = ERC20_WITHDRAWAL_GAS_LIMIT; } function setGenesisRootAndAddresses(bytes32 _genesisRoot, address _zkSyncCommitBlockAddress, address _zkSyncExitAddress) external { // This function cannot be called twice as long as // _zkSyncCommitBlockAddress and _zkSyncExitAddress have been set to // non-zero. require(zkSyncCommitBlockAddress == address(0), "sraa1"); require(zkSyncExitAddress == address(0), "sraa2"); blocks[0].stateRoot = _genesisRoot; zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress; zkSyncExitAddress = _zkSyncExitAddress; } /// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} /// @notice Sends tokens /// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @param _maxAmount Maximum possible amount of tokens to transfer to this account function withdrawERC20Guarded(IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount) external returns (uint128 withdrawnAmount) { require(msg.sender == address(this), "wtg10"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed) uint16 lpTokenId = tokenIds[address(_token)]; uint256 balance_before = _token.balanceOf(address(this)); if (lpTokenId > 0) { validatePairTokenAddress(address(_token)); pairmanager.mint(address(_token), _to, _amount); } else { require(Utils.sendERC20(_token, _to, _amount), "wtg11"); // wtg11 - ERC20 transfer fails } uint256 balance_after = _token.balanceOf(address(this)); uint256 balance_diff = balance_before.sub(balance_after); require(balance_diff <= _maxAmount, "wtg12"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount return SafeCast.toUint128(balance_diff); } /// @notice executes pending withdrawals /// @param _n The number of withdrawals to complete starting from oldest function completeWithdrawals(uint32 _n) external nonReentrant { // TODO: when switched to multi validators model we need to add incentive mechanism to call complete. uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals); uint32 startIndex = firstPendingWithdrawalIndex; numberOfPendingWithdrawals -= toProcess; firstPendingWithdrawalIndex += toProcess; for (uint32 i = startIndex; i < startIndex + toProcess; ++i) { uint16 tokenId = pendingWithdrawals[i].tokenId; address to = pendingWithdrawals[i].to; // send fails are ignored hence there is always a direct way to withdraw. delete pendingWithdrawals[i]; bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId); uint128 amount = balancesToWithdraw[packedBalanceKey].balanceToWithdraw; // amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20 if (amount != 0) { balancesToWithdraw[packedBalanceKey].balanceToWithdraw -= amount; bool sent = false; if (tokenId == 0) { address payable toPayable = address(uint160(to)); sent = Utils.sendETHNoRevert(toPayable, amount); } else { address tokenAddr = address(0); if (tokenId < PAIR_TOKEN_START_ID) { // It is normal ERC20 tokenAddr = governance.tokenAddresses(tokenId); } else { // It is pair token tokenAddr = tokenAddresses[tokenId]; } // tokenAddr cannot be 0 require(tokenAddr != address(0), "cwt0"); // we can just check that call not reverts because it wants to withdraw all amount (sent,) = address(this).call.gas(withdrawGasLimit)( abi.encodeWithSignature("withdrawERC20Guarded(address,address,uint128,uint128)", tokenAddr, to, amount, amount) ); } if (!sent) { balancesToWithdraw[packedBalanceKey].balanceToWithdraw += amount; } } } if (toProcess > 0) { emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess); } } /// @notice Accrues users balances from deposit priority requests in Exodus mode /// @dev WARNING: Only for Exodus mode /// @dev Canceling may take several separate transactions to be completed /// @param _n number of requests to process function cancelOutstandingDepositsForExodusMode(uint64 _n) external nonReentrant { require(exodusMode, "coe01"); // exodus mode not active uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n); require(toProcess > 0, "coe02"); // no deposits to process for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) { if (priorityRequests[id].opType == Operations.OpType.Deposit) { Operations.Deposit memory op = Operations.readDepositPubdata(priorityRequests[id].pubData); bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId); balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op.amount; } delete priorityRequests[id]; } firstPriorityRequestId += toProcess; totalOpenPriorityRequests -= toProcess; } /// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit /// @param _franklinAddr The receiver Layer 2 address function depositETH(address _franklinAddr) external payable nonReentrant { requireActive(); registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr); } /// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender /// @param _amount Ether amount to withdraw function withdrawETH(uint128 _amount) external nonReentrant { registerWithdrawal(0, _amount, msg.sender); (bool success,) = msg.sender.call.value(_amount)(""); require(success, "fwe11"); // ETH withdraw failed } /// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to _to address /// @param _amount Ether amount to withdraw function withdrawETHWithAddress(uint128 _amount, address payable _to) external nonReentrant { require(_to != address(0), "ipa11"); registerWithdrawal(0, _amount, _to); (bool success,) = _to.call.value(_amount)(""); require(success, "fwe12"); // ETH withdraw failed } /// @notice Config amount limit for each ERC20 deposit /// @param _amount Max deposit amount function setMaxDepositAmount(uint128 _amount) external { governance.requireGovernor(msg.sender); maxDepositAmount = _amount; } /// @notice Config gas limit for withdraw erc20 token /// @param _gasLimit withdraw erc20 gas limit function setWithDrawGasLimit(uint256 _gasLimit) external { governance.requireGovernor(msg.sender); withdrawGasLimit = _gasLimit; } /// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit /// @param _token Token address /// @param _amount Token amount /// @param _franklinAddr Receiver Layer 2 address function depositERC20(IERC20 _token, uint104 _amount, address _franklinAddr) external nonReentrant { requireActive(); // Get token id by its address uint16 lpTokenId = tokenIds[address(_token)]; uint16 tokenId = 0; if (lpTokenId == 0) { // This means it is not a pair address tokenId = governance.validateTokenAddress(address(_token)); } else { lpTokenId = validatePairTokenAddress(address(_token)); } uint256 balance_before = 0; uint256 balance_after = 0; uint128 deposit_amount = 0; if (lpTokenId > 0) { // Note: For lp token, main contract always has no money balance_before = _token.balanceOf(msg.sender); pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount)); balance_after = _token.balanceOf(msg.sender); deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after)); require(deposit_amount <= maxDepositAmount, "fd011"); registerDeposit(lpTokenId, deposit_amount, _franklinAddr); } else { balance_before = _token.balanceOf(address(this)); require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012"); // token transfer failed deposit balance_after = _token.balanceOf(address(this)); deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before)); require(deposit_amount <= maxDepositAmount, "fd013"); registerDeposit(tokenId, deposit_amount, _franklinAddr); } } /// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender /// @param _token Token address /// @param _amount amount to withdraw function withdrawERC20(IERC20 _token, uint128 _amount) external nonReentrant { uint16 lpTokenId = tokenIds[address(_token)]; uint16 tokenId = 0; if (lpTokenId == 0) { // This means it is not a pair address tokenId = governance.validateTokenAddress(address(_token)); } else { tokenId = validatePairTokenAddress(address(_token)); } bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw; uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, msg.sender, _amount, balance); registerWithdrawal(tokenId, withdrawnAmount, msg.sender); } /// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to _to address /// @param _token Token address /// @param _amount amount to withdraw /// @param _to address to withdraw function withdrawERC20WithAddress(IERC20 _token, uint128 _amount, address payable _to) external nonReentrant { require(_to != address(0), "ipa12"); uint16 lpTokenId = tokenIds[address(_token)]; uint16 tokenId = 0; if (lpTokenId == 0) { // This means it is not a pair address tokenId = governance.validateTokenAddress(address(_token)); } else { tokenId = validatePairTokenAddress(address(_token)); } bytes22 packedBalanceKey = packAddressAndTokenId(_to, tokenId); uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw; uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, _to, _amount, balance); registerWithdrawal(tokenId, withdrawnAmount, _to); } /// @notice Register full exit request - pack pubdata, add priority request /// @param _accountId Numerical id of the account /// @param _token Token address, 0 address for ether function fullExit(uint32 _accountId, address _token) external nonReentrant { requireActive(); require(_accountId <= MAX_ACCOUNT_ID, "fee11"); uint16 tokenId; if (_token == address(0)) { tokenId = 0; } else { tokenId = governance.validateTokenAddress(_token); require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "fee12"); } // Priority Queue request Operations.FullExit memory op = Operations.FullExit({ accountId : _accountId, owner : msg.sender, tokenId : tokenId, amount : 0 // unknown at this point }); bytes memory pubData = Operations.writeFullExitPubdata(op); addPriorityRequest(Operations.OpType.FullExit, pubData, ""); // User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value // In this case operator should just overwrite this slot during confirming withdrawal bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId); balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff; } /// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event /// @param _tokenId Token by id /// @param _amount Token amount /// @param _owner Receiver function registerDeposit( uint16 _tokenId, uint128 _amount, address _owner ) internal { // Priority Queue request Operations.Deposit memory op = Operations.Deposit({ accountId : 0, // unknown at this point owner : _owner, tokenId : _tokenId, amount : _amount }); bytes memory pubData = Operations.writeDepositPubdata(op); addPriorityRequest(Operations.OpType.Deposit, pubData, ""); emit OnchainDeposit( msg.sender, _tokenId, _amount, _owner ); } /// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event /// @param _token - token by id /// @param _amount - token amount /// @param _to - address to withdraw to function registerWithdrawal(uint16 _token, uint128 _amount, address payable _to) internal { bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token); uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw; balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(_amount); emit OnchainWithdrawal( _to, _token, _amount ); } /// @notice Checks that current state not is exodus mode function requireActive() internal view { require(!exodusMode, "fre11"); // exodus mode activated } // Priority queue /// @notice Saves priority request in storage /// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event /// @param _opType Rollup operation type /// @param _pubData Operation pubdata function addPriorityRequest( Operations.OpType _opType, bytes memory _pubData, bytes memory _userData ) internal { // Expiration block is: current block number + priority expiration delta uint256 expirationBlock = block.number + PRIORITY_EXPIRATION; uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests; priorityRequests[nextPriorityRequestId] = PriorityOperation({ opType : _opType, pubData : _pubData, expirationBlock : expirationBlock }); emit NewPriorityRequest( msg.sender, nextPriorityRequestId, _opType, _pubData, _userData, expirationBlock ); totalOpenPriorityRequests++; } // The contract is too large. Break some functions to zkSyncCommitBlockAddress function() external payable { address nextAddress = zkSyncCommitBlockAddress; require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set"); // Execute external function from facet using delegatecall and return any value. assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { /// Address of lock flag variable. /// Flag is placed at random memory location to not interfere with Storage contract. uint constant private LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1; function initializeReentrancyGuard () 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. assembly { sstore(LOCK_FLAG_ADDRESS, 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() { bool notEntered; assembly { notEntered := sload(LOCK_FLAG_ADDRESS) } // On the first call to nonReentrant, _notEntered will be true require(notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail assembly { sstore(LOCK_FLAG_ADDRESS, 0) } _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) assembly { sstore(LOCK_FLAG_ADDRESS, 1) } } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; /** * @dev 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 SafeMathUInt128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. * * _Available since v2.5.0._ */ 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); } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./Bytes.sol"; library Utils { /// @notice Returns lesser of two values function minU32(uint32 a, uint32 b) internal pure returns (uint32) { return a < b ? a : b; } /// @notice Returns lesser of two values function minU64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } /// @notice Sends tokens /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transfer` to this token may return (bool) or nothing /// @param _token Token address /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendERC20(IERC20 _token, address _to, uint256 _amount) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call( abi.encodeWithSignature("transfer(address,uint256)", _to, _amount) ); // `transfer` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Transfers token from one address to another /// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard /// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing /// @param _token Token address /// @param _from Address of sender /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function transferFromERC20(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { (bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call( abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount) ); // `transferFrom` method may return (bool) or nothing. bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool)); return callSuccess && returnedSuccess; } /// @notice Sends ETH /// @param _to Address of recipient /// @param _amount Amount of tokens to transfer /// @return bool flag indicating that transfer is successful function sendETHNoRevert(address payable _to, uint256 _amount) internal returns (bool) { // TODO: Use constant from Config uint256 ETH_WITHDRAWAL_GAS_LIMIT = 10000; (bool callSuccess, ) = _to.call.gas(ETH_WITHDRAWAL_GAS_LIMIT).value(_amount)(""); return callSuccess; } /// @notice Recovers signer's address from ethereum signature for given message /// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1) /// @param _message signed message. /// @return address of the signer function recoverAddressFromEthSignature(bytes memory _signature, bytes memory _message) internal pure returns (address) { require(_signature.length == 65, "ves10"); // incorrect signature length bytes32 signR; bytes32 signS; uint offset = 0; (offset, signR) = Bytes.readBytes32(_signature, offset); (offset, signS) = Bytes.readBytes32(_signature, offset); uint8 signV = uint8(_signature[offset]); return ecrecover(keccak256(_message), signV, signR, signS); } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./Governance.sol"; import "./Verifier.sol"; import "./VerifierExit.sol"; import "./Operations.sol"; import "./uniswap/UniswapV2Factory.sol"; /// @title ZKSwap storage contract /// @author Matter Labs /// @author ZKSwap L2 Labs contract Storage { /// @notice Flag indicates that upgrade preparation status is active /// @dev Will store false in case of not active upgrade mode bool public upgradePreparationActive; /// @notice Upgrade preparation activation timestamp (as seconds since unix epoch) /// @dev Will be equal to zero in case of not active upgrade mode uint public upgradePreparationActivationTime; /// @notice Verifier contract. Used to verify block proof and exit proof Verifier internal verifier; VerifierExit internal verifierExit; /// @notice Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list Governance internal governance; UniswapV2Factory internal pairmanager; struct BalanceToWithdraw { uint128 balanceToWithdraw; uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value } /// @notice Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw mapping(bytes22 => BalanceToWithdraw) public balancesToWithdraw; /// @notice verified withdrawal pending to be executed. struct PendingWithdrawal { address to; uint16 tokenId; } /// @notice Verified but not executed withdrawals for addresses stored in here (key is pendingWithdrawal's index in pending withdrawals queue) mapping(uint32 => PendingWithdrawal) public pendingWithdrawals; uint32 public firstPendingWithdrawalIndex; uint32 public numberOfPendingWithdrawals; /// @notice Total number of verified blocks i.e. blocks[totalBlocksVerified] points at the latest verified block (block 0 is genesis) uint32 public totalBlocksVerified; /// @notice Total number of checked blocks uint32 public totalBlocksChecked; /// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block uint32 public totalBlocksCommitted; /// @notice Rollup block data (once per block) /// @member validator Block producer /// @member committedAtBlock ETH block number at which this block was committed /// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks /// @member priorityOperations Total number of priority operations for this block /// @member commitment Hash of the block circuit commitment /// @member stateRoot New tree root hash /// /// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html struct Block { uint32 committedAtBlock; uint64 priorityOperations; uint32 chunks; bytes32 withdrawalsDataHash; /// can be restricted to 16 bytes to reduce number of required storage slots bytes32 commitment; bytes32 stateRoot; } /// @notice Blocks by Franklin block id mapping(uint32 => Block) public blocks; /// @notice Onchain operations - operations processed inside rollup blocks /// @member opType Onchain operation type /// @member amount Amount used in the operation /// @member pubData Operation pubdata struct OnchainOperation { Operations.OpType opType; bytes pubData; } /// @notice Flag indicates that a user has exited certain token balance (per account id and tokenId) mapping(uint32 => mapping(uint16 => bool)) public exited; mapping(uint32 => mapping(uint32 => bool)) public swap_exited; /// @notice Flag indicates that exodus (mass exit) mode is triggered /// @notice Once it was raised, it can not be cleared again, and all users must exit bool public exodusMode; /// @notice User authenticated fact hashes for some nonce. mapping(address => mapping(uint32 => bytes32)) public authFacts; /// @notice Priority Operation container /// @member opType Priority operation type /// @member pubData Priority operation public data /// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before) struct PriorityOperation { Operations.OpType opType; bytes pubData; uint256 expirationBlock; } /// @notice Priority Requests mapping (request id - operation) /// @dev Contains op type, pubdata and expiration block of unsatisfied requests. /// @dev Numbers are in order of requests receiving mapping(uint64 => PriorityOperation) public priorityRequests; /// @notice First open priority request id uint64 public firstPriorityRequestId; /// @notice Total number of requests uint64 public totalOpenPriorityRequests; /// @notice Total number of committed requests. /// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big uint64 public totalCommittedPriorityRequests; /// @notice Packs address and token id into single word to use as a key in balances mapping function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) { return bytes22((uint176(_address) | (uint176(_tokenId) << 160))); } /// @notice Gets value from balancesToWithdraw function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) { return balancesToWithdraw[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw; } address public zkSyncCommitBlockAddress; address public zkSyncExitAddress; /// @notice Limit the max amount for each ERC20 deposit uint128 public maxDepositAmount; /// @notice withdraw erc20 token gas limit uint256 public withdrawGasLimit; } pragma solidity ^0.5.0; /// @title ZKSwap configuration constants /// @author Matter Labs /// @author ZKSwap L2 Labs contract Config { /// @notice ERC20 token withdrawal gas limit, used only for complete withdrawals uint256 constant ERC20_WITHDRAWAL_GAS_LIMIT = 350000; /// @notice ETH token withdrawal gas limit, used only for complete withdrawals uint256 constant ETH_WITHDRAWAL_GAS_LIMIT = 10000; /// @notice Bytes in one chunk uint8 constant CHUNK_BYTES = 11; /// @notice ZKSwap address length uint8 constant ADDRESS_BYTES = 20; uint8 constant PUBKEY_HASH_BYTES = 20; /// @notice Public key bytes length uint8 constant PUBKEY_BYTES = 32; /// @notice Ethereum signature r/s bytes length uint8 constant ETH_SIGN_RS_BYTES = 32; /// @notice Success flag bytes length uint8 constant SUCCESS_FLAG_BYTES = 1; /// @notice Max amount of fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 constant MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS = 32 - 1; /// @notice start ID for user tokens uint16 constant USER_TOKENS_START_ID = 32; /// @notice Max amount of user tokens registered in the network uint16 constant MAX_AMOUNT_OF_REGISTERED_USER_TOKENS = 16352; /// @notice Max amount of tokens registered in the network uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 16384 - 1; /// @notice Max account id that could be registered in the network uint32 constant MAX_ACCOUNT_ID = (2 ** 28) - 1; /// @notice Expected average period of block creation uint256 constant BLOCK_PERIOD = 15 seconds; /// @notice ETH blocks verification expectation /// Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN. /// If set to 0 validator can revert blocks at any time. uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD; uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES; uint256 constant CREATE_PAIR_BYTES = 3 * CHUNK_BYTES; uint256 constant DEPOSIT_BYTES = 4 * CHUNK_BYTES; uint256 constant TRANSFER_TO_NEW_BYTES = 4 * CHUNK_BYTES; uint256 constant PARTIAL_EXIT_BYTES = 5 * CHUNK_BYTES; uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES; uint256 constant UNISWAP_ADD_LIQ_BYTES = 3 * CHUNK_BYTES; uint256 constant UNISWAP_RM_LIQ_BYTES = 3 * CHUNK_BYTES; uint256 constant UNISWAP_SWAP_BYTES = 2 * CHUNK_BYTES; /// @notice Full exit operation length uint256 constant FULL_EXIT_BYTES = 4 * CHUNK_BYTES; /// @notice OnchainWithdrawal data length uint256 constant ONCHAIN_WITHDRAWAL_BYTES = 1 + 20 + 2 + 16; // (uint8 addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount) /// @notice ChangePubKey operation length uint256 constant CHANGE_PUBKEY_BYTES = 5 * CHUNK_BYTES; /// @notice Expiration delta for priority request to be satisfied (in seconds) /// NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD), otherwise incorrect block with priority op could not be reverted. uint256 constant PRIORITY_EXPIRATION_PERIOD = 3 days; /// @notice Expiration delta for priority request to be satisfied (in ETH blocks) uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD; /// @notice Maximum number of priority request to clear during verifying the block /// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots /// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6; /// @notice Reserved time for users to send full exit priority operation in case of an upgrade (in seconds) uint constant MASS_FULL_EXIT_PERIOD = 3 days; /// @notice Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds) uint constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days; /// @notice Notice period before activation preparation status of upgrade mode (in seconds) // NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it. uint constant UPGRADE_NOTICE_PERIOD = MASS_FULL_EXIT_PERIOD + PRIORITY_EXPIRATION_PERIOD + TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT; // @notice Default amount limit for each ERC20 deposit uint128 constant DEFAULT_MAX_DEPOSIT_AMOUNT = 2 ** 85; } pragma solidity ^0.5.0; import "./Upgradeable.sol"; import "./Operations.sol"; /// @title ZKSwap events /// @author Matter Labs /// @author ZKSwap L2 Labs interface Events { /// @notice Event emitted when a block is committed event BlockCommit(uint32 indexed blockNumber); /// @notice Event emitted when a block is verified event BlockVerification(uint32 indexed blockNumber); /// @notice Event emitted when a sequence of blocks is verified event MultiblockVerification(uint32 indexed blockNumberFrom, uint32 indexed blockNumberTo); /// @notice Event emitted when user send a transaction to withdraw her funds from onchain balance event OnchainWithdrawal( address indexed owner, uint16 indexed tokenId, uint128 amount ); /// @notice Event emitted when user send a transaction to deposit her funds event OnchainDeposit( address indexed sender, uint16 indexed tokenId, uint128 amount, address indexed owner ); event OnchainCreatePair( uint16 indexed tokenAId, uint16 indexed tokenBId, uint16 indexed pairId, address pair ); /// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash) event FactAuth( address indexed sender, uint32 nonce, bytes fact ); /// @notice Event emitted when blocks are reverted event BlocksRevert( uint32 indexed totalBlocksVerified, uint32 indexed totalBlocksCommitted ); /// @notice Exodus mode entered event event ExodusMode(); /// @notice New priority request event. Emitted when a request is placed into mapping event NewPriorityRequest( address sender, uint64 serialId, Operations.OpType opType, bytes pubData, bytes userData, uint256 expirationBlock ); /// @notice Deposit committed event. event DepositCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Full exit committed event. event FullExitCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, address owner, uint16 indexed tokenId, uint128 amount ); /// @notice Pending withdrawals index range that were added in the verifyBlock operation. /// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex) event PendingWithdrawalsAdd( uint32 queueStartIndex, uint32 queueEndIndex ); /// @notice Pending withdrawals index range that were executed in the completeWithdrawals operation. /// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex) event PendingWithdrawalsComplete( uint32 queueStartIndex, uint32 queueEndIndex ); event CreatePairCommit( uint32 indexed zkSyncBlockId, uint32 indexed accountId, uint16 tokenAId, uint16 tokenBId, uint16 indexed tokenPairId, address pair ); } /// @title Upgrade events /// @author Matter Labs interface UpgradeEvents { /// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts event NewUpgradable( uint indexed versionId, address indexed upgradeable ); /// @notice Upgrade mode enter event event NoticePeriodStart( uint indexed versionId, address[] newTargets, uint noticePeriod // notice period (in seconds) ); /// @notice Upgrade mode cancel event event UpgradeCancel( uint indexed versionId ); /// @notice Upgrade mode preparation status event event PreparationStart( uint indexed versionId ); /// @notice Upgrade mode complete event event UpgradeComplete( uint indexed versionId, address[] newTargets ); } pragma solidity ^0.5.0; // Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word) // implements the following algorithm: // f(bytes memory input, uint offset) -> X out // where byte representation of out is N bytes from input at the given offset // 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N] // W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N // 2) We load W from memory into out, last N bytes of W are placed into out library Bytes { function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 2); } function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 3); } function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 4); } function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) { return toBytesFromUIntTruncated(uint(self), 16); } // Copies 'len' lower bytes from 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'. function toBytesFromUIntTruncated(uint self, uint8 byteLength) private pure returns (bytes memory bts) { require(byteLength <= 32, "bt211"); bts = new bytes(byteLength); // Even though the bytes will allocate a full word, we don't want // any potential garbage bytes in there. uint data = self << ((32 - byteLength) * 8); assembly { mstore(add(bts, /*BYTES_HEADER_SIZE*/32), data) } } // Copies 'self' into a new 'bytes memory'. // Returns the newly created 'bytes memory'. The returned bytes will be of length '20'. function toBytesFromAddress(address self) internal pure returns (bytes memory bts) { bts = toBytesFromUIntTruncated(uint(self), 20); } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 20) function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) { uint256 offset = _start + 20; require(self.length >= offset, "bta11"); assembly { addr := mload(add(self, offset)) } } // Reasoning about why this function works is similar to that of other similar functions, except NOTE below. // NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types // NOTE: theoretically possible overflow of (_start + 20) function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) { require(self.length >= (_start + 20), "btb20"); assembly { r := mload(add(add(self, 0x20), _start)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x2) function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) { uint256 offset = _start + 0x2; require(_bytes.length >= offset, "btu02"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x3) function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) { uint256 offset = _start + 0x3; require(_bytes.length >= offset, "btu03"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x4) function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) { uint256 offset = _start + 0x4; require(_bytes.length >= offset, "btu04"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x10) function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) { uint256 offset = _start + 0x10; require(_bytes.length >= offset, "btu16"); assembly { r := mload(add(_bytes, offset)) } } // See comment at the top of this file for explanation of how this function works. // NOTE: theoretically possible overflow of (_start + 0x14) function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) { uint256 offset = _start + 0x14; require(_bytes.length >= offset, "btu20"); assembly { r := mload(add(_bytes, offset)) } } // NOTE: theoretically possible overflow of (_start + 0x20) function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) { uint256 offset = _start + 0x20; require(_bytes.length >= offset, "btb32"); assembly { r := mload(add(_bytes, offset)) } } // Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228 // Get slice from bytes arrays // Returns the newly created 'bytes memory' // NOTE: theoretically possible overflow of (_start + _length) function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "bse11"); // bytes length is less then start byte + length bytes bytes memory tempBytes = new bytes(_length); if (_length != 0) { // TODO: Review this thoroughly. assembly { let slice_curr := add(tempBytes, 0x20) let slice_end := add(slice_curr, _length) for { let array_current := add(_bytes, add(_start, 0x20)) } lt(slice_curr, slice_end) { slice_curr := add(slice_curr, 0x20) array_current := add(array_current, 0x20) } { mstore(slice_curr, mload(array_current)) } } } return tempBytes; } /// Reads byte stream /// @return new_offset - offset + amount of bytes read /// @return data - actually read data // NOTE: theoretically possible overflow of (_offset + _length) function read(bytes memory _data, uint _offset, uint _length) internal pure returns (uint new_offset, bytes memory data) { data = slice(_data, _offset, _length); new_offset = _offset + _length; } // NOTE: theoretically possible overflow of (_offset + 1) function readBool(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bool r) { new_offset = _offset + 1; r = uint8(_data[_offset]) != 0; } // NOTE: theoretically possible overflow of (_offset + 1) function readUint8(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint8 r) { new_offset = _offset + 1; r = uint8(_data[_offset]); } // NOTE: theoretically possible overflow of (_offset + 2) function readUInt16(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint16 r) { new_offset = _offset + 2; r = bytesToUInt16(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 3) function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) { new_offset = _offset + 3; r = bytesToUInt24(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 4) function readUInt32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint32 r) { new_offset = _offset + 4; r = bytesToUInt32(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 16) function readUInt128(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint128 r) { new_offset = _offset + 16; r = bytesToUInt128(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readUInt160(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint160 r) { new_offset = _offset + 20; r = bytesToUInt160(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readAddress(bytes memory _data, uint _offset) internal pure returns (uint new_offset, address r) { new_offset = _offset + 20; r = bytesToAddress(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 20) function readBytes20(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes20 r) { new_offset = _offset + 20; r = bytesToBytes20(_data, _offset); } // NOTE: theoretically possible overflow of (_offset + 32) function readBytes32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes32 r) { new_offset = _offset + 32; r = bytesToBytes32(_data, _offset); } // Helper function for hex conversion. function halfByteToHex(byte _byte) internal pure returns (byte _hexByte) { require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range. // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. return byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byte) * 8))); } // Convert bytes to ASCII hex representation function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) { bytes memory outStringBytes = new bytes(_input.length * 2); // code in `assembly` construction is equivalent of the next code: // for (uint i = 0; i < _input.length; ++i) { // outStringBytes[i*2] = halfByteToHex(_input[i] >> 4); // outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f); // } assembly { let input_curr := add(_input, 0x20) let input_end := add(input_curr, mload(_input)) for { let out_curr := add(outStringBytes, 0x20) } lt(input_curr, input_end) { input_curr := add(input_curr, 0x01) out_curr := add(out_curr, 0x02) } { let curr_input_byte := shr(0xf8, mload(input_curr)) // here outStringByte from each half of input byte calculates by the next: // // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. // outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8))) mstore(out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))) mstore(add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))) } } return outStringBytes; } /// Trim bytes into single word function trim(bytes memory _data, uint _new_length) internal pure returns (uint r) { require(_new_length <= 0x20, "trm10"); // new_length is longer than word require(_data.length >= _new_length, "trm11"); // data is to short uint a; assembly { a := mload(add(_data, 0x20)) // load bytes into uint256 } return a >> ((0x20 - _new_length) * 8); } } pragma solidity ^0.5.0; import "./Bytes.sol"; /// @title ZKSwap operations tools library Operations { // Circuit ops and their pubdata (chunks * bytes) /// @notice ZKSwap circuit operation type enum OpType { Noop, Deposit, TransferToNew, PartialExit, _CloseAccount, // used for correct op id offset Transfer, FullExit, ChangePubKey, CreatePair, AddLiquidity, RemoveLiquidity, Swap } // Byte lengths uint8 constant TOKEN_BYTES = 2; uint8 constant PUBKEY_BYTES = 32; uint8 constant NONCE_BYTES = 4; uint8 constant PUBKEY_HASH_BYTES = 20; uint8 constant ADDRESS_BYTES = 20; /// @notice Packed fee bytes lengths uint8 constant FEE_BYTES = 2; /// @notice ZKSwap account id bytes lengths uint8 constant ACCOUNT_ID_BYTES = 4; uint8 constant AMOUNT_BYTES = 16; /// @notice Signature (for example full exit signature) bytes length uint8 constant SIGNATURE_BYTES = 64; // Deposit pubdata struct Deposit { uint32 accountId; uint16 tokenId; uint128 amount; address owner; } uint public constant PACKED_DEPOSIT_PUBDATA_BYTES = ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES; /// Deserialize deposit pubdata function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "rdp10"); // reading invalid deposit pubdata size } /// Serialize deposit pubdata function writeDepositPubdata(Deposit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenId, // tokenId op.amount, // amount op.owner // owner ); } /// @notice Check that deposit pubdata from request and block matches function depositPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // We must ignore `accountId` because it is present in block pubdata but not in priority queue bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES); bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES); return keccak256(lhs_trimmed) == keccak256(rhs_trimmed); } // FullExit pubdata struct FullExit { uint32 accountId; address owner; uint16 tokenId; uint128 amount; } uint public constant PACKED_FULL_EXIT_PUBDATA_BYTES = ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES; function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "rfp10"); // reading invalid full exit pubdata size } function writeFullExitPubdata(FullExit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( op.accountId, // accountId op.owner, // owner op.tokenId, // tokenId op.amount // amount ); } /// @notice Check that full exit pubdata from request and block matches function fullExitPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // `amount` is ignored because it is present in block pubdata but not in priority queue uint lhs = Bytes.trim(_lhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES); uint rhs = Bytes.trim(_rhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES); return lhs == rhs; } // PartialExit pubdata struct PartialExit { //uint32 accountId; -- present in pubdata, ignored at serialization uint16 tokenId; uint128 amount; //uint16 fee; -- present in pubdata, ignored at serialization address owner; } function readPartialExitPubdata(bytes memory _data, uint _offset) internal pure returns (PartialExit memory parsed) { // NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible. uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored) (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId (offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount } function writePartialExitPubdata(PartialExit memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.owner, // owner op.tokenId, // tokenId op.amount // amount ); } // ChangePubKey struct ChangePubKey { uint32 accountId; bytes20 pubKeyHash; address owner; uint32 nonce; } function readChangePubKeyPubdata(bytes memory _data, uint _offset) internal pure returns (ChangePubKey memory parsed) { uint offset = _offset; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash (offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner (offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce } // Withdrawal data process function readWithdrawalData(bytes memory _data, uint _offset) internal pure returns (bool _addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount) { uint offset = _offset; (offset, _addToPendingWithdrawalsQueue) = Bytes.readBool(_data, offset); (offset, _to) = Bytes.readAddress(_data, offset); (offset, _tokenId) = Bytes.readUInt16(_data, offset); (offset, _amount) = Bytes.readUInt128(_data, offset); } // CreatePair pubdata struct CreatePair { uint32 accountId; uint16 tokenA; uint16 tokenB; uint16 tokenPair; address pair; } uint public constant PACKED_CREATE_PAIR_PUBDATA_BYTES = ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES; function readCreatePairPubdata(bytes memory _data) internal pure returns (CreatePair memory parsed) { uint offset = 0; (offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId (offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId (offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId (offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId (offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size } function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) { buf = abi.encodePacked( bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed) op.tokenA, // tokenAId op.tokenB, // tokenBId op.tokenPair, // pairId op.pair // pair account ); } /// @notice Check that create pair pubdata from request and block matches function createPairPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) { // We must ignore `accountId` because it is present in block pubdata but not in priority queue bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES); bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES); return keccak256(lhs_trimmed) == keccak256(rhs_trimmed); } } pragma solidity ^0.5.0; /// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it) /// @author Matter Labs /// @author ZKSwap L2 Labs interface UpgradeableMaster { /// @notice Notice period before activation preparation status of upgrade mode function getNoticePeriod() external returns (uint); /// @notice Notifies contract that notice period started function upgradeNoticePeriodStarted() external; /// @notice Notifies contract that upgrade preparation status is activated function upgradePreparationStarted() external; /// @notice Notifies contract that upgrade canceled function upgradeCanceled() external; /// @notice Notifies contract that upgrade finishes function upgradeFinishes() external; /// @notice Checks that contract is ready for upgrade /// @return bool flag indicating that contract is ready for upgrade function isReadyForUpgrade() external returns (bool); } pragma solidity =0.5.16; import './interfaces/IUniswapV2Factory.sol'; import './UniswapV2Pair.sol'; contract UniswapV2Factory is IUniswapV2Factory { mapping(address => mapping(address => address)) public getPair; address[] public allPairs; address public zkSyncAddress; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor() public { } function initialize(bytes calldata data) external { } function setZkSyncAddress(address _zksyncAddress) external { require(zkSyncAddress == address(0), "szsa1"); zkSyncAddress = _zksyncAddress; } /// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} function allPairsLength() external view returns (uint) { return allPairs.length; } function createPair(address tokenA, address tokenB) external returns (address pair) { require(msg.sender == zkSyncAddress, 'fcp1'); require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); //require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } require(zkSyncAddress != address(0), 'wzk'); IUniswapV2Pair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function mint(address pair, address to, uint amount) external { require(msg.sender == zkSyncAddress, 'fmt1'); IUniswapV2Pair(pair).mint(to, amount); } function burn(address pair, address to, uint amount) external { require(msg.sender == zkSyncAddress, 'fbr1'); IUniswapV2Pair(pair).burn(to, amount); } } pragma solidity ^0.5.0; contract PairTokenManager { /// @notice Max amount of pair tokens registered in the network. uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 49152; uint16 constant PAIR_TOKEN_START_ID = 16384; /// @notice Total number of pair tokens registered in the network uint16 public totalPairTokens; /// @notice List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @notice List of registered tokens by address mapping(address => uint16) public tokenIds; /// @notice Token added to Franklin net event NewToken( address indexed token, uint16 indexed tokenId ); function addPairToken(address _token) internal { require(tokenIds[_token] == 0, "pan1"); // token exists require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens; totalPairTokens++; tokenAddresses[newPairTokenId] = _token; tokenIds[_token] = newPairTokenId; emit NewToken(_token, newPairTokenId); } /// @notice Validate pair token address /// @param _tokenAddr Token address /// @return tokens id function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "pms3"); require(tokenId <= (PAIR_TOKEN_START_ID -1 + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4"); return tokenId; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./Config.sol"; /// @title Governance Contract /// @author Matter Labs /// @author ZKSwap L2 Labs contract Governance is Config { /// @notice Token added to Franklin net event NewToken( address indexed token, uint16 indexed tokenId ); /// @notice Governor changed event NewGovernor( address newGovernor ); /// @notice tokenLister changed event NewTokenLister( address newTokenLister ); /// @notice Validator's status changed event ValidatorStatusUpdate( address indexed validatorAddress, bool isActive ); /// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades address public networkGovernor; /// @notice Total number of ERC20 fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0) uint16 public totalFeeTokens; /// @notice Total number of ERC20 user tokens registered in the network uint16 public totalUserTokens; /// @notice List of registered tokens by tokenId mapping(uint16 => address) public tokenAddresses; /// @notice List of registered tokens by address mapping(address => uint16) public tokenIds; /// @notice List of permitted validators mapping(address => bool) public validators; address public tokenLister; constructor() public { networkGovernor = msg.sender; } /// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function. /// @param initializationParameters Encoded representation of initialization parameters: /// _networkGovernor The address of network governor function initialize(bytes calldata initializationParameters) external { require(networkGovernor == address(0), "init0"); (address _networkGovernor, address _tokenLister) = abi.decode(initializationParameters, (address, address)); networkGovernor = _networkGovernor; tokenLister = _tokenLister; } /// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} /// @notice Change current governor /// @param _newGovernor Address of the new governor function changeGovernor(address _newGovernor) external { requireGovernor(msg.sender); require(_newGovernor != address(0), "zero address is passed as _newGovernor"); if (networkGovernor != _newGovernor) { networkGovernor = _newGovernor; emit NewGovernor(_newGovernor); } } /// @notice Change current governor /// @param _newTokenLister Address of the new governor function changeTokenLister(address _newTokenLister) external { requireGovernor(msg.sender); require(_newTokenLister != address(0), "zero address is passed as _newTokenLister"); if (tokenLister != _newTokenLister) { tokenLister = _newTokenLister; emit NewTokenLister(_newTokenLister); } } /// @notice Add fee token to the list of networks tokens /// @param _token Token address function addFeeToken(address _token) external { requireGovernor(msg.sender); require(tokenIds[_token] == 0, "gan11"); // token exists require(totalFeeTokens < MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "fee12"); // no free identifiers for tokens require( _token != address(0), "address cannot be zero" ); totalFeeTokens++; uint16 newTokenId = totalFeeTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth tokenAddresses[newTokenId] = _token; tokenIds[_token] = newTokenId; emit NewToken(_token, newTokenId); } /// @notice Add token to the list of networks tokens /// @param _token Token address function addToken(address _token) external { requireTokenLister(msg.sender); require(tokenIds[_token] == 0, "gan11"); // token exists require(totalUserTokens < MAX_AMOUNT_OF_REGISTERED_USER_TOKENS, "gan12"); // no free identifiers for tokens require( _token != address(0), "address cannot be zero" ); uint16 newTokenId = USER_TOKENS_START_ID + totalUserTokens; totalUserTokens++; tokenAddresses[newTokenId] = _token; tokenIds[_token] = newTokenId; emit NewToken(_token, newTokenId); } /// @notice Change validator status (active or not active) /// @param _validator Validator address /// @param _active Active flag function setValidator(address _validator, bool _active) external { requireGovernor(msg.sender); if (validators[_validator] != _active) { validators[_validator] = _active; emit ValidatorStatusUpdate(_validator, _active); } } /// @notice Check if specified address is is governor /// @param _address Address to check function requireGovernor(address _address) public view { require(_address == networkGovernor, "grr11"); // only by governor } /// @notice Check if specified address can list token /// @param _address Address to check function requireTokenLister(address _address) public view { require(_address == networkGovernor || _address == tokenLister, "grr11"); // token lister or governor } /// @notice Checks if validator is active /// @param _address Validator address function requireActiveValidator(address _address) external view { require(validators[_address], "grr21"); // validator is not active } /// @notice Validate token id (must be less than or equal to total tokens amount) /// @param _tokenId Token id /// @return bool flag that indicates if token id is less than or equal to total tokens amount function isValidTokenId(uint16 _tokenId) external view returns (bool) { return (_tokenId <= totalFeeTokens) || (_tokenId >= USER_TOKENS_START_ID && _tokenId < (USER_TOKENS_START_ID + totalUserTokens )); } /// @notice Validate token address /// @param _tokenAddr Token address /// @return tokens id function validateTokenAddress(address _tokenAddr) external view returns (uint16) { uint16 tokenId = tokenIds[_tokenAddr]; require(tokenId != 0, "gvs11"); // 0 is not a valid token require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "gvs12"); return tokenId; } function getTokenAddress(uint16 _tokenId) external view returns (address) { address tokenAddr = tokenAddresses[_tokenId]; return tokenAddr; } } pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./KeysWithPlonkAggVerifier.sol"; // Hardcoded constants to avoid accessing store contract Verifier is KeysWithPlonkAggVerifier { bool constant DUMMY_VERIFIER = false; function initialize(bytes calldata) external { } /// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} function isBlockSizeSupported(uint32 _size) public pure returns (bool) { if (DUMMY_VERIFIER) { return true; } else { return isBlockSizeSupportedInternal(_size); } } function verifyMultiblockProof( uint256[] calldata _recursiveInput, uint256[] calldata _proof, uint32[] calldata _block_sizes, uint256[] calldata _individual_vks_inputs, uint256[] calldata _subproofs_limbs ) external view returns (bool) { if (DUMMY_VERIFIER) { uint oldGasValue = gasleft(); uint tmp; while (gasleft() + 500000 > oldGasValue) { tmp += 1; } return true; } uint8[] memory vkIndexes = new uint8[](_block_sizes.length); for (uint32 i = 0; i < _block_sizes.length; i++) { vkIndexes[i] = blockSizeToVkIndex(_block_sizes[i]); } VerificationKey memory vk = getVkAggregated(uint32(_block_sizes.length)); return verify_serialized_proof_with_recursion(_recursiveInput, _proof, VK_TREE_ROOT, VK_MAX_INDEX, vkIndexes, _individual_vks_inputs, _subproofs_limbs, vk); } } pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./KeysWithPlonkSingleVerifier.sol"; // Hardcoded constants to avoid accessing store contract VerifierExit is KeysWithPlonkSingleVerifier { function initialize(bytes calldata) external { } /// @notice VerifierExit contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function. /// @param upgradeParameters Encoded representation of upgrade parameters function upgrade(bytes calldata upgradeParameters) external {} function verifyExitProof( bytes32 _rootHash, uint32 _accountId, address _owner, uint16 _tokenId, uint128 _amount, uint256[] calldata _proof ) external view returns (bool) { bytes32 commitment = sha256(abi.encodePacked(_rootHash, _accountId, _owner, _tokenId, _amount)); uint256[] memory inputs = new uint256[](1); uint256 mask = (~uint256(0)) >> 3; inputs[0] = uint256(commitment) & mask; Proof memory proof = deserialize_proof(inputs, _proof); VerificationKey memory vk = getVkExit(); require(vk.num_inputs == inputs.length); return verify(proof, vk); } function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) { bytes memory merged = new bytes(param1.length + param2.length); uint k = 0; for (uint i = 0; i < param1.length; i++) { merged[k] = param1[i]; k++; } for (uint i = 0; i < param2.length; i++) { merged[k] = param2[i]; k++; } return merged; } function verifyLpExitProof( bytes calldata _account_data, bytes calldata _pair_data0, bytes calldata _pair_data1, uint256[] calldata _proof ) external view returns (bool) { bytes memory _data1 = concatBytes(_account_data, _pair_data0); bytes memory _data2 = concatBytes(_data1, _pair_data1); bytes32 commitment = sha256(_data2); uint256[] memory inputs = new uint256[](1); uint256 mask = (~uint256(0)) >> 3; inputs[0] = uint256(commitment) & mask; Proof memory proof = deserialize_proof(inputs, _proof); VerificationKey memory vk = getVkLpExit(); require(vk.num_inputs == inputs.length); return verify(proof, vk); } } pragma solidity ^0.5.0; /// @title Interface of the upgradeable contract /// @author Matter Labs /// @author ZKSwap L2 Labs interface Upgradeable { /// @notice Upgrades target of upgradeable contract /// @param newTarget New target /// @param newTargetInitializationParameters New target initialization parameters function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external; } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); } pragma solidity =0.5.16; import './interfaces/IUniswapV2Pair.sol'; import './UniswapV2ERC20.sol'; import './libraries/Math.sol'; import './libraries/UQ112x112.sol'; import './interfaces/IUNISWAPERC20.sol'; import './interfaces/IUniswapV2Factory.sol'; import './interfaces/IUniswapV2Callee.sol'; contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 { using UniswapSafeMath for uint; using UQ112x112 for uint224; address public factory; address public token0; address public token1; uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } function mint(address to, uint amount) external lock { require(msg.sender == factory, 'mt1'); _mint(to, amount); } function burn(address to, uint amount) external lock { require(msg.sender == factory, 'br1'); _burn(to, amount); } } pragma solidity >=0.5.0 <0.7.0; pragma experimental ABIEncoderV2; import "./PlonkAggCore.sol"; // Hardcoded constants to avoid accessing store contract KeysWithPlonkAggVerifier is AggVerifierWithDeserialize { uint256 constant VK_TREE_ROOT = 0x0a3cdc9655e61bf64758c1e8df745723e9b83addd4f0d0f2dd65dc762dc1e9e7; uint8 constant VK_MAX_INDEX = 5; function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) { if (_size == uint32(6)) { return true; } else if (_size == uint32(12)) { return true; } else if (_size == uint32(48)) { return true; } else if (_size == uint32(96)) { return true; } else if (_size == uint32(204)) { return true; } else if (_size == uint32(420)) { return true; } else { return false; } } function blockSizeToVkIndex(uint32 _chunks) internal pure returns (uint8) { if (_chunks == uint32(6)) { return 0; } else if (_chunks == uint32(12)) { return 1; } else if (_chunks == uint32(48)) { return 2; } else if (_chunks == uint32(96)) { return 3; } else if (_chunks == uint32(204)) { return 4; } else if (_chunks == uint32(420)) { return 5; } } function getVkAggregated(uint32 _blocks) internal pure returns (VerificationKey memory vk) { if (_blocks == uint32(1)) { return getVkAggregated1(); } else if (_blocks == uint32(5)) { return getVkAggregated5(); } } function getVkAggregated1() internal pure returns(VerificationKey memory vk) { vk.domain_size = 4194304; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b, 0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48 ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e, 0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0 ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5, 0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123 ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7, 0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346 ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263, 0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474, 0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927, 0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c, 0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951, 0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3, 0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6, 0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899, 0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1, 0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59 ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkAggregated5() internal pure returns(VerificationKey memory vk) { vk.domain_size = 16777216; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb); vk.gate_setup_commitments[0] = PairingsBn254.new_g1( 0x023cfc69ef1b002da66120fce352ede75893edd8cd8196403a54e1eceb82cd43, 0x2baf3bd673e46be9df0d43ca30f834671543c22db422f450b2efd8c931e9b34e ); vk.gate_setup_commitments[1] = PairingsBn254.new_g1( 0x23783fe0e5c3f83c02c864e25fe766afb727134c9a77ae6b9694efb7b46f31ab, 0x1903d01005e447d061c16323a1d604d8fbd4b5cc9b64945a71f1234d280c4d3a ); vk.gate_setup_commitments[2] = PairingsBn254.new_g1( 0x2897df6c6fa993661b2b0b0cf52460278e33533de71b3c0f7ed7c1f20af238c6, 0x042344afee0aed5505e59bce4ebbe942a91268a8af6b77ea95f603b5b726e8cb ); vk.gate_setup_commitments[3] = PairingsBn254.new_g1( 0x0fceed33e78426afc38d8a68c0d93413d2bbaa492b087125271d33d52bdb07b8, 0x0057e4f63be36edb56e91da931f3d0ba72d1862d4b7751c59b92b6ae9f1fcc11 ); vk.gate_setup_commitments[4] = PairingsBn254.new_g1( 0x14230a35f172cd77a2147cecc20b2a13148363cbab78709489a29d08001e26fb, 0x04f1040477d77896475080b5abb8091cda2cce4917ee0ba5dd62d0ab1be379b4 ); vk.gate_setup_commitments[5] = PairingsBn254.new_g1( 0x20d1a079ad80a8abb7fd8ba669dddbbe23231360a5f0ba679b6536b6bf980649, 0x120c5a845903bd6de4105eb8cef90e6dff2c3888ada16c90e1efb393778d6a4d ); vk.gate_setup_commitments[6] = PairingsBn254.new_g1( 0x1af6b9e362e458a96b8bbbf8f8ce2bdbd650fb68478360c408a2acf1633c1ce1, 0x27033728b767b44c659e7896a6fcc956af97566a5a1135f87a2e510976a62d41 ); vk.gate_selector_commitments[0] = PairingsBn254.new_g1( 0x0dbfb3c5f5131eb6f01e12b1a6333b0ad22cc8292b666e46e9bd4d80802cccdf, 0x2d058711c42fd2fd2eef33fb327d111a27fe2063b46e1bb54b32d02e9676e546 ); vk.gate_selector_commitments[1] = PairingsBn254.new_g1( 0x0c8c7352a84dd3f32412b1a96acd94548a292411fd7479d8609ca9bd872f1e36, 0x0874203fd8012d6976698cc2df47bca14bc04879368ade6412a2109c1e71e5e8 ); vk.copy_permutation_commitments[0] = PairingsBn254.new_g1( 0x1b17bb7c319b1cf15461f4f0b69d98e15222320cb2d22f4e3a5f5e0e9e51f4bd, 0x0cf5bc338235ded905926006027aa2aab277bc32a098cd5b5353f5545cbd2825 ); vk.copy_permutation_commitments[1] = PairingsBn254.new_g1( 0x0794d3cfbc2fdd756b162571a40e40b8f31e705c77063f30a4e9155dbc00e0ef, 0x1f821232ab8826ea5bf53fe9866c74e88a218c8d163afcaa395eda4db57b7a23 ); vk.copy_permutation_commitments[2] = PairingsBn254.new_g1( 0x224d93783aa6856621a9bbec495f4830c94994e266b240db9d652dbb394a283b, 0x161bcec99f3bc449d655c0ca59874dafe1194138eec91af34392b09a83338ca1 ); vk.copy_permutation_commitments[3] = PairingsBn254.new_g1( 0x1fa27e2916b2c11d39c74c0e61063190da31c102d2b7da5c0a61ec8c5e82f132, 0x0a815ee76cd8aa600e6f66463b25a0ee57814bfdf06c65a91ddc70cede41caae ); vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } pragma solidity >=0.5.0 <0.7.0; import "./PlonkSingleCore.sol"; // Hardcoded constants to avoid accessing store contract KeysWithPlonkSingleVerifier is SingleVerifierWithDeserialize { function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) { if (_size == uint32(6)) { return true; } else if (_size == uint32(12)) { return true; } else if (_size == uint32(48)) { return true; } else if (_size == uint32(96)) { return true; } else if (_size == uint32(204)) { return true; } else if (_size == uint32(420)) { return true; } else { return false; } } function getVkExit() internal pure returns(VerificationKey memory vk) { vk.domain_size = 262144; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe); vk.selector_commitments[0] = PairingsBn254.new_g1( 0x1abc710835cdc78389d61b670b0e8d26416a63c9bd3d6ed435103ebbb8a8665e, 0x138c6678230ed19f90b947d0a9027bd9fc458bbd1d2b8371fa72e28470a97b9c ); vk.selector_commitments[1] = PairingsBn254.new_g1( 0x28d81ac76e1ddf630b4bf8e4a789cf9c4470c5e5cc010a24849b20ab595b8b22, 0x251ca3cf0829b261d3be8d6cbd25aa97d9af716819c29f6319d806f075e79655 ); vk.selector_commitments[2] = PairingsBn254.new_g1( 0x1504c8c227833a1152f3312d258412c334ac7ae213e21427ff63028729bc28fa, 0x0f0942f3fede795cbe624fb9ddf9be90ba546609383f2246c3c9b92af7aab5fd ); vk.selector_commitments[3] = PairingsBn254.new_g1( 0x1f14a5bb19ea2897ac6b9fbdbd2b4e371be09f8e90a47ae26602d399c9bcd311, 0x029c6ea094247da75d9a66cea627c3c77d48b898003125d4f8e785435dc2cf23 ); vk.selector_commitments[4] = PairingsBn254.new_g1( 0x102cdd83e2d70638a70d700622b662607f8a2d92f5c36053a4ddb4b600d75bcf, 0x09ef3679579d761507ef69eaf49c978b271f0e4500468da1ebd7197f3ff5d6ac ); vk.selector_commitments[5] = PairingsBn254.new_g1( 0x2c2bd1d2fa3d4b3915d0fe465469e11ee563e79751da71c6082fcd0ca4e41cd5, 0x0304f16147a8af177dcc703370931d5161bda9dcf3e091787b9a54377ab54c32 ); // we only have access to value of the d(x) witness polynomial on the next // trace step, so we only need one element here and deal with it in other places // by having this in mind vk.next_step_selector_commitments[0] = PairingsBn254.new_g1( 0x14420680f992f4bc8d8012e2d8b14a774cf9114adf1e41b3c02c20cc1648398e, 0x237d3d5cdee5e3d7d58f4eb336ecd7aa5ec88d89205861b410420f6b9f6b26a1 ); vk.permutation_commitments[0] = PairingsBn254.new_g1( 0x221045ae5578ccb35e0a198d83c0fb191da8cdc98423fc46e580f1762682c73e, 0x15b7f3d74fcd258fdd2ae6001693a7c615e654d613a506d213aaf0ad314e338d ); vk.permutation_commitments[1] = PairingsBn254.new_g1( 0x03e47981b459b3be258a6353593898babec571ccf3e0362d53a67f078f04830a, 0x0809556ab6eb28403bb5a749fcdbd8656940add7685ff5473dc3a9ad940034df ); vk.permutation_commitments[2] = PairingsBn254.new_g1( 0x2c02322c53d7e6a6474b15c7db738419e3f4d1263e9f98ebb56c24906f555ef9, 0x2322c69f51366551665b584d797e0fdadb16fe31b1e7ae2f532847a75b3aeaab ); vk.permutation_commitments[3] = PairingsBn254.new_g1( 0x2147e39b49c2bef4168884c0ac9e38bb4dc65b41ba21953f7ded2daab7fe1534, 0x071f3548c9ca2c6a8d10b11d553263ebe0afaf1f663b927ef970bd6c3974cb68 ); vk.permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } function getVkLpExit() internal pure returns(VerificationKey memory vk) { vk.domain_size = 524288; vk.num_inputs = 1; vk.omega = PairingsBn254.new_fr(0x0cf1526aaafac6bacbb67d11a4077806b123f767e4b0883d14cc0193568fc082); vk.selector_commitments[0] = PairingsBn254.new_g1( 0x067d967299b3d380f2e461409fbacb82d9af8c85b62de082a423f344fb0b9d38, 0x2440bd569ac24e9525b29e433334ee98d72cb8eb19af65250ee0099fb470d873 ); vk.selector_commitments[1] = PairingsBn254.new_g1( 0x086a9ed0f6175964593e516a8c1fc8bbd0a9c8afb724ebbce08a7772bd7b8837, 0x0aca3794dc6a2f0cab69dfed529d31deb7a5e9e6c339e3c07d8d88df0f7abd6b ); vk.selector_commitments[2] = PairingsBn254.new_g1( 0x00b6bfec3aceb55618e6caf637c978c3fe2344568c64515022fcfa00e490eb97, 0x0f890fe6b9cb943fb4887df1529cdae99e2494eabf675f89905215eb51c29c6e ); vk.selector_commitments[3] = PairingsBn254.new_g1( 0x0968470be841bcbfbcccc10dd0d8b63a871cdb3289c214fc59f38c88ab15146a, 0x1a9b4d034050fa0b119bb64ba0e967fd09f224c6fd9cd8b54cd6f081085dfb98 ); vk.selector_commitments[4] = PairingsBn254.new_g1( 0x080dbe10de0cacf12db303a86049c7a4d42f068a9def099e0cb874008f210b1b, 0x02f17638d3410ab573e33a4e6c6cf0c918bea2aa4f1025ca5ee13d7a950c4058 ); vk.selector_commitments[5] = PairingsBn254.new_g1( 0x267043dbe00520bd8bbf55a96b51fde6b3b64219eca9e2fd8309693db0cf0392, 0x08dbbfa17faad841228af22a03fab7ec20f765036a2acae62f543f61e55b6e8c ); // we only have access to value of the d(x) witness polynomial on the next // trace step, so we only need one element here and deal with it in other places // by having this in mind vk.next_step_selector_commitments[0] = PairingsBn254.new_g1( 0x215141775449677e3dbe25ff6c5e5d99336a29d952a61d5ec87618346e78df30, 0x29502caeb6afaf2acd13766d52fac2907efb7d11c66cd8beb93c8321d380b215 ); vk.permutation_commitments[0] = PairingsBn254.new_g1( 0x150790105b9f5455ae6f91daa6b03c5793fb7bcfcd9d5d37d3b643b77535b10a, 0x2b644a9736282f80fae8d35f00cbddf2bba3560c54f3d036ec1c8014c147a506 ); vk.permutation_commitments[1] = PairingsBn254.new_g1( 0x1b898666ded092a449935de7d707ad8d65809c2baccdd7dd7cfdaf2fb27e1262, 0x2a24c241dcad93b7bdf1cce2427c9c54f731a7d50c27a825e2af3dabb66dc81f ); vk.permutation_commitments[2] = PairingsBn254.new_g1( 0x049892634dbbfa0c364523827cd7e604b70a7e24a4cb111cb8fccb7c05b04d7f, 0x1e5d8d7c0bf92d822dcf339a52c326a35cadf010b888b8f26e155a68c7e23dc9 ); vk.permutation_commitments[3] = PairingsBn254.new_g1( 0x04f90846cb1598aa05164a78d171ea918154414652d07d3f5cab84a26e6aa158, 0x0975ba8858f136bb8b1b043daf8dfed33709f72ba37e01e5de62c81f3928a13c ); vk.permutation_non_residues[0] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000005 ); vk.permutation_non_residues[1] = PairingsBn254.new_fr( 0x0000000000000000000000000000000000000000000000000000000000000007 ); vk.permutation_non_residues[2] = PairingsBn254.new_fr( 0x000000000000000000000000000000000000000000000000000000000000000a ); vk.g2_x = PairingsBn254.new_g2( [0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0], [0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55] ); } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function initialize(address, address) external; function mint(address to, uint amount) external; function burn(address to, uint amount) external; } pragma solidity =0.5.16; import './interfaces/IUniswapV2ERC20.sol'; import './libraries/UniswapSafeMath.sol'; contract UniswapV2ERC20 is IUniswapV2ERC20 { using UniswapSafeMath for uint; string public constant name = 'ZKSWAP V2'; string public constant symbol = 'ZKS-V2'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid } } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } pragma solidity =0.5.16; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } pragma solidity =0.5.16; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } pragma solidity >=0.5.0; interface IUNISWAPERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } pragma solidity >=0.5.0 <0.7.0; pragma experimental ABIEncoderV2; import "./PlonkCoreLib.sol"; contract Plonk4AggVerifierWithAccessToDNext { uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant ZERO = 0; uint256 constant ONE = 1; uint256 constant TWO = 2; uint256 constant THREE = 3; uint256 constant FOUR = 4; uint256 constant STATE_WIDTH = 4; uint256 constant NUM_DIFFERENT_GATES = 2; uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7; uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1; uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1; uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant LIMB_WIDTH = 68; struct VerificationKey { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments; PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments; PairingsBn254.Fr[STATE_WIDTH-1] copy_permutation_non_residues; PairingsBn254.G2Point g2_x; } struct Proof { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH] wire_commitments; PairingsBn254.G1Point copy_permutation_grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega; PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z; PairingsBn254.Fr copy_grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierState { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function evaluate_vanishing( uint256 domain_size, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); inputs_term.add_assign(tmp); } inputs_term.mul_assign(proof.gate_selector_values_at_z[0]); rhs.add_assign(inputs_term); // now we need 5th power quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function add_contribution_from_range_constraint_gates( PartialVerifierState memory state, Proof memory proof, PairingsBn254.Fr memory current_alpha ) internal pure returns (PairingsBn254.Fr memory res) { // now add contribution from range constraint gate // we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {}) PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE); PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO); PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE); PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR); res = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0); PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0); for (uint256 i = 0; i < 3; i++) { current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); } // now also d_next - 4a current_alpha.mul_assign(state.alpha); // high - 4*low // this is 4*low t0 = PairingsBn254.copy(proof.wire_values_at_z[0]); t0.mul_assign(four_fr); // high t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]); t1.sub_assign(t0); // t0 is now t1 - {0,1,2,3} // first unroll manually for -0; t2 = PairingsBn254.copy(t1); // -1 t0 = PairingsBn254.copy(t1); t0.sub_assign(one_fr); t2.mul_assign(t0); // -2 t0 = PairingsBn254.copy(t1); t0.sub_assign(two_fr); t2.mul_assign(t0); // -3 t0 = PairingsBn254.copy(t1); t0.sub_assign(three_fr); t2.mul_assign(t0); t2.mul_assign(current_alpha); res.add_assign(t2); return res; } function reconstruct_linearization_commitment( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^{6} * (selector(x) - selector(z)) // + v^{7..9} * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^10 (z(x) - z(z*omega)) <- we need this power // + v^11 * (d(x) - d(z*omega)) // ] // // we reconstruct linearization polynomial virtual selector // for that purpose we first linearize over main gate (over all it's selectors) // and multiply them by value(!) of the corresponding main gate selector res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x) PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH; i++) { tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH+2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x) res.point_add_assign(tmp_g1); // multiply by main gate selector(z) res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE); // calculate scalar contribution from the range check gate tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha); tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar res.point_add_assign(tmp_g1); // proceed as normal to copy permutation current_alpha.mul_assign(state.alpha); // alpha^5 PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i+1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(alpha_for_grand_product); // alpha^n & L_{0}(z), and we bump current_alpha current_alpha.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(current_alpha); grand_product_part_at_z.add_assign(tmp_fr); // prefactor for grand_product(x) is complete // add to the linearization a part from the term // - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X) PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument // actually multiply prefactors by z(x) and perm_d(x) and combine them tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); // multiply them by v immedately as linearization has a factor of v^1 res.point_mul_assign(state.v); // res now contains contribution from the gates linearization and // copy permutation part // now we need to add a part that is the rest // for z(x*omega): // - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega) } function aggregate_commitments( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point[2] memory res) { PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.gate_selector_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint i = 0; i < vk.copy_permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); // now do prefactor for grand_product(x*omega) tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr)); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint i = 0; i < proof.gate_selector_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.gate_selector_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.copy_grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); res[0] = pair_with_generator; res[1] = pair_with_x; return res; } function verify_initial( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs == 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.copy_permutation_grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); state.cached_lagrange_evals = new PairingsBn254.Fr[](1); state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain( 0, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } transcript.update_with_fr(proof.quotient_polynomial_at_z); for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } transcript.update_with_fr(proof.gate_selector_values_at_z[0]); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.copy_grand_product_at_z_omega); transcript.update_with_fr(proof.linearization_polynomial_at_z); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function aggregate_for_verification(Proof memory proof, VerificationKey memory vk) internal view returns (bool valid, PairingsBn254.G1Point[2] memory part) { PartialVerifierState memory state; valid = verify_initial(state, proof, vk); if (valid == false) { return (valid, part); } part = aggregate_commitments(state, proof, vk); (valid, part); } function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) { (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } valid = PairingsBn254.pairingProd2(recursive_proof_part[0], PairingsBn254.P2(), recursive_proof_part[1], vk.g2_x); return valid; } function verify_recursive( Proof memory proof, VerificationKey memory vk, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[] memory subproofs_limbs ) internal view returns (bool) { (uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) = reconstruct_recursive_public_input( recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs ); assert(recursive_input == proof.input_values[0]); (bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk); if (valid == false) { return false; } // aggregated_g1s = inner // recursive_proof_part = outer PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part); valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x); return valid; } function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer) internal view returns (PairingsBn254.G1Point[2] memory result) { // reuse the transcript primitive TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); transcript.update_with_g1(inner[0]); transcript.update_with_g1(inner[1]); transcript.update_with_g1(outer[0]); transcript.update_with_g1(outer[1]); PairingsBn254.Fr memory challenge = transcript.get_challenge(); // 1 * inner + challenge * outer result[0] = PairingsBn254.copy_g1(inner[0]); result[1] = PairingsBn254.copy_g1(inner[1]); PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge); result[0].point_add_assign(tmp); tmp = outer[1].point_mul(challenge); result[1].point_add_assign(tmp); return result; } function reconstruct_recursive_public_input( uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[] memory subproofs_aggregated ) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) { assert(recursive_vks_indexes.length == individual_vks_inputs.length); bytes memory concatenated = abi.encodePacked(recursive_vks_root); uint8 index; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { index = recursive_vks_indexes[i]; assert(index <= max_valid_index); concatenated = abi.encodePacked(concatenated, index); } uint256 input; for (uint256 i = 0; i < recursive_vks_indexes.length; i++) { input = individual_vks_inputs[i]; assert(input < r_mod); concatenated = abi.encodePacked(concatenated, input); } concatenated = abi.encodePacked(concatenated, subproofs_aggregated); bytes32 commitment = sha256(concatenated); recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK; reconstructed_g1s[0] = PairingsBn254.new_g1_checked( subproofs_aggregated[0] + (subproofs_aggregated[1] << LIMB_WIDTH) + (subproofs_aggregated[2] << 2*LIMB_WIDTH) + (subproofs_aggregated[3] << 3*LIMB_WIDTH), subproofs_aggregated[4] + (subproofs_aggregated[5] << LIMB_WIDTH) + (subproofs_aggregated[6] << 2*LIMB_WIDTH) + (subproofs_aggregated[7] << 3*LIMB_WIDTH) ); reconstructed_g1s[1] = PairingsBn254.new_g1_checked( subproofs_aggregated[8] + (subproofs_aggregated[9] << LIMB_WIDTH) + (subproofs_aggregated[10] << 2*LIMB_WIDTH) + (subproofs_aggregated[11] << 3*LIMB_WIDTH), subproofs_aggregated[12] + (subproofs_aggregated[13] << LIMB_WIDTH) + (subproofs_aggregated[14] << 2*LIMB_WIDTH) + (subproofs_aggregated[15] << 3*LIMB_WIDTH) ); return (recursive_input, reconstructed_g1s); } } contract AggVerifierWithDeserialize is Plonk4AggVerifierWithAccessToDNext { uint256 constant SERIALIZED_PROOF_LENGTH = 34; function deserialize_proof( uint256[] memory public_inputs, uint256[] memory serialized_proof ) internal pure returns(Proof memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; } proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) { proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.opening_at_z_proof = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); } function verify_serialized_proof( uint256[] memory public_inputs, uint256[] memory serialized_proof, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify(proof, vk); return valid; } function verify_serialized_proof_with_recursion( uint256[] memory public_inputs, uint256[] memory serialized_proof, uint256 recursive_vks_root, uint8 max_valid_index, uint8[] memory recursive_vks_indexes, uint256[] memory individual_vks_inputs, uint256[] memory subproofs_limbs, VerificationKey memory vk ) public view returns (bool) { require(vk.num_inputs == public_inputs.length); Proof memory proof = deserialize_proof(public_inputs, serialized_proof); bool valid = verify_recursive(proof, vk, recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs); return valid; } } pragma solidity >=0.5.0 <0.7.0; import "./PlonkCoreLib.sol"; contract Plonk4SingleVerifierWithAccessToDNext { using PairingsBn254 for PairingsBn254.G1Point; using PairingsBn254 for PairingsBn254.G2Point; using PairingsBn254 for PairingsBn254.Fr; using TranscriptLibrary for TranscriptLibrary.Transcript; uint256 constant STATE_WIDTH = 4; uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1; struct VerificationKey { uint256 domain_size; uint256 num_inputs; PairingsBn254.Fr omega; PairingsBn254.G1Point[STATE_WIDTH+2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] next_step_selector_commitments; PairingsBn254.G1Point[STATE_WIDTH] permutation_commitments; PairingsBn254.Fr[STATE_WIDTH-1] permutation_non_residues; PairingsBn254.G2Point g2_x; } struct Proof { uint256[] input_values; PairingsBn254.G1Point[STATE_WIDTH] wire_commitments; PairingsBn254.G1Point grand_product_commitment; PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments; PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z; PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega; PairingsBn254.Fr grand_product_at_z_omega; PairingsBn254.Fr quotient_polynomial_at_z; PairingsBn254.Fr linearization_polynomial_at_z; PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z; PairingsBn254.G1Point opening_at_z_proof; PairingsBn254.G1Point opening_at_z_omega_proof; } struct PartialVerifierState { PairingsBn254.Fr alpha; PairingsBn254.Fr beta; PairingsBn254.Fr gamma; PairingsBn254.Fr v; PairingsBn254.Fr u; PairingsBn254.Fr z; PairingsBn254.Fr[] cached_lagrange_evals; } function evaluate_lagrange_poly_out_of_domain( uint256 poly_num, uint256 domain_size, PairingsBn254.Fr memory omega, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { require(poly_num < domain_size); PairingsBn254.Fr memory one = PairingsBn254.new_fr(1); PairingsBn254.Fr memory omega_power = omega.pow(poly_num); res = at.pow(domain_size); res.sub_assign(one); require(res.value != 0); // Vanishing polynomial can not be zero at point `at` res.mul_assign(omega_power); PairingsBn254.Fr memory den = PairingsBn254.copy(at); den.sub_assign(omega_power); den.mul_assign(PairingsBn254.new_fr(domain_size)); den = den.inverse(); res.mul_assign(den); } function evaluate_vanishing( uint256 domain_size, PairingsBn254.Fr memory at ) internal view returns (PairingsBn254.Fr memory res) { res = at.pow(domain_size); res.sub_assign(PairingsBn254.new_fr(1)); } function verify_at_z( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z); require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain lhs.mul_assign(proof.quotient_polynomial_at_z); PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z); // public inputs PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0); for (uint256 i = 0; i < proof.input_values.length; i++) { tmp.assign(state.cached_lagrange_evals[i]); tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i])); rhs.add_assign(tmp); } quotient_challenge.mul_assign(state.alpha); PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp.assign(proof.permutation_polynomials_at_z[i]); tmp.mul_assign(state.beta); tmp.add_assign(state.gamma); tmp.add_assign(proof.wire_values_at_z[i]); z_part.mul_assign(tmp); } tmp.assign(state.gamma); // we need a wire value of the last polynomial in enumeration tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]); z_part.mul_assign(tmp); z_part.mul_assign(quotient_challenge); rhs.sub_assign(z_part); quotient_challenge.mul_assign(state.alpha); tmp.assign(state.cached_lagrange_evals[0]); tmp.mul_assign(quotient_challenge); rhs.sub_assign(tmp); return lhs.value == rhs.value; } function reconstruct_d( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (PairingsBn254.G1Point memory res) { // we compute what power of v is used as a delinearization factor in batch opening of // commitments. Let's label W(x) = 1 / (x - z) * // [ // t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z) // + v (r(x) - r(z)) // + v^{2..5} * (witness(x) - witness(z)) // + v^(6..8) * (permutation(x) - permutation(z)) // ] // W'(x) = 1 / (x - z*omega) * // [ // + v^9 (z(x) - z(z*omega)) <- we need this power // + v^10 * (d(x) - d(z*omega)) // ] // // we pay a little for a few arithmetic operations to not introduce another constant uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH + STATE_WIDTH - 1; res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH + 1]); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0); // addition gates for (uint256 i = 0; i < STATE_WIDTH; i++) { tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]); res.point_add_assign(tmp_g1); } // multiplication gate tmp_fr.assign(proof.wire_values_at_z[0]); tmp_fr.mul_assign(proof.wire_values_at_z[1]); tmp_g1 = vk.selector_commitments[STATE_WIDTH].point_mul(tmp_fr); res.point_add_assign(tmp_g1); // d_next tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]); res.point_add_assign(tmp_g1); // z * non_res * beta + gamma + a PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z); grand_product_part_at_z.mul_assign(state.beta); grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]); grand_product_part_at_z.add_assign(state.gamma); for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) { tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.permutation_non_residues[i]); tmp_fr.mul_assign(state.beta); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i+1]); grand_product_part_at_z.mul_assign(tmp_fr); } grand_product_part_at_z.mul_assign(state.alpha); tmp_fr.assign(state.cached_lagrange_evals[0]); tmp_fr.mul_assign(state.alpha); tmp_fr.mul_assign(state.alpha); grand_product_part_at_z.add_assign(tmp_fr); PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening); grand_product_part_at_z_omega.mul_assign(state.u); PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1); for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { tmp_fr.assign(state.beta); tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]); tmp_fr.add_assign(state.gamma); tmp_fr.add_assign(proof.wire_values_at_z[i]); last_permutation_part_at_z.mul_assign(tmp_fr); } last_permutation_part_at_z.mul_assign(state.beta); last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega); last_permutation_part_at_z.mul_assign(state.alpha); // add to the linearization tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z); tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z)); res.point_add_assign(tmp_g1); res.point_mul_assign(state.v); res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega)); } function verify_commitments( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk); PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size); PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1(); PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]); PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1); for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) { tmp_fr.mul_assign(z_in_domain_size); tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); commitment_aggregation.point_add_assign(d); for (uint i = 0; i < proof.wire_commitments.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } for (uint i = 0; i < vk.permutation_commitments.length - 1; i++) { aggregation_challenge.mul_assign(state.v); tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge); commitment_aggregation.point_add_assign(tmp_g1); } aggregation_challenge.mul_assign(state.v); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(aggregation_challenge); tmp_fr.mul_assign(state.u); tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr); commitment_aggregation.point_add_assign(tmp_g1); // collect opening values aggregation_challenge = PairingsBn254.new_fr(1); PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.linearization_polynomial_at_z); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); for (uint i = 0; i < proof.wire_values_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) { aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.permutation_polynomials_at_z[i]); tmp_fr.mul_assign(aggregation_challenge); aggregated_value.add_assign(tmp_fr); } aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.grand_product_at_z_omega); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); aggregation_challenge.mul_assign(state.v); tmp_fr.assign(proof.wire_values_at_z_omega[0]); tmp_fr.mul_assign(aggregation_challenge); tmp_fr.mul_assign(state.u); aggregated_value.add_assign(tmp_fr); commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value)); PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation; pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z)); tmp_fr.assign(state.z); tmp_fr.mul_assign(vk.omega); tmp_fr.mul_assign(state.u); pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr)); PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u); pair_with_x.point_add_assign(proof.opening_at_z_proof); pair_with_x.negate(); return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x); } function verify_initial( PartialVerifierState memory state, Proof memory proof, VerificationKey memory vk ) internal view returns (bool) { require(proof.input_values.length == vk.num_inputs); require(vk.num_inputs == 1); TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript(); for (uint256 i = 0; i < vk.num_inputs; i++) { transcript.update_with_u256(proof.input_values[i]); } for (uint256 i = 0; i < proof.wire_commitments.length; i++) { transcript.update_with_g1(proof.wire_commitments[i]); } state.beta = transcript.get_challenge(); state.gamma = transcript.get_challenge(); transcript.update_with_g1(proof.grand_product_commitment); state.alpha = transcript.get_challenge(); for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) { transcript.update_with_g1(proof.quotient_poly_commitments[i]); } state.z = transcript.get_challenge(); state.cached_lagrange_evals = new PairingsBn254.Fr[](1); state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain( 0, vk.domain_size, vk.omega, state.z ); bool valid = verify_at_z(state, proof, vk); if (valid == false) { return false; } for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) { transcript.update_with_fr(proof.wire_values_at_z[i]); } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { transcript.update_with_fr(proof.wire_values_at_z_omega[i]); } for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { transcript.update_with_fr(proof.permutation_polynomials_at_z[i]); } transcript.update_with_fr(proof.quotient_polynomial_at_z); transcript.update_with_fr(proof.linearization_polynomial_at_z); transcript.update_with_fr(proof.grand_product_at_z_omega); state.v = transcript.get_challenge(); transcript.update_with_g1(proof.opening_at_z_proof); transcript.update_with_g1(proof.opening_at_z_omega_proof); state.u = transcript.get_challenge(); return true; } // This verifier is for a PLONK with a state width 4 // and main gate equation // q_a(X) * a(X) + // q_b(X) * b(X) + // q_c(X) * c(X) + // q_d(X) * d(X) + // q_m(X) * a(X) * b(X) + // q_constants(X)+ // q_d_next(X) * d(X*omega) // where q_{}(X) are selectors a, b, c, d - state (witness) polynomials // q_d_next(X) "peeks" into the next row of the trace, so it takes // the same d(X) polynomial, but shifted function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) { PartialVerifierState memory state; bool valid = verify_initial(state, proof, vk); if (valid == false) { return false; } valid = verify_commitments(state, proof, vk); return valid; } } contract SingleVerifierWithDeserialize is Plonk4SingleVerifierWithAccessToDNext { uint256 constant SERIALIZED_PROOF_LENGTH = 33; function deserialize_proof( uint256[] memory public_inputs, uint256[] memory serialized_proof ) internal pure returns(Proof memory proof) { require(serialized_proof.length == SERIALIZED_PROOF_LENGTH); proof.input_values = new uint256[](public_inputs.length); for (uint256 i = 0; i < public_inputs.length; i++) { proof.input_values[i] = public_inputs[i]; } uint256 j = 0; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; } proof.grand_product_commitment = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; } for (uint256 i = 0; i < STATE_WIDTH; i++) { proof.wire_values_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) { proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } proof.grand_product_at_z_omega = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.quotient_polynomial_at_z = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; proof.linearization_polynomial_at_z = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) { proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr( serialized_proof[j] ); j += 1; } proof.opening_at_z_proof = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); j += 2; proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked( serialized_proof[j], serialized_proof[j+1] ); } } pragma solidity >=0.5.0; interface IUniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } pragma solidity =0.5.16; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library UniswapSafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } pragma solidity >=0.5.0 <0.7.0; library PairingsBn254 { uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant bn254_b_coeff = 3; struct G1Point { uint256 X; uint256 Y; } struct Fr { uint256 value; } function new_fr(uint256 fr) internal pure returns (Fr memory) { require(fr < r_mod); return Fr({value: fr}); } function copy(Fr memory self) internal pure returns (Fr memory n) { n.value = self.value; } function assign(Fr memory self, Fr memory other) internal pure { self.value = other.value; } function inverse(Fr memory fr) internal view returns (Fr memory) { require(fr.value != 0); return pow(fr, r_mod-2); } function add_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, other.value, r_mod); } function sub_assign(Fr memory self, Fr memory other) internal pure { self.value = addmod(self.value, r_mod - other.value, r_mod); } function mul_assign(Fr memory self, Fr memory other) internal pure { self.value = mulmod(self.value, other.value, r_mod); } function pow(Fr memory self, uint256 power) internal view returns (Fr memory) { uint256[6] memory input = [32, 32, 32, self.value, power, r_mod]; uint256[1] memory result; bool success; assembly { success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20) } require(success); return Fr({value: result[0]}); } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint[2] X; uint[2] Y; } function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); } function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) { return G1Point(x, y); } function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) { if (x == 0 && y == 0) { // point of infinity is (0,0) return G1Point(x, y); } // check encoding require(x < q_mod); require(y < q_mod); // check on curve uint256 lhs = mulmod(y, y, q_mod); // y^2 uint256 rhs = mulmod(x, x, q_mod); // x^2 rhs = mulmod(rhs, x, q_mod); // x^3 rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b require(lhs == rhs); return G1Point(x, y); } function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) { return G2Point(x, y); } function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) { result.X = self.X; result.Y = self.Y; } function P2() internal pure returns (G2Point memory) { // for some reason ethereum expects to have c1*v + c0 form return G2Point( [0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed], [0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa] ); } function negate(G1Point memory self) internal pure { // The prime q in the base field F_q for G1 if (self.Y == 0) { require(self.X == 0); return; } self.Y = q_mod - self.Y; } function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { point_add_into_dest(p1, p2, r); return r; } function point_add_assign(G1Point memory p1, G1Point memory p2) internal view { point_add_into_dest(p1, p2, p1); } function point_add_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest) internal view { if (p2.X == 0 && p2.Y == 0) { // we add zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we add into zero, and we add non-zero point dest.X = p2.X; dest.Y = p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view { point_sub_into_dest(p1, p2, p1); } function point_sub_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest) internal view { if (p2.X == 0 && p2.Y == 0) { // we subtracted zero, nothing happens dest.X = p1.X; dest.Y = p1.Y; return; } else if (p1.X == 0 && p1.Y == 0) { // we subtract from zero, and we subtract non-zero point dest.X = p2.X; dest.Y = q_mod - p2.Y; return; } else { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = q_mod - p2.Y; bool success = false; assembly { success := staticcall(gas(), 6, input, 0x80, dest, 0x40) } require(success); } } function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) { point_mul_into_dest(p, s, r); return r; } function point_mul_assign(G1Point memory p, Fr memory s) internal view { point_mul_into_dest(p, s, p); } function point_mul_into_dest(G1Point memory p, Fr memory s, G1Point memory dest) internal view { uint[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s.value; bool success; assembly { success := staticcall(gas(), 7, input, 0x60, dest, 0x40) } require(success); } function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length); uint elements = p1.length; uint inputSize = elements * 6; uint[] memory input = new uint[](inputSize); for (uint i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint[1] memory out; bool success; assembly { success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } } library TranscriptLibrary { // flip 0xe000000000000000000000000000000000000000000000000000000000000000; uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint32 constant DST_0 = 0; uint32 constant DST_1 = 1; uint32 constant DST_CHALLENGE = 2; struct Transcript { bytes32 state_0; bytes32 state_1; uint32 challenge_counter; } function new_transcript() internal pure returns (Transcript memory t) { t.state_0 = bytes32(0); t.state_1 = bytes32(0); t.challenge_counter = 0; } function update_with_u256(Transcript memory self, uint256 value) internal pure { bytes32 old_state_0 = self.state_0; self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value)); self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value)); } function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure { update_with_u256(self, value.value); } function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure { update_with_u256(self, p.X); update_with_u256(self, p.Y); } function get_challenge(Transcript memory self) internal pure returns(PairingsBn254.Fr memory challenge) { bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter)); self.challenge_counter += 1; challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK}); } }
Checks that contract is ready for upgrade return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool) { return !exodusMode; }
1,250,285
pragma solidity ^0.5.0; contract BuilderShop { address[] builderInstances; uint contractId = 0; // nifty registry is hard coded address niftyRegistryContract = 0x6e53130dDfF21E3BC963Ee902005223b9A202106; modifier onlyValidSender() { NiftyRegistry nftg_registry = NiftyRegistry(niftyRegistryContract); bool is_valid = nftg_registry.isValidNiftySender(msg.sender); require(is_valid==true); _; } mapping (address => bool) public BuilderShops; function isValidBuilderShop(address builder_shop) public view returns (bool isValid) { // public function, allowing anyone to check if a contract address is a valid nifty gateway contract return(BuilderShops[builder_shop]); } event BuilderInstanceCreated(address new_contract_address, uint contractId); function createNewBuilderInstance( string memory _name, string memory _symbol, uint num_nifties, string memory token_base_uri, string memory creator_name) public onlyValidSender returns (NiftyBuilderInstance tokenAddress) { contractId = contractId + 1; NiftyBuilderInstance new_contract = new NiftyBuilderInstance( _name, _symbol, contractId, num_nifties, token_base_uri, creator_name ); address externalId = address(new_contract); BuilderShops[externalId] = true; emit BuilderInstanceCreated(externalId, contractId); return (new_contract); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; 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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @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), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return 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), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * 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, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @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) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * 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 != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), 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. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * 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 { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-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. * 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 { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-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. * Requires the _msgSender() 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 memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * 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. * 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 memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @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) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * 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. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * 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. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * 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 */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @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) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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. * * This function is deprecated. * @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) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { 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 with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * 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(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @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) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * 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 */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @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.sub(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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Optional mapping for IPFS link to canonical image file mapping(uint256 => string) private _tokenIPFSHashes; mapping(uint256 => string) private _niftyTypeName; // Optional mapping for IPFS link to canonical image file by Nifty type mapping(uint256 => string) private _niftyTypeIPFSHashes; mapping(uint256 => string) private _tokenName; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } // master builder - ONLY DOES STATIC CALLS address public masterBuilderContract = 0x6EFB06cF568253a53C7511BD3c31AB28BecB0192; /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); BuilderMaster bm = BuilderMaster(masterBuilderContract); string memory tokenIdStr = bm.uint2str(tokenId); string memory tokenURIStr = bm.strConcat(_baseURI, tokenIdStr); return tokenURIStr; } /** * @dev Returns an IPFS hash for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenIPFSHash(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: IPFS hash query for nonexistent token"); //master for static calls BuilderMaster bm = BuilderMaster(masterBuilderContract); uint nifty_type = bm.getNiftyTypeId(tokenId); return _niftyTypeIPFSHashes[nifty_type]; } /** * @dev Returns the Name for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenName(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: Name query for nonexistent token"); //master for static calls BuilderMaster bm = BuilderMaster(masterBuilderContract); uint nifty_type = bm.getNiftyTypeId(tokenId); return _niftyTypeName[nifty_type]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to set the token IPFS hash for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param ipfs_hash string IPFS link to assign */ function _setTokenIPFSHash(uint256 tokenId, string memory ipfs_hash) internal { require(_exists(tokenId), "ERC721Metadata: IPFS hash set of nonexistent token"); _tokenIPFSHashes[tokenId] = ipfs_hash; } /** * @dev Internal function to set the token IPFS hash for a nifty type. * @param nifty_type uint256 ID component of the token to set its IPFS hash * @param ipfs_hash string IPFS link to assign */ function _setTokenIPFSHashNiftyType(uint256 nifty_type, string memory ipfs_hash) internal { _niftyTypeIPFSHashes[nifty_type] = ipfs_hash; } /** * @dev Internal function to set the name for a nifty type. * @param nifty_type uint256 of nifty type name to be set * @param nifty_type_name name of nifty type */ function _setNiftyTypeName(uint256 nifty_type, string memory nifty_type_name) internal { _niftyTypeName[nifty_type] = nifty_type_name; } function _setBaseURIParent(string memory newBaseURI) internal { _baseURI = newBaseURI; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @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); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } contract NiftyBuilderInstance is ERC721Full { // MODIFIERS modifier onlyValidSender() { NiftyRegistry nftg_registry = NiftyRegistry(niftyRegistryContract); bool is_valid = nftg_registry.isValidNiftySender(msg.sender); require(is_valid==true); _; } // CONSTANTS // how many nifties this contract is selling // used for metadat retrieval uint public numNiftiesCurrentlyInContract; // id of this contract for metadata server uint public contractId; // baseURI for metadata server string public baseURI; // name of creator string public nameOfCreator; // nifty registry contract address public niftyRegistryContract = 0x6e53130dDfF21E3BC963Ee902005223b9A202106; // master builder - ONLY DOES STATIC CALLS address public masterBuilderContract = 0x6EFB06cF568253a53C7511BD3c31AB28BecB0192; using Counters for Counters.Counter; // MAPPINGS // mappings for token Ids mapping (uint => Counters.Counter) public _numNiftyMinted; mapping (uint => uint) public _numNiftyPermitted; mapping (uint => uint) public _niftyPrice; mapping (uint => bool) public _IPFSHashHasBeenSet; // EVENTS // purchase + creation events event NiftyPurchased(address _buyer, uint256 _amount, uint _tokenId); event NiftyCreated(address new_owner, uint _niftyType, uint _tokenId); // CONSTRUCTOR FUNCTION constructor( string memory _name, string memory _symbol, uint contract_id, uint num_nifties, string memory base_uri, string memory name_of_creator) ERC721Full(_name, _symbol) onlyValidSender public { // set local variables based on inputs contractId = contract_id; numNiftiesCurrentlyInContract = num_nifties; baseURI = base_uri; nameOfCreator = name_of_creator; } function setNiftyName(uint nifty_type, string memory nifty_name) onlyValidSender public { // allow owner to change nifty name _setNiftyTypeName(nifty_type, nifty_name); } function setBaseURI(string memory new_base_URI) onlyValidSender public { // allow owner to change base URI _setBaseURIParent(new_base_URI); } function setNiftyIPFSHash(uint nifty_type, string memory ipfs_hash) onlyValidSender public { // check if IPFS hash has been set if (_IPFSHashHasBeenSet[nifty_type] == true) { revert("IPFS hash already set for this NFT"); } _setTokenIPFSHashNiftyType(nifty_type, ipfs_hash); _IPFSHashHasBeenSet[nifty_type] = true; } function isNiftySoldOut(uint nifty_type) public view returns (bool) { if (nifty_type > numNiftiesCurrentlyInContract) { return true; } if (_numNiftyMinted[nifty_type].current() > _numNiftyPermitted[nifty_type]) { return (true); } return (false); } function giftNifty(address collector_address, uint nifty_type) onlyValidSender public { // master for static calls BuilderMaster bm = BuilderMaster(masterBuilderContract); _numNiftyMinted[nifty_type].increment(); // check if this nifty is sold out if (isNiftySoldOut(nifty_type)==true) { revert("Nifty sold out!"); } // mint a nifty uint specificTokenId = _numNiftyMinted[nifty_type].current(); uint tokenId = bm.encodeTokenId(contractId, nifty_type, specificTokenId); // mint token _mint(collector_address, tokenId); // invoke events emit NiftyCreated(collector_address, nifty_type, tokenId); } function massMintNFTs(address collector_address, uint num_to_mint, uint nifty_type) onlyValidSender public { // loop through array and create nifties for (uint i=0; i < num_to_mint; i++) { giftNifty(collector_address, nifty_type); } } } contract NiftyRegistry { function isValidNiftySender(address sending_key) public view returns (bool); function isOwner(address owner_key) public view returns (bool); } contract BuilderMaster { function getContractId(uint tokenId) public view returns (uint); function getNiftyTypeId(uint tokenId) public view returns (uint); function getSpecificNiftyNum(uint tokenId) public view returns (uint); function encodeTokenId(uint contractId, uint niftyType, uint specificNiftyNum) public view returns (uint); function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) public view returns (string memory); function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) public view returns (string memory); function strConcat(string memory _a, string memory _b, string memory _c) public view returns (string memory); function strConcat(string memory _a, string memory _b) public view returns (string memory); function uint2str(uint _i) public view returns (string memory _uintAsString); } /** * Contracts and libraries below are from OpenZeppelin, except nifty builder instance **/ /** * @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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } }
Internal function to transfer ownership of a given token ID to another address. As opposed to {transferFrom}, this imposes no restrictions on msg.sender. from current owner of the token to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred/
function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); }
502,773
./partial_match/1/0x97b3Ef4C558Ec456D59Cb95c65BFB79046E31fCA/sources/contracts/allocators/interfaces/LiquityInterfaces.sol
ERROR: type should be string, got "https:etherscan.io/address/0x66017D22b0f8556afDd19FC67041899Eb65a21bb The Stability Pool holds LUSD tokens deposited by Stability Pool depositors. When a trove is liquidated, then depending on system conditions, some of its LUSD debt gets offset with LUSD in the Stability Pool: that is, the offset debt evaporates, and an equal amount of LUSD tokens in the Stability Pool is burned. Thus, a liquidation causes each depositor to receive a LUSD loss, in proportion to their deposit as a share of total deposits. They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors, in the same proportion. When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40% of the total LUSD in the Stability Pool, depletes 40% of each deposit. A deposit that has experienced a series of liquidations is termed a \"compounded deposit\": each liquidation depletes the deposit, multiplying it by some factor in range ]0,1[ Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations: --- LQTY ISSUANCE TO STABILITY POOL DEPOSITORS --- An LQTY issuance event occurs at every deposit operation, and every liquidation. Each deposit is tagged with the address of the front end through which it was made. All deposits earn a share of the issued LQTY in proportion to the deposit as a share of total deposits. The LQTY earned by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate. Please see the system Readme for an overview:/ --- Functions ---"
interface IStabilityPool { function provideToSP(uint256 _amount, address _frontEndTag) external; function withdrawFromSP(uint256 _amount) external; function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external; function registerFrontEnd(uint256 _kickbackRate) external; function offset(uint256 _debt, uint256 _coll) external; function getETH() external view returns (uint256); function getTotalLUSDDeposits() external view returns (uint256); function getDepositorETHGain(address _depositor) external view returns (uint256); function getDepositorLQTYGain(address _depositor) external view returns (uint256); function getFrontEndLQTYGain(address _frontEnd) external view returns (uint256); function getCompoundedLUSDDeposit(address _depositor) external view returns (uint256); function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint256); }
4,146,553
./partial_match/4/0x440e072BB89b217f6880E36423a39f5933B8348E/sources/GovTreasurer.sol
DEPOSIT | FARMING ASSETS (TOKENS) | RE-ENTRANCY DEFENSEuint256 owedAmount = user.amount.sub(taxedAmount);
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 pending = user.amount.mul(pool.accGDAOPerShare).div(1e12).sub(user.rewardDebt); uint256 taxedAmount = user.amount.div(pool.taxRate); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accGDAOPerShare).div(1e12); safeGDAOTransfer(msg.sender, pending); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(taxedAmount)); pool.lpToken.safeTransferFrom(address(msg.sender), address(devaddr), _amount.div(pool.taxRate)); emit Deposit(msg.sender, _pid, _amount); }
8,580,536
//Address: 0x05acecc73ff68c850e0ff5a068262678966d9f4d //Contract name: HedgeminerToken //Balance: 0 Ether //Verification Date: 9/11/2017 //Transacion Count: 1 // CODE STARTS HERE /** * HMT - Hedgeminer token * based upon code from ERC223 * and Human Standard Token * author: Marek Owsikowski * Project page: * https://github.com/mjobuda/hedgeminer * */ pragma solidity ^0.4.11; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { require (assertion); } } contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance // function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not // function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { // function transfer(address _to, uint256 _value) returns (bool success) { // //Default assumes totalSupply can't be over max (2^256 - 1). // //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. // //Replace the if with this one instead. // //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); // require(balances[msg.sender] >= _value); // balances[msg.sender] -= _value; // balances[_to] += _value; // Transfer(msg.sender, _to, _value); // return true; // } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract ERC223Basic is StandardToken{ uint public totalSupply; // function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); function transfer(address to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } contract ERC223BasicToken is ERC223Basic{ using SafeMath for uint; mapping(address => uint) balances; // Function that is called when a user or another contract wants to transfer funds . function transfer(address to, uint value, bytes data) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(to) } balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(to); receiver.tokenFallback(msg.sender, value, data); } Transfer(msg.sender, to, value, data); } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address to, uint value) { uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(to) } balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(to); receiver.tokenFallback(msg.sender, value, empty); } Transfer(msg.sender, to, value, empty); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } /* * Contract that is working with ERC223 tokens */ contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data); } contract HumanERC223Token is ERC223BasicToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. function HumanERC223Token ( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } } // Creates 20,000,000.000000000000000000 Hedgeminer Token (HMT) Tokens contract HedgeminerToken is HumanERC223Token (20000000000000000000000000, "Hedgeminer Token", 18, "HMT") {}
Standard function transfer similar to ERC20 transfer with no _data . Added due to backwards compatibility reasons . Retrieve the size of the code on target address, this needs assembly .
function transfer(address to, uint value) { uint codeLength; bytes memory empty; assembly { codeLength := extcodesize(to) } balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(to); receiver.tokenFallback(msg.sender, value, empty); } Transfer(msg.sender, to, value, empty); }
12,734,942
pragma solidity 0.4.24; contract ExecutionTarget { uint256 public counter; function execute() public { counter += 1; emit Executed(counter); } function setCounter(uint256 x) public { counter = x; } event Executed(uint256 x); } pragma solidity 0.4.24; import "@aragon/os/contracts/acl/ACL.sol"; import "@aragon/os/contracts/kernel/Kernel.sol"; import "@aragon/os/contracts/factory/DAOFactory.sol"; import "@aragon/os/contracts/factory/APMRegistryFactory.sol"; import "@aragon/os/contracts/factory/ENSFactory.sol"; import "@aragon/os/contracts/apm/APMRegistry.sol"; import "@aragon/os/contracts/apm/Repo.sol"; import "@aragon/os/contracts/ens/ENSSubdomainRegistrar.sol"; import "@aragon/os/contracts/lib/ens/ENS.sol"; import "@aragon/os/contracts/lib/ens/AbstractENS.sol"; import "@aragon/os/contracts/lib/ens/PublicResolver.sol"; import "@aragon/test-helpers/contracts/TokenMock.sol"; contract Imports { // solium-disable-previous-line no-empty-blocks } pragma solidity 0.4.24; import "../apps/AragonApp.sol"; import "../common/ConversionHelpers.sol"; import "../common/TimeHelpers.sol"; import "./ACLSyntaxSugar.sol"; import "./IACL.sol"; import "./IACLOracle.sol"; /* 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" 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); bool ok; assembly { // send all available gas; if the oracle eats up all the gas, we will eventually revert // note that we are currently guaranteed to still have some gas after the call from // EIP-150's 63/64 gas forward rule ok := staticcall(gas, _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)); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./AppStorage.sol"; import "../acl/ACLSyntaxSugar.sol"; import "../common/Autopetrified.sol"; import "../common/ConversionHelpers.sol"; import "../common/ReentrancyGuard.sol"; import "../common/VaultRecoverable.sol"; import "../evmscript/EVMScriptRunner.sol"; // 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 } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../common/UnstructuredStorage.sol"; import "../kernel/IKernel.sol"; 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); } } /* * SPDX-License-Identifier: 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) } } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../acl/IACL.sol"; import "../common/IVaultRecoverable.sol"; 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); } /* * SPDX-License-Identifier: 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); } /* * SPDX-License-Identifier: 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); } /* * SPDX-License-Identifier: 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)); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./Petrifiable.sol"; 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(); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./Initializable.sol"; 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); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./TimeHelpers.sol"; import "./UnstructuredStorage.sol"; 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); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./Uint256Helpers.sol"; 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(); } } 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); } } 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) } } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../common/UnstructuredStorage.sol"; 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); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../lib/token/ERC20.sol"; import "./EtherTokenConstant.sol"; import "./IsContract.sol"; import "./IVaultRecoverable.sol"; import "./SafeERC20.sol"; 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); } // 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 ); } /* * SPDX-License-Identifier: 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); } /* * SPDX-License-Identifier: 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; } } // 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; import "../lib/token/ERC20.sol"; 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; } /** * @dev Static call into ERC20.totalSupply(). * Reverts if the call fails for some reason (should never fail). */ function staticTotalSupply(ERC20 _token) internal view returns (uint256) { bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector); (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return totalSupply; } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./IEVMScriptExecutor.sol"; import "./IEVMScriptRegistry.sol"; import "../apps/AppStorage.sol"; import "../kernel/KernelConstants.sol"; import "../common/Initializable.sol"; 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); } } /* * SPDX-License-Identifier: 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); } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "./IEVMScriptExecutor.sol"; 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); } /* * SPDX-License-Identifier: 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; } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } pragma solidity 0.4.24; import "./IKernel.sol"; import "./KernelConstants.sol"; import "./KernelStorage.sol"; import "../acl/IACL.sol"; import "../acl/ACLSyntaxSugar.sol"; import "../common/ConversionHelpers.sol"; import "../common/IsContract.sol"; import "../common/Petrifiable.sol"; import "../common/VaultRecoverable.sol"; import "../factory/AppProxyFactory.sol"; import "../lib/misc/ERCProxy.sol"; // 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 ); _; } } pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } pragma solidity 0.4.24; import "../apps/AppProxyUpgradeable.sol"; import "../apps/AppProxyPinned.sol"; 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; } } pragma solidity 0.4.24; import "./AppProxyBase.sol"; 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; } } pragma solidity 0.4.24; import "./AppStorage.sol"; import "../common/DepositableDelegateProxy.sol"; import "../kernel/KernelConstants.sol"; import "../kernel/IKernel.sol"; 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); } } pragma solidity 0.4.24; import "./DelegateProxy.sol"; import "./DepositableStorage.sol"; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { uint256 forwardGasThreshold = FWD_GAS_LIMIT; bytes32 isDepositablePosition = DEPOSITABLE_POSITION; // Optimized assembly implementation to prevent EIP-1884 from breaking deposits, reference code in Solidity: // https://github.com/aragon/aragonOS/blob/v4.2.1/contracts/common/DepositableDelegateProxy.sol#L10-L20 assembly { // Continue only if the gas left is lower than the threshold for forwarding to the implementation code, // otherwise continue outside of the assembly block. if lt(gas, forwardGasThreshold) { // Only accept the deposit and emit an event if all of the following are true: // the proxy accepts deposits (isDepositable), msg.data.length == 0, and msg.value > 0 if and(and(sload(isDepositablePosition), iszero(calldatasize)), gt(callvalue, 0)) { // Equivalent Solidity code for emitting the event: // emit ProxyDeposit(msg.sender, msg.value); let logData := mload(0x40) // free memory pointer mstore(logData, caller) // add 'msg.sender' to the log data (first event param) mstore(add(logData, 0x20), callvalue) // add 'msg.value' to the log data (second event param) // Emit an event with one topic to identify the event: keccak256('ProxyDeposit(address,uint256)') = 0x15ee...dee1 log1(logData, 0x40, 0x15eeaa57c7bd188c1388020bcadc2c436ec60d647d36ef5b9eb3c742217ddee1) stop() // Stop. Exits execution context } // If any of above checks failed, revert the execution (if ETH was sent, it is returned to the sender) revert(0, 0) } } address target = implementation(); delegatedFwd(target, msg.data); } } pragma solidity 0.4.24; import "../common/IsContract.sol"; import "../lib/misc/ERCProxy.sol"; 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) } } } } /* * SPDX-License-Identifier: 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); } pragma solidity 0.4.24; import "./UnstructuredStorage.sol"; 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); } } pragma solidity 0.4.24; import "../common/UnstructuredStorage.sol"; import "../common/IsContract.sol"; import "./AppProxyBase.sol"; 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(); } } pragma solidity 0.4.24; import "../kernel/IKernel.sol"; import "../kernel/Kernel.sol"; import "../kernel/KernelProxy.sol"; import "../acl/IACL.sol"; import "../acl/ACL.sol"; import "./EVMScriptRegistryFactory.sol"; 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; } } pragma solidity 0.4.24; import "./IKernel.sol"; import "./KernelConstants.sol"; import "./KernelStorage.sol"; import "../common/DepositableDelegateProxy.sol"; import "../common/IsContract.sol"; 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]; } } pragma solidity 0.4.24; import "../evmscript/IEVMScriptExecutor.sol"; import "../evmscript/EVMScriptRegistry.sol"; import "../evmscript/executors/CallsScript.sol"; import "../kernel/Kernel.sol"; import "../acl/ACL.sol"; 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; } } pragma solidity 0.4.24; import "../apps/AragonApp.sol"; import "./ScriptHelpers.sol"; import "./IEVMScriptExecutor.sol"; import "./IEVMScriptRegistry.sol"; /* 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); } } /* * SPDX-License-Identifier: 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; } } pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager import "../ScriptHelpers.sol"; import "./BaseEVMScriptExecutor.sol"; 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; } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; import "../../common/Autopetrified.sol"; import "../IEVMScriptExecutor.sol"; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } pragma solidity 0.4.24; import "../apm/APMRegistry.sol"; import "../apm/Repo.sol"; import "../ens/ENSSubdomainRegistrar.sol"; import "./DAOFactory.sol"; import "./ENSFactory.sol"; import "./AppProxyFactory.sol"; contract APMRegistryFactory is APMInternalAppNames { DAOFactory public daoFactory; APMRegistry public registryBase; Repo public repoBase; ENSSubdomainRegistrar public ensSubdomainRegistrarBase; ENS public ens; event DeployAPM(bytes32 indexed node, address apm); /** * @notice Create a new factory for deploying Aragon Package Managers (aragonPM) * @dev Requires either a given ENS registrar or ENSFactory (used for generating a new ENS in test environments). * @param _daoFactory Base factory for deploying DAOs * @param _registryBase APMRegistry base contract location * @param _repoBase Repo base contract location * @param _ensSubBase ENSSubdomainRegistrar base contract location * @param _ens ENS instance * @param _ensFactory ENSFactory (used to generated a new ENS if no ENS is given) */ constructor( DAOFactory _daoFactory, APMRegistry _registryBase, Repo _repoBase, ENSSubdomainRegistrar _ensSubBase, ENS _ens, ENSFactory _ensFactory ) public // DAO initialized without evmscript run support { daoFactory = _daoFactory; registryBase = _registryBase; repoBase = _repoBase; ensSubdomainRegistrarBase = _ensSubBase; // Either the ENS address provided is used, if any. // Or we use the ENSFactory to generate a test instance of ENS // If not the ENS address nor factory address are provided, this will revert ens = _ens != address(0) ? _ens : _ensFactory.newENS(this); } /** * @notice Create a new Aragon Package Manager (aragonPM) DAO, holding the `_label` subdomain from parent `_tld` and controlled by `_root` * @param _tld The parent node of the controlled subdomain * @param _label The subdomain label * @param _root Manager for the new aragonPM DAO * @return The new aragonPM's APMRegistry app */ function newAPM(bytes32 _tld, bytes32 _label, address _root) public returns (APMRegistry) { bytes32 node = keccak256(abi.encodePacked(_tld, _label)); // Assume it is the test ENS if (ens.owner(node) != address(this)) { // If we weren't in test ens and factory doesn't have ownership, will fail require(ens.owner(_tld) == address(this)); ens.setSubnodeOwner(_tld, _label, this); } Kernel dao = daoFactory.newDAO(this); ACL acl = ACL(dao.acl()); acl.createPermission(this, dao, dao.APP_MANAGER_ROLE(), this); // Deploy app proxies bytes memory noInit = new bytes(0); ENSSubdomainRegistrar ensSub = ENSSubdomainRegistrar( dao.newAppInstance( keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(ENS_SUB_APP_NAME)))), ensSubdomainRegistrarBase, noInit, false ) ); APMRegistry apm = APMRegistry( dao.newAppInstance( keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(APM_APP_NAME)))), registryBase, noInit, false ) ); // APMRegistry controls Repos bytes32 repoAppId = keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(REPO_APP_NAME)))); dao.setApp(dao.APP_BASES_NAMESPACE(), repoAppId, repoBase); emit DeployAPM(node, apm); // Grant permissions needed for APM on ENSSubdomainRegistrar acl.createPermission(apm, ensSub, ensSub.CREATE_NAME_ROLE(), _root); acl.createPermission(apm, ensSub, ensSub.POINT_ROOTNODE_ROLE(), _root); // allow apm to create permissions for Repos in Kernel bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); acl.grantPermission(apm, acl, permRole); // Initialize ens.setOwner(node, ensSub); ensSub.initialize(ens, node); apm.initialize(ensSub); uint16[3] memory firstVersion; firstVersion[0] = 1; acl.createPermission(this, apm, apm.CREATE_REPO_ROLE(), this); apm.newRepoWithVersion(APM_APP_NAME, _root, firstVersion, registryBase, b("ipfs:apm")); apm.newRepoWithVersion(ENS_SUB_APP_NAME, _root, firstVersion, ensSubdomainRegistrarBase, b("ipfs:enssub")); apm.newRepoWithVersion(REPO_APP_NAME, _root, firstVersion, repoBase, b("ipfs:repo")); configureAPMPermissions(acl, apm, _root); // Permission transition to _root acl.setPermissionManager(_root, dao, dao.APP_MANAGER_ROLE()); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); return apm; } function b(string memory x) internal pure returns (bytes memory y) { y = bytes(x); } // Factory can be subclassed and permissions changed function configureAPMPermissions(ACL _acl, APMRegistry _apm, address _root) internal { _acl.grantPermission(_root, _apm, _apm.CREATE_REPO_ROLE()); _acl.setPermissionManager(_root, _apm, _apm.CREATE_REPO_ROLE()); } } pragma solidity 0.4.24; import "../lib/ens/AbstractENS.sol"; import "../ens/ENSSubdomainRegistrar.sol"; import "../factory/AppProxyFactory.sol"; import "../apps/AragonApp.sol"; import "../acl/ACL.sol"; import "./Repo.sol"; contract APMInternalAppNames { string internal constant APM_APP_NAME = "apm-registry"; string internal constant REPO_APP_NAME = "apm-repo"; string internal constant ENS_SUB_APP_NAME = "apm-enssub"; } contract APMRegistry is AragonApp, AppProxyFactory, APMInternalAppNames { /* Hardcoded constants to save gas bytes32 public constant CREATE_REPO_ROLE = keccak256("CREATE_REPO_ROLE"); */ bytes32 public constant CREATE_REPO_ROLE = 0x2a9494d64846c9fdbf0158785aa330d8bc9caf45af27fa0e8898eb4d55adcea6; string private constant ERROR_INIT_PERMISSIONS = "APMREG_INIT_PERMISSIONS"; string private constant ERROR_EMPTY_NAME = "APMREG_EMPTY_NAME"; AbstractENS public ens; ENSSubdomainRegistrar public registrar; event NewRepo(bytes32 id, string name, address repo); /** * NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar * @dev Initialize can only be called once. It saves the block number in which it was initialized * @notice Initialize this APMRegistry instance and set `_registrar` as the ENS subdomain registrar * @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership */ function initialize(ENSSubdomainRegistrar _registrar) public onlyInit { initialized(); registrar = _registrar; ens = registrar.ens(); registrar.pointRootNode(this); // Check APM has all permissions it needss ACL acl = ACL(kernel().acl()); require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE()), ERROR_INIT_PERMISSIONS); require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE()), ERROR_INIT_PERMISSIONS); } /** * @notice Create new repo in registry with `_name` * @param _name Repo name, must be ununsed * @param _dev Address that will be given permission to create versions */ function newRepo(string _name, address _dev) public auth(CREATE_REPO_ROLE) returns (Repo) { return _newRepo(_name, _dev); } /** * @notice Create new repo in registry with `_name` and publish a first version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _name Repo name * @param _dev Address that will be given permission to create versions * @param _initialSemanticVersion 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 newRepoWithVersion( string _name, address _dev, uint16[3] _initialSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_REPO_ROLE) returns (Repo) { Repo repo = _newRepo(_name, this); // need to have permissions to create version repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI); // Give permissions to _dev ACL acl = ACL(kernel().acl()); acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE()); acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE()); acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE()); return repo; } function _newRepo(string _name, address _dev) internal returns (Repo) { require(bytes(_name).length > 0, ERROR_EMPTY_NAME); Repo repo = newClonedRepo(); ACL(kernel().acl()).createPermission(_dev, repo, repo.CREATE_VERSION_ROLE(), _dev); // Creates [name] subdomain in the rootNode and sets registry as resolver // This will fail if repo name already exists bytes32 node = registrar.createNameAndPoint(keccak256(abi.encodePacked(_name)), repo); emit NewRepo(node, _name, repo); return repo; } function newClonedRepo() internal returns (Repo repo) { repo = Repo(newAppProxy(kernel(), repoAppId())); repo.initialize(); } function repoAppId() internal view returns (bytes32) { return keccak256(abi.encodePacked(registrar.rootNode(), keccak256(abi.encodePacked(REPO_APP_NAME)))); } } // 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); } pragma solidity 0.4.24; import "../lib/ens/AbstractENS.sol"; import "../lib/ens/PublicResolver.sol"; import "./ENSConstants.sol"; import "../apps/AragonApp.sol"; /* solium-disable function-order */ // Allow public initialize() to be first contract ENSSubdomainRegistrar is AragonApp, ENSConstants { /* Hardcoded constants to save gas bytes32 public constant CREATE_NAME_ROLE = keccak256("CREATE_NAME_ROLE"); bytes32 public constant DELETE_NAME_ROLE = keccak256("DELETE_NAME_ROLE"); bytes32 public constant POINT_ROOTNODE_ROLE = keccak256("POINT_ROOTNODE_ROLE"); */ bytes32 public constant CREATE_NAME_ROLE = 0xf86bc2abe0919ab91ef714b2bec7c148d94f61fdb069b91a6cfe9ecdee1799ba; bytes32 public constant DELETE_NAME_ROLE = 0x03d74c8724218ad4a99859bcb2d846d39999449fd18013dd8d69096627e68622; bytes32 public constant POINT_ROOTNODE_ROLE = 0x9ecd0e7bddb2e241c41b595a436c4ea4fd33c9fa0caa8056acf084fc3aa3bfbe; string private constant ERROR_NO_NODE_OWNERSHIP = "ENSSUB_NO_NODE_OWNERSHIP"; string private constant ERROR_NAME_EXISTS = "ENSSUB_NAME_EXISTS"; string private constant ERROR_NAME_DOESNT_EXIST = "ENSSUB_DOESNT_EXIST"; AbstractENS public ens; bytes32 public rootNode; event NewName(bytes32 indexed node, bytes32 indexed label); event DeleteName(bytes32 indexed node, bytes32 indexed label); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. This contract must be the owner of the `_rootNode` node so that it can create subdomains. * @notice Initialize this ENSSubdomainRegistrar instance with `_ens` as the root ENS registry and `_rootNode` as the node to allocate subdomains under * @param _ens Address of ENS registry * @param _rootNode Node to allocate subdomains under */ function initialize(AbstractENS _ens, bytes32 _rootNode) public onlyInit { initialized(); // We need ownership to create subnodes require(_ens.owner(_rootNode) == address(this), ERROR_NO_NODE_OWNERSHIP); ens = _ens; rootNode = _rootNode; } /** * @notice Create a new ENS subdomain record for `_label` and assign ownership to `_owner` * @param _label Label of new subdomain * @param _owner Owner of new subdomain * @return node Hash of created node */ function createName(bytes32 _label, address _owner) external auth(CREATE_NAME_ROLE) returns (bytes32 node) { return _createName(_label, _owner); } /** * @notice Create a new ENS subdomain record for `_label` that resolves to `_target` and is owned by this ENSSubdomainRegistrar * @param _label Label of new subdomain * @param _target Ethereum address this new subdomain label will point to * @return node Hash of created node */ function createNameAndPoint(bytes32 _label, address _target) external auth(CREATE_NAME_ROLE) returns (bytes32 node) { node = _createName(_label, this); _pointToResolverAndResolve(node, _target); } /** * @notice Deregister ENS subdomain record for `_label` * @param _label Label of subdomain to deregister */ function deleteName(bytes32 _label) external auth(DELETE_NAME_ROLE) { bytes32 node = getNodeForLabel(_label); address currentOwner = ens.owner(node); require(currentOwner != address(0), ERROR_NAME_DOESNT_EXIST); // fail if deleting unset name if (currentOwner != address(this)) { // needs to reclaim ownership so it can set resolver ens.setSubnodeOwner(rootNode, _label, this); } ens.setResolver(node, address(0)); // remove resolver so it ends resolving ens.setOwner(node, address(0)); emit DeleteName(node, _label); } /** * @notice Resolve this ENSSubdomainRegistrar's root node to `_target` * @param _target Ethereum address root node will point to */ function pointRootNode(address _target) external auth(POINT_ROOTNODE_ROLE) { _pointToResolverAndResolve(rootNode, _target); } function _createName(bytes32 _label, address _owner) internal returns (bytes32 node) { node = getNodeForLabel(_label); require(ens.owner(node) == address(0), ERROR_NAME_EXISTS); // avoid name reset ens.setSubnodeOwner(rootNode, _label, _owner); emit NewName(node, _label); return node; } function _pointToResolverAndResolve(bytes32 _node, address _target) internal { address publicResolver = getAddr(PUBLIC_RESOLVER_NODE); ens.setResolver(_node, publicResolver); PublicResolver(publicResolver).setAddr(_node, _target); } function getAddr(bytes32 node) internal view returns (address) { address resolver = ens.resolver(node); return PublicResolver(resolver).addr(node); } function getNodeForLabel(bytes32 _label) internal view returns (bytes32) { return keccak256(abi.encodePacked(rootNode, _label)); } } // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; import "./AbstractENS.sol"; /** * 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); } } /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ENSConstants { /* Hardcoded constants to save gas bytes32 internal constant ENS_ROOT = bytes32(0); bytes32 internal constant ETH_TLD_LABEL = keccak256("eth"); bytes32 internal constant ETH_TLD_NODE = keccak256(abi.encodePacked(ENS_ROOT, ETH_TLD_LABEL)); bytes32 internal constant PUBLIC_RESOLVER_LABEL = keccak256("resolver"); bytes32 internal constant PUBLIC_RESOLVER_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL)); */ bytes32 internal constant ENS_ROOT = bytes32(0); bytes32 internal constant ETH_TLD_LABEL = 0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0; bytes32 internal constant ETH_TLD_NODE = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae; bytes32 internal constant PUBLIC_RESOLVER_LABEL = 0x329539a1d23af1810c48a07fe7fc66a3b34fbc8b37e9b3cdb97bb88ceab7e4bf; bytes32 internal constant PUBLIC_RESOLVER_NODE = 0xfdd5d5de6dd63db72bbc2d487944ba13bf775b50a80805fe6fcaba9b0fba88f5; } pragma solidity 0.4.24; import "../apps/AragonApp.sol"; /* 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])); } } pragma solidity 0.4.24; import "../lib/ens/ENS.sol"; import "../lib/ens/PublicResolver.sol"; import "../ens/ENSConstants.sol"; // WARNING: This is an incredibly trustful ENS deployment, do NOT use in production! // This contract is NOT meant to be deployed to a live network. // Its only purpose is to easily create ENS instances for testing aragonPM. contract ENSFactory is ENSConstants { event DeployENS(address ens); /** * @notice Create a new ENS and set `_owner` as the owner of the top level domain. * @param _owner Owner of .eth * @return ENS */ function newENS(address _owner) public returns (ENS) { ENS ens = new ENS(); // Setup .eth TLD ens.setSubnodeOwner(ENS_ROOT, ETH_TLD_LABEL, this); // Setup public resolver PublicResolver resolver = new PublicResolver(ens); ens.setSubnodeOwner(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL, this); ens.setResolver(PUBLIC_RESOLVER_NODE, resolver); resolver.setAddr(PUBLIC_RESOLVER_NODE, resolver); ens.setOwner(ETH_TLD_NODE, _owner); ens.setOwner(ENS_ROOT, _owner); emit DeployENS(ens); return ens; } } // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; import "./AbstractENS.sol"; /** * 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; } } // Modified from https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/StandardToken.sol pragma solidity 0.4.24; import "@aragon/os/contracts/lib/math/SafeMath.sol"; contract TokenMock { using SafeMath for uint256; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; uint256 private totalSupply_; bool private allowTransfer_; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); // Allow us to set the inital balance for an account on construction constructor(address initialAccount, uint256 initialBalance) public { balances[initialAccount] = initialBalance; totalSupply_ = initialBalance; allowTransfer_ = true; } 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 Set whether the token is transferable or not * @param _allowTransfer Should token be transferable */ function setAllowTransfer(bool _allowTransfer) public { allowTransfer_ = _allowTransfer; } /** * @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(allowTransfer_); require(_value <= balances[msg.sender]); require(_to != address(0)); 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) { // Assume we want to protect for the race condition require(allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(allowTransfer_); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); 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; } } // 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; } } pragma solidity ^0.4.24; import "@aragon/os/contracts/lib/math/SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken { using SafeMath for uint256; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal supply; string public name; string public symbol; uint8 public decimals; constructor( string _name, string _symbol, uint8 _decimals, uint256 _totalSupply ) public { supply = _totalSupply; // Update total supply name = _name; // Set the id for reference symbol = _symbol; decimals = _decimals; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); // Transfer event indicating token creation } /** * @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]); require(_to != address(0)); 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]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); 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 Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return supply; } /** * @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]; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity 0.4.24; import "@1hive/apps-dandelion-voting/contracts/DandelionVoting.sol"; // NOTE: used because truffle does not support function overloading contract VotingMock is DandelionVoting { function newVoteExt( bytes _executionScript, string _metadata, bool _castVote ) external returns (uint256) { return _newVote(_executionScript, _metadata, _castVote); } } /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; import "@aragon/os/contracts/apps/AragonApp.sol"; import "@aragon/os/contracts/common/IForwarder.sol"; import "@aragon/os/contracts/acl/IACLOracle.sol"; import "@aragon/os/contracts/lib/math/SafeMath.sol"; import "@aragon/os/contracts/lib/math/SafeMath64.sol"; import "@aragon/apps-shared-minime/contracts/MiniMeToken.sol"; contract DandelionVoting is IForwarder, IACLOracle, 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"); bytes32 public constant MODIFY_BUFFER_BLOCKS_ROLE = keccak256("MODIFY_BUFFER_BLOCKS_ROLE"); bytes32 public constant MODIFY_EXECUTION_DELAY_ROLE = keccak256("MODIFY_EXECUTION_DELAY_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint8 private constant EXECUTION_PERIOD_FALLBACK_DIVISOR = 2; string private constant ERROR_VOTE_ID_ZERO = "DANDELION_VOTING_VOTE_ID_ZERO"; string private constant ERROR_NO_VOTE = "DANDELION_VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "DANDELION_VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "DANDELION_VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "DANDELION_VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "DANDELION_VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "DANDELION_VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "DANDELION_VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "DANDELION_VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "DANDELION_VOTING_CAN_NOT_FORWARD"; string private constant ERROR_ORACLE_SENDER_MISSING = "DANDELION_VOTING_ORACLE_SENDER_MISSING"; string private constant ERROR_ORACLE_SENDER_TOO_BIG = "DANDELION_VOTING_ORACLE_SENDER_TOO_BIG"; string private constant ERROR_ORACLE_SENDER_ZERO = "DANDELION_VOTING_ORACLE_SENDER_ZERO"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startBlock; uint64 executionBlock; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public durationBlocks; uint64 public bufferBlocks; uint64 public executionDelayBlocks; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; mapping (address => uint256) public latestYeaVoteId; 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); event ChangeBufferBlocks(uint64 bufferBlocks); event ChangeExecutionDelayBlocks(uint64 executionDelayBlocks); modifier voteExists(uint256 _voteId) { require(_voteId != 0, ERROR_VOTE_ID_ZERO); 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)`%, a voting duration of `_voteDurationBlocks` blocks, and a vote buffer of `_voteBufferBlocks` blocks * @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 _durationBlocks Blocks that a vote will be open for token holders to vote * @param _bufferBlocks Minimum number of blocks between the start block of each vote * @param _executionDelayBlocks Minimum number of blocks between the end of a vote and when it can be executed */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _durationBlocks, uint64 _bufferBlocks, uint64 _executionDelayBlocks ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; durationBlocks = _durationBlocks; bufferBlocks = _bufferBlocks; executionDelayBlocks = _executionDelayBlocks; } /** * @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 Change vote buffer to `_voteBufferBlocks` blocks * @param _bufferBlocks New vote buffer defined in blocks */ function changeBufferBlocks(uint64 _bufferBlocks) external auth(MODIFY_BUFFER_BLOCKS_ROLE) { bufferBlocks = _bufferBlocks; emit ChangeBufferBlocks(_bufferBlocks); } /** * @notice Change execution delay to `_executionDelayBlocks` blocks * @param _executionDelayBlocks New vote execution delay defined in blocks */ function changeExecutionDelayBlocks(uint64 _executionDelayBlocks) external auth(MODIFY_EXECUTION_DELAY_ROLE) { executionDelayBlocks = _executionDelayBlocks; emit ChangeExecutionDelayBlocks(_executionDelayBlocks); } /** * @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 * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote); } /** * @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 */ function vote(uint256 _voteId, bool _supports) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender); } /** * @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 { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); 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); } // Forwarding fns /** * @notice Returns whether the Voting app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ 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); } /** * @notice Returns 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 create votes, false otherwise */ 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()); } // ACL Oracle fns /** * @notice Returns whether the sender has voted on the most recent open vote or closed unexecuted vote. * @dev IACLOracle interface conformance. The ACLOracle permissioned function should specify the sender * with 'authP(SOME_ACL_ROLE, arr(sender))', where sender is typically set to 'msg.sender'. * @param _how Array passed by Kernel when using 'authP()'. First item should be the address to check can perform. * return False if the sender has voted on the most recent open vote or closed unexecuted vote, true if they haven't. */ function canPerform(address, address, bytes32, uint256[] _how) external view returns (bool) { if (votesLength == 0) { return true; } require(_how.length > 0, ERROR_ORACLE_SENDER_MISSING); require(_how[0] < 2**160, ERROR_ORACLE_SENDER_TOO_BIG); require(_how[0] != 0, ERROR_ORACLE_SENDER_ZERO); address sender = address(_how[0]); uint256 senderLatestYeaVoteId = latestYeaVoteId[sender]; Vote storage senderLatestYeaVote_ = votes[senderLatestYeaVoteId]; uint64 blockNumber = getBlockNumber64(); bool senderLatestYeaVoteFailed = !_votePassed(senderLatestYeaVote_); bool senderLatestYeaVoteExecutionBlockPassed = blockNumber >= senderLatestYeaVote_.executionBlock; uint64 fallbackPeriodLength = bufferBlocks / EXECUTION_PERIOD_FALLBACK_DIVISOR; bool senderLatestYeaVoteFallbackPeriodPassed = blockNumber > senderLatestYeaVote_.executionBlock.add(fallbackPeriodLength); return senderLatestYeaVoteFailed && senderLatestYeaVoteExecutionBlockPassed || senderLatestYeaVote_.executed || senderLatestYeaVoteFallbackPeriodPassed; } // Getter fns /** * @notice Tells whether a vote #`_voteId` can be executed or not * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @return True if the given vote can be executed, false otherwise */ function canExecute(uint256 _voteId) public view returns (bool) { return _canExecute(_voteId); } /** * @notice Tells whether `_sender` can participate in the vote #`_voteId` or not * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @return True if the given voter can participate a certain vote, false otherwise */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } /** * @dev Return all information for a vote by its ID * @param _voteId Vote identifier * @return Vote open status * @return Vote executed status * @return Vote start block * @return Vote snapshot block * @return Vote support required * @return Vote minimum acceptance quorum * @return Vote yeas amount * @return Vote nays amount * @return Vote power * @return Vote script */ function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startBlock, uint64 executionBlock, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 votingPower, uint256 yea, uint256 nay, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startBlock = vote_.startBlock; executionBlock = vote_.executionBlock; snapshotBlock = vote_.snapshotBlock; votingPower = token.totalSupplyAt(vote_.snapshotBlock); supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; script = vote_.executionScript; } /** * @dev Return the state of a voter for a given vote by its ID * @param _voteId Vote identifier * @return VoterState of the requested voter for a certain vote */ function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns /** * @dev Internal function to create a new vote * @return voteId id for newly created vote */ function _newVote(bytes _executionScript, string _metadata, bool _castVote) internal returns (uint256 voteId) { voteId = ++votesLength; // Increment votesLength before assigning to votedId. The first voteId is 1. uint64 previousVoteStartBlock = votes[voteId - 1].startBlock; uint64 earliestStartBlock = previousVoteStartBlock == 0 ? 0 : previousVoteStartBlock.add(bufferBlocks); uint64 startBlock = earliestStartBlock < getBlockNumber64() ? getBlockNumber64() : earliestStartBlock; uint64 executionBlock = startBlock.add(durationBlocks).add(executionDelayBlocks); Vote storage vote_ = votes[voteId]; vote_.startBlock = startBlock; vote_.executionBlock = executionBlock; vote_.snapshotBlock = startBlock - 1; // avoid double voting in this very block vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender); } } /** * @dev Internal function to cast a vote. It assumes the queried vote exists. */ function _vote(uint256 _voteId, bool _supports, address _voter) internal { Vote storage vote_ = votes[_voteId]; uint256 voterStake = _voterStake(vote_, _voter); if (_supports) { vote_.yea = vote_.yea.add(voterStake); if (latestYeaVoteId[_voter] < _voteId) { latestYeaVoteId[_voter] = _voteId; } } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); } /** * @dev Internal function to check if a vote can be executed. It assumes the queried vote exists. * @return True if the given vote can be executed, false otherwise */ function _canExecute(uint256 _voteId) internal view voteExists(_voteId) returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // This will always be later than the end of the previous vote if (getBlockNumber64() < vote_.executionBlock) { return false; } return _votePassed(vote_); } /** * @dev Internal function to check if a vote has passed. It assumes the vote period has passed. * @return True if the given vote has passed, false otherwise. */ function _votePassed(Vote storage vote_) internal view returns (bool) { uint256 totalVotes = vote_.yea.add(vote_.nay); uint256 votingPowerAtSnapshot = token.totalSupplyAt(vote_.snapshotBlock); bool hasSupportRequired = _isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct); bool hasMinQuorum = _isValuePct(vote_.yea, votingPowerAtSnapshot, vote_.minAcceptQuorumPct); return hasSupportRequired && hasMinQuorum; } /** * @dev Internal function to check if a voter can participate on a vote. It assumes the queried vote exists. * @return True if the given voter can participate a certain vote, false otherwise */ function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; uint256 voterStake = _voterStake(vote_, _voter); bool hasNotVoted = vote_.voters[_voter] == VoterState.Absent; return _isVoteOpen(vote_) && voterStake > 0 && hasNotVoted; } /** * @dev Internal function to determine a voters stake which is the minimum of snapshot balance and current balance. * @return Voters current stake. */ function _voterStake(Vote storage vote_, address _voter) internal view returns (uint256) { uint256 balanceAtSnapshot = token.balanceOfAt(_voter, vote_.snapshotBlock); uint256 currentBalance = token.balanceOf(_voter); return balanceAtSnapshot < currentBalance ? balanceAtSnapshot : currentBalance; } /** * @dev Internal function to check if a vote is still open * @return True if the given vote is open, false otherwise */ function _isVoteOpen(Vote storage vote_) internal view returns (bool) { uint256 votingPowerAtSnapshot = token.totalSupplyAt(vote_.snapshotBlock); uint64 blockNumber = getBlockNumber64(); return votingPowerAtSnapshot > 0 && blockNumber >= vote_.startBlock && blockNumber < vote_.startBlock.add(durationBlocks); } /** * @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; } } /* * SPDX-License-Identifier: 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; } // 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; } } 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. import "./ITokenController.sol"; contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; 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; } } 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); } pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "@aragon/os/contracts/apps/AragonApp.sol"; import "@aragon/os/contracts/common/SafeERC20.sol"; import "@aragon/os/contracts/lib/token/ERC20.sol"; import "@1hive/apps-dandelion-voting/contracts/DandelionVoting.sol"; import "@aragon/apps-vault/contracts/Vault.sol"; import "@aragon/os/contracts/lib/math/SafeMath.sol"; import "@aragon/os/contracts/lib/math/SafeMath64.sol"; import "@aragon/apps-shared-minime/contracts/MiniMeToken.sol"; contract VotingRewards is AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CHANGE_EPOCH_DURATION_ROLE = keccak256("CHANGE_EPOCH_DURATION_ROLE"); bytes32 public constant CHANGE_LOCK_TIME_ROLE = keccak256("CHANGE_LOCK_TIME_ROLE"); bytes32 public constant CHANGE_MISSING_VOTES_THRESHOLD_ROLE = keccak256("CHANGE_MISSING_VOTES_THRESHOLD_ROLE"); bytes32 public constant OPEN_REWARDS_DISTRIBUTION_ROLE = keccak256("OPEN_REWARDS_DISTRIBUTION_ROLE"); bytes32 public constant CLOSE_REWARDS_DISTRIBUTION_ROLE = keccak256("CLOSE_REWARDS_DISTRIBUTION_ROLE"); bytes32 public constant DISTRIBUTE_REWARDS_ROLE = keccak256("DISTRIBUTE_REWARDS_ROLE"); bytes32 public constant CHANGE_PERCENTAGE_REWARDS_ROLE = keccak256("CHANGE_PERCENTAGE_REWARDS_ROLE"); bytes32 public constant CHANGE_VAULT_ROLE = keccak256("CHANGE_VAULT_ROLE"); bytes32 public constant CHANGE_REWARDS_TOKEN_ROLE = keccak256("CHANGE_REWARDS_TOKEN_ROLE"); bytes32 public constant CHANGE_VOTING_ROLE = keccak256("CHANGE_VOTING_ROLE"); uint64 public constant PCT_BASE = 10**18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_ADDRESS_NOT_CONTRACT = "VOTING_REWARDS_ADDRESS_NOT_CONTRACT"; string private constant ERROR_EPOCH = "VOTING_REWARDS_ERROR_EPOCH"; string private constant ERROR_PERCENTAGE_REWARDS = "VOTING_REWARDS_ERROR_PERCENTAGE_REWARDS"; // prettier-ignore string private constant ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED = "VOTING_REWARDS_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED"; // prettier-ignore string private constant ERROR_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED = "VOTING_REWARDS_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED"; string private constant ERROR_NO_REWARDS = "VOTING_REWARDS_NO_REWARDS"; struct Reward { uint256 amount; uint64 lockBlock; uint64 lockTime; } Vault public baseVault; Vault public rewardsVault; DandelionVoting public dandelionVoting; address public rewardsToken; uint256 public percentageRewards; uint256 public missingVotesThreshold; uint64 public epochDuration; uint64 public currentEpoch; uint64 public startBlockNumberOfCurrentEpoch; uint64 public lockTime; uint64 public lastRewardsDistributionBlock; uint64 private deployBlock; bool public isDistributionOpen; // NOTE: previousRewardsDistributionBlockNumber kept even if not used so as not to break the proxy contract storage after an upgrade mapping(address => uint64) private previousRewardsDistributionBlockNumber; mapping(address => Reward[]) public addressUnlockedRewards; mapping(address => Reward[]) public addressWithdrawnRewards; // kept even if not used so as not to break the proxy contract storage after an upgrade event BaseVaultChanged(address baseVault); event RewardsVaultChanged(address rewardsVault); event DandelionVotingChanged(address dandelionVoting); event PercentageRewardsChanged(uint256 percentageRewards); event RewardDistributed(address indexed beneficiary, uint256 indexed amount, uint64 lockTime); event RewardCollected(address indexed beneficiary, uint256 amount, uint64 indexed lockBlock, uint64 lockTime); event EpochDurationChanged(uint64 epochDuration); event MissingVoteThresholdChanged(uint256 missingVotesThreshold); event LockTimeChanged(uint64 lockTime); event RewardsDistributionEpochOpened(uint64 startBlock, uint64 endBlock); event RewardsDistributionEpochClosed(uint64 rewardDistributionBlock); event RewardsTokenChanged(address rewardsToken); /** * @notice Initialize VotingRewards app contract * @param _baseVault Vault address from which token are taken * @param _rewardsVault Vault address to which token are put * @param _rewardsToken Accepted token address * @param _epochDuration number of blocks for which an epoch is opened * @param _percentageRewards percentage of a reward expressed as a number between 10^16 and 10^18 * @param _lockTime number of blocks for which token will be locked after colleting reward * @param _missingVotesThreshold number of missing votes allowed in an epoch */ function initialize( address _baseVault, address _rewardsVault, address _dandelionVoting, address _rewardsToken, uint64 _epochDuration, uint256 _percentageRewards, uint64 _lockTime, uint256 _missingVotesThreshold ) external onlyInit { require(isContract(_baseVault), ERROR_ADDRESS_NOT_CONTRACT); require(isContract(_rewardsVault), ERROR_ADDRESS_NOT_CONTRACT); require(isContract(_dandelionVoting), ERROR_ADDRESS_NOT_CONTRACT); require(isContract(_rewardsToken), ERROR_ADDRESS_NOT_CONTRACT); require(_percentageRewards <= PCT_BASE, ERROR_PERCENTAGE_REWARDS); baseVault = Vault(_baseVault); rewardsVault = Vault(_rewardsVault); dandelionVoting = DandelionVoting(_dandelionVoting); rewardsToken = _rewardsToken; epochDuration = _epochDuration; percentageRewards = _percentageRewards; missingVotesThreshold = _missingVotesThreshold; lockTime = _lockTime; deployBlock = getBlockNumber64(); lastRewardsDistributionBlock = getBlockNumber64(); currentEpoch = 0; initialized(); } /** * @notice Open the distribution for the current epoch from _fromBlock * @param _fromBlock block from which starting to look for rewards */ function openRewardsDistributionForEpoch(uint64 _fromBlock) external auth(OPEN_REWARDS_DISTRIBUTION_ROLE) { require(!isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_ALREADY_OPENED); require(_fromBlock > lastRewardsDistributionBlock, ERROR_EPOCH); require(getBlockNumber64() - lastRewardsDistributionBlock > epochDuration, ERROR_EPOCH); startBlockNumberOfCurrentEpoch = _fromBlock; isDistributionOpen = true; emit RewardsDistributionEpochOpened(_fromBlock, _fromBlock + epochDuration); } /** * @notice close distribution for thee current epoch if it's opened and starts a new one */ function closeRewardsDistributionForCurrentEpoch() external auth(CLOSE_REWARDS_DISTRIBUTION_ROLE) { require(isDistributionOpen == true, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED); isDistributionOpen = false; currentEpoch = currentEpoch.add(1); lastRewardsDistributionBlock = getBlockNumber64(); emit RewardsDistributionEpochClosed(lastRewardsDistributionBlock); } /** * @notice distribute rewards for a list of address. Tokens are locked for lockTime in rewardsVault * @param _beneficiaries address that are looking for reward * @dev this function should be called from outside each _epochDuration seconds */ function distributeRewardsToMany(address[] _beneficiaries, uint256[] _amount) external auth(DISTRIBUTE_REWARDS_ROLE) returns (bool) { require(isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED); uint256 totalRewardAmount = 0; for (uint256 i = 0; i < _beneficiaries.length; i++) { // NOTE: switching to a semi-trusted solution in order to spend less in gas // _assignUnlockedReward(_beneficiaries[i], _amount[i]); totalRewardAmount = totalRewardAmount.add(_amount[i]); emit RewardDistributed(_beneficiaries[i], _amount[i], lockTime); } baseVault.transfer(rewardsToken, rewardsVault, totalRewardAmount); return true; } /** * @notice Distribute rewards to _beneficiary * @param _beneficiary address to which the deposit will be transferred if successful * @dev baseVault should have TRANSFER_ROLE permission */ function distributeRewardsTo(address _beneficiary, uint256 _amount) external auth(DISTRIBUTE_REWARDS_ROLE) returns (bool) { require(isDistributionOpen, ERROR_EPOCH_REWARDS_DISTRIBUTION_NOT_OPENED); // NOTE: switching to a semi-trusted solution in order to spend less in gas // _assignUnlockedReward(_beneficiary, _amount); baseVault.transfer(rewardsToken, rewardsVault, _amount); emit RewardDistributed(_beneficiary, _amount, lockTime); return true; } /** * @notice collect rewards for a list of address * if lockTime is passed since when tokens have been distributed * @param _beneficiaries addresses that should be fund with rewards */ function collectRewardsForMany(address[] _beneficiaries) external { for (uint256 i = 0; i < _beneficiaries.length; i++) { collectRewardsFor(_beneficiaries[i]); } } /** * @notice Change minimum number of seconds to claim dandelionVoting rewards * @param _epochDuration number of seconds minimum to claim access to dandelionVoting rewards */ function changeEpochDuration(uint64 _epochDuration) external auth(CHANGE_EPOCH_DURATION_ROLE) { require(_epochDuration > 0, ERROR_EPOCH); epochDuration = _epochDuration; emit EpochDurationChanged(_epochDuration); } /** * @notice Change minimum number of missing votes allowed * @param _missingVotesThreshold number of seconds minimum to claim access to voting rewards */ function changeMissingVotesThreshold(uint256 _missingVotesThreshold) external auth(CHANGE_MISSING_VOTES_THRESHOLD_ROLE) { missingVotesThreshold = _missingVotesThreshold; emit MissingVoteThresholdChanged(_missingVotesThreshold); } /** * @notice Change minimum number of missing votes allowed * @param _lockTime number of seconds for which tokens will be locked after distributing reward */ function changeLockTime(uint64 _lockTime) external auth(CHANGE_LOCK_TIME_ROLE) { lockTime = _lockTime; emit LockTimeChanged(_lockTime); } /** * @notice Change Base Vault * @param _baseVault new base vault address */ function changeBaseVaultContractAddress(address _baseVault) external auth(CHANGE_VAULT_ROLE) { require(isContract(_baseVault), ERROR_ADDRESS_NOT_CONTRACT); baseVault = Vault(_baseVault); emit BaseVaultChanged(_baseVault); } /** * @notice Change Reward Vault * @param _rewardsVault new reward vault address */ function changeRewardsVaultContractAddress(address _rewardsVault) external auth(CHANGE_VAULT_ROLE) { require(isContract(_rewardsVault), ERROR_ADDRESS_NOT_CONTRACT); rewardsVault = Vault(_rewardsVault); emit RewardsVaultChanged(_rewardsVault); } /** * @notice Change Dandelion Voting contract address * @param _dandelionVoting new dandelionVoting address */ function changeDandelionVotingContractAddress(address _dandelionVoting) external auth(CHANGE_VOTING_ROLE) { require(isContract(_dandelionVoting), ERROR_ADDRESS_NOT_CONTRACT); dandelionVoting = DandelionVoting(_dandelionVoting); emit DandelionVotingChanged(_dandelionVoting); } /** * @notice Change percentage rewards * @param _percentageRewards new percentage * @dev PCT_BASE is the maximun allowed percentage */ function changePercentageRewards(uint256 _percentageRewards) external auth(CHANGE_PERCENTAGE_REWARDS_ROLE) { require(_percentageRewards <= PCT_BASE, ERROR_PERCENTAGE_REWARDS); percentageRewards = _percentageRewards; emit PercentageRewardsChanged(percentageRewards); } /** * @notice Change rewards token * @param _rewardsToken new percentage */ function changeRewardsTokenContractAddress(address _rewardsToken) external auth(CHANGE_REWARDS_TOKEN_ROLE) { require(isContract(_rewardsToken), ERROR_ADDRESS_NOT_CONTRACT); rewardsToken = _rewardsToken; emit RewardsTokenChanged(rewardsToken); } /** * @notice Returns all unlocked rewards given an address * @param _beneficiary address of which we want to get all rewards */ function getUnlockedRewardsInfo(address _beneficiary) external view returns (Reward[]) { Reward[] storage rewards = addressUnlockedRewards[_beneficiary]; return rewards; } /** * @notice Returns all withdrawan rewards given an address * @param _beneficiary address of which we want to get all rewards */ function getWithdrawnRewardsInfo(address _beneficiary) external view returns (Reward[]) { Reward[] storage rewards = addressWithdrawnRewards[_beneficiary]; return rewards; } /** * @notice collect rewards for an msg.sender */ function collectRewards() external { collectRewardsFor(msg.sender); } /** * @notice collect rewards for an address if lockTime is passed since when tokens have been distributed * @param _beneficiary address that should be fund with rewards * @dev rewardsVault should have TRANSFER_ROLE permission */ function collectRewardsFor(address _beneficiary) public returns (bool) { uint64 currentBlockNumber = getBlockNumber64(); Reward[] storage rewards = addressUnlockedRewards[_beneficiary]; uint256 rewardsLength = rewards.length; require(rewardsLength > 0, ERROR_NO_REWARDS); uint256 collectedRewardsAmount = 0; for (uint256 i = 0; i < rewardsLength; i++) { Reward reward = rewards[i]; if (currentBlockNumber - reward.lockBlock > reward.lockTime && !_isRewardEmpty(reward)) { collectedRewardsAmount = collectedRewardsAmount + reward.amount; emit RewardCollected(_beneficiary, reward.amount, reward.lockBlock, reward.lockTime); delete rewards[i]; } } rewardsVault.transfer(rewardsToken, _beneficiary, collectedRewardsAmount); return true; } /** * @notice Check if msg.sender is able to be rewarded, and in positive case, * he will be funded with the corresponding earned amount of tokens * @param _beneficiary address to which the deposit will be transferred if successful */ function _assignUnlockedReward(address _beneficiary, uint256 _amount) internal returns (bool) { Reward[] storage unlockedRewards = addressUnlockedRewards[_beneficiary]; uint64 currentBlockNumber = getBlockNumber64(); // prettier-ignore uint64 lastBlockDistributedReward = unlockedRewards.length == 0 ? deployBlock : unlockedRewards[unlockedRewards.length - 1].lockBlock; // NOTE: avoid double collecting for the same epoch require(currentBlockNumber.sub(lastBlockDistributedReward) > epochDuration, ERROR_EPOCH); addressUnlockedRewards[_beneficiary].push(Reward(_amount, currentBlockNumber, lockTime)); return true; } /** * @notice Check if a Reward is empty * @param _reward reward */ function _isRewardEmpty(Reward memory _reward) internal pure returns (bool) { return _reward.amount == 0 && _reward.lockBlock == 0 && _reward.lockTime == 0; } } pragma solidity 0.4.24; import "@aragon/os/contracts/apps/AragonApp.sol"; import "@aragon/os/contracts/common/DepositableStorage.sol"; import "@aragon/os/contracts/common/EtherTokenConstant.sol"; import "@aragon/os/contracts/common/SafeERC20.sol"; import "@aragon/os/contracts/lib/token/ERC20.sol"; 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); } }
Check if a Reward is empty _reward reward/
function _isRewardEmpty(Reward memory _reward) internal pure returns (bool) { return _reward.amount == 0 && _reward.lockBlock == 0 && _reward.lockTime == 0; }
13,454,037
./partial_match/1/0x51B29cD73C5d13a97c1Db060f94c39087797ae8D/sources/ZeroxPonzi.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("0xPonzi", "0xP") { router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(router.factory()).createPair(address(this), router.WETH()); _isExcludedMaxTransactionAmount[address(router)] = true; _isExcludedMaxTransactionAmount[address(uniswapV2Pair)] = true; _isExcludedMaxTransactionAmount[owner()] = true; _isExcludedMaxTransactionAmount[address(this)] = true; _isExcludedFromFees[owner()] = true; _isExcludedFromFees[address(this)] = true; _isExcludedMaxWalletAmount[owner()] = true; _isExcludedMaxWalletAmount[address(this)] = true; _isExcludedMaxWalletAmount[address(uniswapV2Pair)] = true; marketPair[address(uniswapV2Pair)] = true; approve(address(router), type(uint256).max); uint256 totalSupply = 1e9 * 1e18; _fees.buyMarketingFee = 15; _fees.buyLiquidityFee = 0; _fees.buyDevFee = 5; _fees.buyTotalFees = _fees.buyMarketingFee + _fees.buyLiquidityFee + _fees.buyDevFee; _fees.sellMarketingFee = 20; _fees.sellLiquidityFee = 0; _fees.sellDevFee = 5; _fees.sellTotalFees = _fees.sellMarketingFee + _fees.sellLiquidityFee + _fees.sellDevFee; marketingWallet = address(0xEED67d93fb9CDEaeA68a912f679C70127533b3E6); devWallet = address(0xCDE97f1F1389B0ca269f97F31B59Fc6A2f033497); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
3,536,330
./partial_match/1/0xC2DA2859901fdB615Ebf4449983b96BECa238c57/sources/StabilizeStrategyDSDESDArb.sol
Change percent of balance to trigger trade --------------------
function startChangePercentTradeTrigger(uint256 _percent) external onlyGovernance { require(_percent <= 100000,"Percent cannot be greater than 100%"); _timelockStart = now; _timelockType = 8; _timelock_data_1 = _percent; }
2,615,985
pragma solidity ^0.4.24; // File: @0xcert/ethereum-utils/contracts/math/SafeMath.sol /** * @dev Math operations with safety checks that throw on error. This contract is based * on the source code at https://goo.gl/iyQsmU. */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. * @param _a Factor number. * @param _b Factor number. */ function mul( uint256 _a, uint256 _b ) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. * @param _a Dividend number. * @param _b Divisor number. */ function div( uint256 _a, uint256 _b ) internal pure returns (uint256) { uint256 c = _a / _b; // assert(b > 0); // Solidity automatically throws when dividing by 0 // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). * @param _a Minuend number. * @param _b Subtrahend number. */ function sub( uint256 _a, uint256 _b ) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. * @param _a Number. * @param _b Number. */ function add( uint256 _a, uint256 _b ) internal pure returns (uint256) { uint256 c = _a + _b; assert(c >= _a); return c; } } // File: @0xcert/ethereum-erc721/contracts/tokens/ERC721Enumerable.sol /** * @dev Optional enumeration extension for ERC-721 non-fungible token standard. * See https://goo.gl/pc9yoS. */ interface ERC721Enumerable { /** * @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an * assigned and queryable owner not equal to the zero address. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified. * @param _index A counter less than `totalSupply()`. */ function tokenByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is * not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address, * representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them. * @param _index A counter less than `balanceOf(_owner)`. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256); } // File: @0xcert/ethereum-erc721/contracts/tokens/ERC721.sol /** * @dev ERC-721 non-fungible token standard. See https://goo.gl/pc9yoS. */ interface ERC721 { /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. */ function balanceOf( address _owner ) external view returns (uint256); /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` * on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) external; /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they mayb be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved The new approved NFT controller. * @param _tokenId The NFT to approve. */ function approve( address _approved, uint256 _tokenId ) external; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } // File: @0xcert/ethereum-erc721/contracts/tokens/ERC721TokenReceiver.sol /** * @dev ERC-721 interface for accepting safe transfers. See https://goo.gl/pc9yoS. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function. * @param _from The address which previously owned the token. * @param _tokenId The NFT identifier which is being transferred. * @param _data Additional data with no specified format. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) external returns(bytes4); } // File: @0xcert/ethereum-utils/contracts/utils/AddressUtils.sol /** * @dev Utility library of inline functions on addresses. */ library AddressUtils { /** * @dev Returns whether the target address is a contract. * @param _addr Address to check. */ function isContract( address _addr ) internal view returns (bool) { uint256 size; /** * XXX Currently there is no better way to check if there is a contract in an address than to * check the size of the code at that address. * See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works. * TODO: Check this again before the Serenity release, because all addresses will be * contracts then. */ assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: @0xcert/ethereum-utils/contracts/utils/ERC165.sol /** * @dev A standard for detecting smart contract interfaces. See https://goo.gl/cxQCse. */ interface ERC165 { /** * @dev Checks if the smart contract includes a specific interface. * @notice This function uses less than 30,000 gas. * @param _interfaceID The interface identifier, as specified in ERC-165. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool); } // File: @0xcert/ethereum-utils/contracts/utils/SupportsInterface.sol /** * @dev Implementation of standard for detect smart contract interfaces. */ contract SupportsInterface is ERC165 { /** * @dev Mapping of supported intefraces. * @notice You must not set element 0xffffffff to true. */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x01ffc9a7] = true; // ERC165 } /** * @dev Function to check which interfaces are suported by this contract. * @param _interfaceID Id of the interface. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool) { return supportedInterfaces[_interfaceID]; } } // File: @0xcert/ethereum-erc721/contracts/tokens/NFToken.sol /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract NFToken is ERC721, SupportsInterface { using SafeMath for uint256; using AddressUtils for address; /** * @dev A mapping from NFT ID to the address that owns it. */ mapping (uint256 => address) internal idToOwner; /** * @dev Mapping from NFT ID to approved address. */ mapping (uint256 => address) internal idToApprovals; /** * @dev Mapping from owner address to count of his tokens. */ mapping (address => uint256) internal ownerToNFTokenCount; /** * @dev Mapping from owner address to mapping of operator addresses. */ mapping (address => mapping (address => bool)) internal ownerToOperators; /** * @dev Magic value of a smart contract that can recieve NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. * @param _from Sender of NFT (if address is zero address it indicates token creation). * @param _to Receiver of NFT (if address is zero address it indicates token destruction). * @param _tokenId The NFT that got transfered. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. * @param _owner Owner of NFT. * @param _approved Address that we are approving. * @param _tokenId NFT which we are approving. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. * @param _owner Owner of NFT. * @param _operator Address to which we are setting operator rights. * @param _approved Status of operator rights(true if operator rights are given and false if * revoked). */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Guarantees that the msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender]); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || getApproved(_tokenId) == msg.sender || ownerToOperators[tokenOwner][msg.sender] ); _; } /** * @dev Guarantees that _tokenId is a valid Token. * @param _tokenId ID of the NFT to validate. */ modifier validNFToken( uint256 _tokenId ) { require(idToOwner[_tokenId] != address(0)); _; } /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x80ac58cd] = true; // ERC721 } /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. */ function balanceOf( address _owner ) external view returns (uint256) { require(_owner != address(0)); return ownerToNFTokenCount[_owner]; } /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. */ function ownerOf( uint256 _tokenId ) external view returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0)); } /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` * on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) external { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they maybe be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from); require(_to != address(0)); _transfer(_to, _tokenId); } /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved Address to be approved for the given NFT ID. * @param _tokenId ID of the token to be approved. */ function approve( address _approved, uint256 _tokenId ) external canOperate(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner); idToApprovals[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice This works even if sender doesn't own any tokens at the time. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external { require(_operator != address(0)); ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId ID of the NFT to query the approval of. */ function getApproved( uint256 _tokenId ) public view validNFToken(_tokenId) returns (address) { return idToApprovals[_tokenId]; } /** * @dev Checks if `_operator` is an approved operator for `_owner`. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool) { require(_owner != address(0)); require(_operator != address(0)); return ownerToOperators[_owner][_operator]; } /** * @dev Actually perform the safeTransferFrom. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) internal canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from); require(_to != address(0)); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == MAGIC_ON_ERC721_RECEIVED); } } /** * @dev Actually preforms the transfer. * @notice Does NO checks. * @param _to Address of a new owner. * @param _tokenId The NFT that is being transferred. */ function _transfer( address _to, uint256 _tokenId ) private { address from = idToOwner[_tokenId]; clearApproval(_tokenId); removeNFToken(from, _tokenId); addNFToken(_to, _tokenId); emit Transfer(from, _to, _tokenId); } /** * @dev Mints a new NFT. * @notice This is a private function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal { require(_to != address(0)); require(_tokenId != 0); require(idToOwner[_tokenId] == address(0)); addNFToken(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Burns a NFT. * @notice This is a private function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _owner Address of the NFT owner. * @param _tokenId ID of the NFT to be burned. */ function _burn( address _owner, uint256 _tokenId ) validNFToken(_tokenId) internal { clearApproval(_tokenId); removeNFToken(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function clearApproval( uint256 _tokenId ) private { if(idToApprovals[_tokenId] != 0) { delete idToApprovals[_tokenId]; } } /** * @dev Removes a NFT from owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function removeNFToken( address _from, uint256 _tokenId ) internal { require(idToOwner[_tokenId] == _from); assert(ownerToNFTokenCount[_from] > 0); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from].sub(1); delete idToOwner[_tokenId]; } /** * @dev Assignes a new NFT to owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function addNFToken( address _to, uint256 _tokenId ) internal { require(idToOwner[_tokenId] == address(0)); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1); } } // File: @0xcert/ethereum-erc721/contracts/tokens/NFTokenEnumerable.sol /** * @dev Optional enumeration implementation for ERC-721 non-fungible token standard. */ contract NFTokenEnumerable is NFToken, ERC721Enumerable { /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Mints a new NFT. * @notice This is a private function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length.sub(1); } /** * @dev Burns a NFT. * @notice This is a private function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _owner Address of the NFT owner. * @param _tokenId ID of the NFT to be burned. */ function _burn( address _owner, uint256 _tokenId ) internal { super._burn(_owner, _tokenId); assert(tokens.length > 0); uint256 tokenIndex = idToIndex[_tokenId]; // Sanity check. This could be removed in the future. assert(tokens[tokenIndex] == _tokenId); uint256 lastTokenIndex = tokens.length.sub(1); uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.length--; // Consider adding a conditional check for the last token in order to save GAS. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function removeNFToken( address _from, uint256 _tokenId ) internal { super.removeNFToken(_from, _tokenId); assert(ownerToIds[_from].length > 0); uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length.sub(1); uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; ownerToIds[_from].length--; // Consider adding a conditional check for the last token in order to save GAS. idToOwnerIndex[lastToken] = tokenToRemoveIndex; idToOwnerIndex[_tokenId] = 0; } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function addNFToken( address _to, uint256 _tokenId ) internal { super.addNFToken(_to, _tokenId); uint256 length = ownerToIds[_to].length; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = length; } /** * @dev Returns the count of all existing NFTokens. */ function totalSupply() external view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. */ function tokenByIndex( uint256 _index ) external view returns (uint256) { require(_index < tokens.length); // Sanity check. This could be removed in the future. assert(idToIndex[tokens[_index]] == _index); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256) { require(_index < ownerToIds[_owner].length); return ownerToIds[_owner][_index]; } } // File: @0xcert/ethereum-erc721/contracts/tokens/ERC721Metadata.sol /** * @dev Optional metadata extension for ERC-721 non-fungible token standard. * See https://goo.gl/pc9yoS. */ interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. */ function name() external view returns (string _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. */ function symbol() external view returns (string _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". */ function tokenURI(uint256 _tokenId) external view returns (string); } // File: @0xcert/ethereum-erc721/contracts/tokens/NFTokenMetadata.sol /** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */ contract NFTokenMetadata is NFToken, ERC721Metadata { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata } /** * @dev Burns a NFT. * @notice This is a internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _owner Address of the NFT owner. * @param _tokenId ID of the NFT to be burned. */ function _burn( address _owner, uint256 _tokenId ) internal { super._burn(_owner, _tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice this is a internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want uri. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string _uri ) validNFToken(_tokenId) internal { idToUri[_tokenId] = _uri; } /** * @dev Returns a descriptive name for a collection of NFTokens. */ function name() external view returns (string _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. */ function symbol() external view returns (string _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. */ function tokenURI( uint256 _tokenId ) validNFToken(_tokenId) external view returns (string) { return idToUri[_tokenId]; } } // File: @0xcert/ethereum-utils/contracts/ownership/Ownable.sol /** * @dev The contract has an owner address, and provides basic authorization control whitch * simplifies the implementation of user permissions. This contract is based on the source code * at https://goo.gl/n2ZGVt. */ contract Ownable { address public owner; /** * @dev An event which is triggered when the owner is changed. * @param previousOwner The address of the previous owner. * @param newOwner The address of the new owner. */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The constructor sets the original `owner` of the contract to the sender account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership( address _newOwner ) onlyOwner public { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: @0xcert/ethereum-xcert/contracts/tokens/Xcert.sol /** * @dev Xcert implementation. */ contract Xcert is NFTokenEnumerable, NFTokenMetadata, Ownable { using SafeMath for uint256; using AddressUtils for address; /** * @dev Unique ID which determines each Xcert smart contract type by its JSON convention. * @notice Calculated as bytes4(keccak256(jsonSchema)). */ bytes4 internal nftConventionId; /** * @dev Maps NFT ID to proof. */ mapping (uint256 => string) internal idToProof; /** * @dev Maps NFT ID to protocol config. */ mapping (uint256 => bytes32[]) internal config; /** * @dev Maps NFT ID to convention data. */ mapping (uint256 => bytes32[]) internal data; /** * @dev Maps address to authorization of contract. */ mapping (address => bool) internal addressToAuthorized; /** * @dev Emits when an address is authorized to some contract control or the authorization is revoked. * The _target has some contract controle like minting new NFTs. * @param _target Address to set authorized state. * @param _authorized True if the _target is authorised, false to revoke authorization. */ event AuthorizedAddress( address indexed _target, bool _authorized ); /** * @dev Guarantees that msg.sender is allowed to mint a new NFT. */ modifier isAuthorized() { require(msg.sender == owner || addressToAuthorized[msg.sender]); _; } /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftConventionId, nftName and * nftSymbol. */ constructor() public { supportedInterfaces[0x6be14f75] = true; // Xcert } /** * @dev Mints a new NFT. * @param _to The address that will own the minted NFT. * @param _id The NFT to be minted by the msg.sender. * @param _uri An URI pointing to NFT metadata. * @param _proof Cryptographic asset imprint. * @param _config Array of protocol config values where 0 index represents token expiration * timestamp, other indexes are not yet definied but are ready for future xcert upgrades. * @param _data Array of convention data values. */ function mint( address _to, uint256 _id, string _uri, string _proof, bytes32[] _config, bytes32[] _data ) external isAuthorized() { require(_config.length > 0); require(bytes(_proof).length > 0); super._mint(_to, _id); super._setTokenUri(_id, _uri); idToProof[_id] = _proof; config[_id] = _config; data[_id] = _data; } /** * @dev Returns a bytes4 of keccak256 of json schema representing 0xcert protocol convention. */ function conventionId() external view returns (bytes4 _conventionId) { _conventionId = nftConventionId; } /** * @dev Returns proof for NFT. * @param _tokenId Id of the NFT. */ function tokenProof( uint256 _tokenId ) validNFToken(_tokenId) external view returns(string) { return idToProof[_tokenId]; } /** * @dev Returns convention data value for a given index field. * @param _tokenId Id of the NFT we want to get value for key. * @param _index for which we want to get value. */ function tokenDataValue( uint256 _tokenId, uint256 _index ) validNFToken(_tokenId) public view returns(bytes32 value) { require(_index < data[_tokenId].length); value = data[_tokenId][_index]; } /** * @dev Returns expiration date from 0 index of token config values. * @param _tokenId Id of the NFT we want to get expiration time of. */ function tokenExpirationTime( uint256 _tokenId ) validNFToken(_tokenId) external view returns(bytes32) { return config[_tokenId][0]; } /** * @dev Sets authorised address for minting. * @param _target Address to set authorized state. * @param _authorized True if the _target is authorised, false to revoke authorization. */ function setAuthorizedAddress( address _target, bool _authorized ) onlyOwner external { require(_target != address(0)); addressToAuthorized[_target] = _authorized; emit AuthorizedAddress(_target, _authorized); } /** * @dev Sets mint authorised address. * @param _target Address for which we want to check if it is authorized. * @return Is authorized or not. */ function isAuthorizedAddress( address _target ) external view returns (bool) { require(_target != address(0)); return addressToAuthorized[_target]; } } // File: @0xcert/ethereum-erc20/contracts/tokens/ERC20.sol /** * @title A standard interface for tokens. */ interface ERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string _name); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string _symbol); /** * @dev Returns the number of decimals the token uses. */ function decimals() external view returns (uint8 _decimals); /** * @dev Returns the total token supply. */ function totalSupply() external view returns (uint256 _totalSupply); /** * @dev Returns the account balance of another account with address _owner. * @param _owner The address from which the balance will be retrieved. */ function balanceOf( address _owner ) external view returns (uint256 _balance); /** * @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The * function SHOULD throw if the _from account balance does not have enough tokens to spend. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. */ function transfer( address _to, uint256 _value ) external returns (bool _success); /** * @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the * Transfer event. * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) external returns (bool _success); /** * @dev Allows _spender to withdraw from your account multiple times, up to * the _value amount. If this function is called again it overwrites the current * allowance with _value. * @param _spender The address of the account able to transfer the tokens. * @param _value The amount of tokens to be approved for transfer. */ function approve( address _spender, uint256 _value ) external returns (bool _success); /** * @dev Returns the amount which _spender is still allowed to withdraw from _owner. * @param _owner The address of the account owning tokens. * @param _spender The address of the account able to transfer the tokens. */ function allowance( address _owner, address _spender ) external view returns (uint256 _remaining); /** * @dev Triggers when tokens are transferred, including zero value transfers. */ event Transfer( address indexed _from, address indexed _to, uint256 _value ); /** * @dev Triggers on any successful call to approve(address _spender, uint256 _value). */ event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: @0xcert/ethereum-erc20/contracts/tokens/Token.sol /** * @title ERC20 standard token implementation. * @dev Standard ERC20 token. This contract follows the implementation at https://goo.gl/mLbAPJ. */ contract Token is ERC20 { using SafeMath for uint256; /** * Token name. */ string internal tokenName; /** * Token symbol. */ string internal tokenSymbol; /** * Number of decimals. */ uint8 internal tokenDecimals; /** * Total supply of tokens. */ uint256 internal tokenTotalSupply; /** * Balance information map. */ mapping (address => uint256) internal balances; /** * Token allowance mapping. */ mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Trigger when tokens are transferred, including zero value transfers. */ event Transfer( address indexed _from, address indexed _to, uint256 _value ); /** * @dev Trigger on any successful call to approve(address _spender, uint256 _value). */ event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /** * @dev Returns the name of the token. */ function name() external view returns (string _name) { _name = tokenName; } /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string _symbol) { _symbol = tokenSymbol; } /** * @dev Returns the number of decimals the token uses. */ function decimals() external view returns (uint8 _decimals) { _decimals = tokenDecimals; } /** * @dev Returns the total token supply. */ function totalSupply() external view returns (uint256 _totalSupply) { _totalSupply = tokenTotalSupply; } /** * @dev Returns the account balance of another account with address _owner. * @param _owner The address from which the balance will be retrieved. */ function balanceOf( address _owner ) external view returns (uint256 _balance) { _balance = balances[_owner]; } /** * @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The * function SHOULD throw if the _from account balance does not have enough tokens to spend. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. */ function transfer( address _to, uint256 _value ) public returns (bool _success) { require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); _success = true; } /** * @dev Allows _spender to withdraw from your account multiple times, up to the _value amount. If * this function is called again it overwrites the current allowance with _value. * @param _spender The address of the account able to transfer the tokens. * @param _value The amount of tokens to be approved for transfer. */ function approve( address _spender, uint256 _value ) public returns (bool _success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); _success = true; } /** * @dev Returns the amount which _spender is still allowed to withdraw from _owner. * @param _owner The address of the account owning tokens. * @param _spender The address of the account able to transfer the tokens. */ function allowance( address _owner, address _spender ) external view returns (uint256 _remaining) { _remaining = allowed[_owner][_spender]; } /** * @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the * Transfer event. * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool _success) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); _success = true; } } // File: @0xcert/ethereum-zxc/contracts/tokens/Zxc.sol /* * @title ZXC protocol token. * @dev Standard ERC20 token used by the 0xcert protocol. This contract follows the implementation * at https://goo.gl/twbPwp. */ contract Zxc is Token, Ownable { using SafeMath for uint256; /** * Transfer feature state. */ bool internal transferEnabled; /** * Crowdsale smart contract address. */ address public crowdsaleAddress; /** * @dev An event which is triggered when tokens are burned. * @param _burner The address which burns tokens. * @param _value The amount of burned tokens. */ event Burn( address indexed _burner, uint256 _value ); /** * @dev Assures that the provided address is a valid destination to transfer tokens to. * @param _to Target address. */ modifier validDestination( address _to ) { require(_to != address(0x0)); require(_to != address(this)); require(_to != address(crowdsaleAddress)); _; } /** * @dev Assures that tokens can be transfered. */ modifier onlyWhenTransferAllowed() { require(transferEnabled || msg.sender == crowdsaleAddress); _; } /** * @dev Contract constructor. */ constructor() public { tokenName = "0xcert Protocol Token"; tokenSymbol = "ZXC"; tokenDecimals = 18; tokenTotalSupply = 400000000000000000000000000; transferEnabled = false; balances[owner] = tokenTotalSupply; emit Transfer(address(0x0), owner, tokenTotalSupply); } /** * @dev Transfers token to a specified address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer( address _to, uint256 _value ) onlyWhenTransferAllowed() validDestination(_to) public returns (bool _success) { _success = super.transfer(_to, _value); } /** * @dev Transfers tokens from one address to another. * @param _from address The address which you want to send tokens from. * @param _to address The address which you want to transfer to. * @param _value uint256 The amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) onlyWhenTransferAllowed() validDestination(_to) public returns (bool _success) { _success = super.transferFrom(_from, _to, _value); } /** * @dev Enables token transfers. */ function enableTransfer() onlyOwner() external { transferEnabled = true; } /** * @dev Burns a specific amount of tokens. This function is based on BurnableToken implementation * at goo.gl/GZEhaq. * @notice Only owner is allowed to perform this operation. * @param _value The amount of tokens to be burned. */ function burn( uint256 _value ) onlyOwner() external { require(_value <= balances[msg.sender]); balances[owner] = balances[owner].sub(_value); tokenTotalSupply = tokenTotalSupply.sub(_value); emit Burn(owner, _value); emit Transfer(owner, address(0x0), _value); } /** * @dev Set crowdsale address which can distribute tokens even when onlyWhenTransferAllowed is * false. * @param crowdsaleAddr Address of token offering contract. */ function setCrowdsaleAddress( address crowdsaleAddr ) external onlyOwner() { crowdsaleAddress = crowdsaleAddr; } } // File: contracts/crowdsale/ZxcCrowdsale.sol /** * @title ZXC crowdsale contract. * @dev Crowdsale contract for distributing ZXC tokens. * Start timestamps for the token sale stages (start dates are inclusive, end exclusive): * - Token presale with 10% bonus: 2018/06/26 - 2018/07/04 * - Token sale with 5% bonus: 2018/07/04 - 2018/07/05 * - Token sale with 0% bonus: 2018/07/05 - 2018/07/18 */ contract ZxcCrowdsale { using SafeMath for uint256; /** * @dev Token being sold. */ Zxc public token; /** * @dev Xcert KYC token. */ Xcert public xcertKyc; /** * @dev Start time of the presale. */ uint256 public startTimePresale; /** * @dev Start time of the token sale with bonus. */ uint256 public startTimeSaleWithBonus; /** * @dev Start time of the token sale with no bonus. */ uint256 public startTimeSaleNoBonus; /** * @dev Presale bonus expressed as percentage integer (10% = 10). */ uint256 public bonusPresale; /** * @dev Token sale bonus expressed as percentage integer (10% = 10). */ uint256 public bonusSale; /** * @dev End timestamp to end the crowdsale. */ uint256 public endTime; /** * @dev Minimum required wei deposit for public presale period. */ uint256 public minimumPresaleWeiDeposit; /** * @dev Total amount of ZXC tokens offered for the presale. */ uint256 public preSaleZxcCap; /** * @dev Total supply of ZXC tokens for the sale. */ uint256 public crowdSaleZxcSupply; /** * @dev Amount of ZXC tokens sold. */ uint256 public zxcSold; /** * @dev Address where funds are collected. */ address public wallet; /** * @dev How many token units buyer gets per wei. */ uint256 public rate; /** * @dev An event which is triggered when tokens are bought. * @param _from The address sending tokens. * @param _to The address receiving tokens. * @param _weiAmount Purchase amount in wei. * @param _tokenAmount The amount of purchased tokens. */ event TokenPurchase( address indexed _from, address indexed _to, uint256 _weiAmount, uint256 _tokenAmount ); /** * @dev Contract constructor. * @param _walletAddress Address of the wallet which collects funds. * @param _tokenAddress Address of the ZXC token contract. * @param _xcertKycAddress Address of the Xcert KYC token contract. * @param _startTimePresale Start time of presale stage. * @param _startTimeSaleWithBonus Start time of public sale stage with bonus. * @param _startTimeSaleNoBonus Start time of public sale stage with no bonus. * @param _endTime Time when sale ends. * @param _rate ZXC/ETH exchange rate. * @param _presaleZxcCap Maximum number of ZXC offered for the presale. * @param _crowdSaleZxcSupply Supply of ZXC tokens offered for the sale. Includes _presaleZxcCap. * @param _bonusPresale Bonus token percentage for presale. * @param _bonusSale Bonus token percentage for public sale stage with bonus. * @param _minimumPresaleWeiDeposit Minimum required deposit in wei. */ constructor( address _walletAddress, address _tokenAddress, address _xcertKycAddress, uint256 _startTimePresale, // 1529971200: date -d '2018-06-26 00:00:00 UTC' +%s uint256 _startTimeSaleWithBonus, // 1530662400: date -d '2018-07-04 00:00:00 UTC' +%s uint256 _startTimeSaleNoBonus, //1530748800: date -d '2018-07-05 00:00:00 UTC' +%s uint256 _endTime, // 1531872000: date -d '2018-07-18 00:00:00 UTC' +%s uint256 _rate, // 10000: 1 ETH = 10,000 ZXC uint256 _presaleZxcCap, // 195M uint256 _crowdSaleZxcSupply, // 250M uint256 _bonusPresale, // 10 (%) uint256 _bonusSale, // 5 (%) uint256 _minimumPresaleWeiDeposit // 1 ether; ) public { require(_walletAddress != address(0)); require(_tokenAddress != address(0)); require(_xcertKycAddress != address(0)); require(_tokenAddress != _walletAddress); require(_tokenAddress != _xcertKycAddress); require(_xcertKycAddress != _walletAddress); token = Zxc(_tokenAddress); xcertKyc = Xcert(_xcertKycAddress); uint8 _tokenDecimals = token.decimals(); require(_tokenDecimals == 18); // Sanity check. wallet = _walletAddress; // Bonus should be > 0% and <= 100% require(_bonusPresale > 0 && _bonusPresale <= 100); require(_bonusSale > 0 && _bonusSale <= 100); bonusPresale = _bonusPresale; bonusSale = _bonusSale; require(_startTimeSaleWithBonus > _startTimePresale); require(_startTimeSaleNoBonus > _startTimeSaleWithBonus); startTimePresale = _startTimePresale; startTimeSaleWithBonus = _startTimeSaleWithBonus; startTimeSaleNoBonus = _startTimeSaleNoBonus; endTime = _endTime; require(_rate > 0); rate = _rate; require(_crowdSaleZxcSupply > 0); require(token.totalSupply() >= _crowdSaleZxcSupply); crowdSaleZxcSupply = _crowdSaleZxcSupply; require(_presaleZxcCap > 0 && _presaleZxcCap <= _crowdSaleZxcSupply); preSaleZxcCap = _presaleZxcCap; zxcSold = 71157402800000000000000000; require(_minimumPresaleWeiDeposit > 0); minimumPresaleWeiDeposit = _minimumPresaleWeiDeposit; } /** * @dev Fallback function can be used to buy tokens. */ function() external payable { buyTokens(); } /** * @dev Low level token purchase function. */ function buyTokens() public payable { uint256 tokens; // Sender needs Xcert KYC token. uint256 balance = xcertKyc.balanceOf(msg.sender); require(balance > 0); uint256 tokenId = xcertKyc.tokenOfOwnerByIndex(msg.sender, balance - 1); uint256 kycLevel = uint(xcertKyc.tokenDataValue(tokenId, 0)); if (isInTimeRange(startTimePresale, startTimeSaleWithBonus)) { require(kycLevel > 1); require(msg.value >= minimumPresaleWeiDeposit); tokens = getTokenAmount(msg.value, bonusPresale); require(zxcSold.add(tokens) <= preSaleZxcCap); } else if (isInTimeRange(startTimeSaleWithBonus, startTimeSaleNoBonus)) { require(kycLevel > 0); tokens = getTokenAmount(msg.value, bonusSale); } else if (isInTimeRange(startTimeSaleNoBonus, endTime)) { require(kycLevel > 0); tokens = getTokenAmount(msg.value, uint256(0)); } else { revert("Purchase outside of token sale time windows"); } require(zxcSold.add(tokens) <= crowdSaleZxcSupply); zxcSold = zxcSold.add(tokens); wallet.transfer(msg.value); require(token.transferFrom(token.owner(), msg.sender, tokens)); emit TokenPurchase(msg.sender, msg.sender, msg.value, tokens); } /** * @return true if crowdsale event has ended */ function hasEnded() external view returns (bool) { bool capReached = zxcSold >= crowdSaleZxcSupply; bool endTimeReached = now >= endTime; return capReached || endTimeReached; } /** * @dev Check if currently active period is a given time period. * @param _startTime Starting timestamp (inclusive). * @param _endTime Ending timestamp (exclusive). * @return bool */ function isInTimeRange( uint256 _startTime, uint256 _endTime ) internal view returns(bool) { if (now >= _startTime && now < _endTime) { return true; } else { return false; } } /** * @dev Calculate amount of tokens for a given wei amount. Apply special bonuses depending on * @param weiAmount Amount of wei for token purchase. * @param bonusPercent Percentage of bonus tokens. * @return Number of tokens with possible bonus. */ function getTokenAmount( uint256 weiAmount, uint256 bonusPercent ) internal view returns(uint256) { uint256 tokens = weiAmount.mul(rate); if (bonusPercent > 0) { uint256 bonusTokens = tokens.mul(bonusPercent).div(uint256(100)); // tokens * bonus (%) / 100% tokens = tokens.add(bonusTokens); } return tokens; } }
return true if crowdsale event has ended/
function hasEnded() external view returns (bool) { bool capReached = zxcSold >= crowdSaleZxcSupply; bool endTimeReached = now >= endTime; return capReached || endTimeReached; }
5,546,363