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/1/0x5C60dC4fE512e059C100df80720ace8fDB098Bd2/sources/contracts/rUSTPool.sol
The USD value of the collateral asset must be higher than safeCollateralRate./
function _requireIsSafeCollateralRate(address user) internal view { uint256 borrowedAmount = getrUSTPAmountByShares(borrowedShares[user]); if (borrowedAmount == 0) { return; } require( (stbt.getAmountByShares(depositedSharesSTBT[user]).mul(_stbtPrice()).mul(100) / borrowedAmount) >= safeCollateralRate, "Cannot be lower than the safeCollateralRate." ); }
3,187,555
pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @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); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @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; } } contract EmcoTokenInterface is ERC20 { function setReferral(bytes32 _code) public; function setReferralCode(bytes32 _code) public view returns (bytes32); function referralCodeOwners(bytes32 _code) public view returns (address); function referrals(address _address) public view returns (address); function userReferralCodes(address _address) public view returns (bytes32); } /** * @title EMCO Clan * @dev EMCO Clan */ contract Clan is Ownable { using SafeMath for uint256; mapping(address => uint256) public rewards; mapping(uint256 => uint256) public epochRewards; mapping(address => uint256) public epochJoined; mapping(uint => uint256) private membersNumForEpoch; mapping(address => mapping(uint => bool)) public reclaimedRewards; uint public lastMembersNumber = 0; event UserJoined(address userAddress); event UserLeaved(address userAddress); uint public startBlock; uint public epochLength; uint public ownersReward; EmcoToken emco; address public clanOwner; constructor(address _clanOwner, address _emcoToken, uint256 _epochLength) public { clanOwner = _clanOwner; startBlock = block.number; epochLength = _epochLength; emco = EmcoToken(_emcoToken); } function replenish(uint amount) public onlyOwner { //update members number for epoch if it was not set //we should ensure that for each epoch that has a reward members num is set uint currentEpoch = getCurrentEpoch(); if(membersNumForEpoch[currentEpoch] == 0) { membersNumForEpoch[currentEpoch] = lastMembersNumber; } uint ownersPart; if(membersNumForEpoch[currentEpoch] == 0) { //first user joined, mines on current epoch, but user is able to redeem for next epoch ownersPart = amount; } else { ownersPart = amount.div(10); epochRewards[currentEpoch] = epochRewards[currentEpoch].add(amount - ownersPart); } ownersReward = ownersReward.add(ownersPart); } function getMembersForEpoch(uint epochNumber) public view returns (uint membersNumber) { return membersNumForEpoch[epochNumber]; } function getCurrentEpoch() public view returns (uint256) { return (block.number - startBlock) / epochLength; } //only token can join a user to a clan. Owner is an EMCO Token contract function join(address user) public onlyOwner { emit UserJoined(user); uint currentEpoch = getCurrentEpoch(); epochJoined[user] = currentEpoch + 1; //increment members number uint currentMembersNum = lastMembersNumber; if(currentMembersNum == 0) { membersNumForEpoch[currentEpoch + 1] = currentMembersNum + 1; } else { membersNumForEpoch[currentEpoch + 1] = membersNumForEpoch[currentEpoch + 1] + 1; } //update last members num lastMembersNumber = membersNumForEpoch[currentEpoch + 1]; } function leaveClan(address user) public onlyOwner { epochJoined[user] = 0; emit UserLeaved(user); //decrement members number uint currentEpoch = getCurrentEpoch(); uint currentMembersNum = lastMembersNumber; if(currentMembersNum != 0) { membersNumForEpoch[currentEpoch + 1] = membersNumForEpoch[currentEpoch + 1] - 1; } //update last members num lastMembersNumber = membersNumForEpoch[currentEpoch + 1]; } function calculateReward(uint256 epoch) public view returns (uint256) { return epochRewards[epoch].div(membersNumForEpoch[epoch]); } function reclaimOwnersReward() public { require(msg.sender == clanOwner); emco.transfer(msg.sender, ownersReward); ownersReward = 0; } //get your bonus for specific epoch function reclaimReward(uint256 epoch) public { uint currentEpoch = getCurrentEpoch(); require(currentEpoch > epoch); require(epochJoined[msg.sender] != 0); require(epochJoined[msg.sender] <= epoch); require(reclaimedRewards[msg.sender][epoch] == false); uint userReward = calculateReward(epoch); require(userReward > 0); require(emco.transfer(msg.sender, userReward)); reclaimedRewards[msg.sender][epoch] = true; } } /** * @title Emco token 2nd version * @dev Emco token implementation */ contract EmcoToken is StandardToken, Ownable { string public constant name = "EmcoToken"; string public constant symbol = "EMCO"; uint8 public constant decimals = 18; // uint public constant INITIAL_SUPPLY = 1500000 * (10 ** uint(decimals)); uint public constant MAX_SUPPLY = 36000000 * (10 ** uint(decimals)); mapping (address => uint) public miningBalances; mapping (address => uint) public lastMiningBalanceUpdateTime; //clans mapping (address => address) public joinedClans; mapping (address => address) public userClans; mapping (address => bool) public clanRegistry; mapping (address => uint256) public inviteeCount; address systemAddress; EmcoTokenInterface private oldContract; uint public constant DAY_MINING_DEPOSIT_LIMIT = 360000 * (10 ** uint(decimals)); uint public constant TOTAL_MINING_DEPOSIT_LIMIT = 3600000 * (10 ** uint(decimals)); uint currentDay; uint currentDayDeposited; uint public miningTotalDeposited; mapping(address => bytes32) private userRefCodes; mapping(bytes32 => address) private refCodeOwners; mapping(address => address) private refs; event Mine(address indexed beneficiary, uint value); event MiningBalanceUpdated(address indexed owner, uint amount, bool isDeposit); event Migrate(address indexed user, uint256 amount); event TransferComment(address indexed to, uint256 amount, bytes comment); event SetReferral(address whoSet, address indexed referrer); constructor(address emcoAddress) public { systemAddress = msg.sender; oldContract = EmcoTokenInterface(emcoAddress); } function migrate(uint _amount) public { require(oldContract.transferFrom(msg.sender, this, _amount)); totalSupply_ = totalSupply_.add(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); emit Migrate(msg.sender, _amount); emit Transfer(address(0), msg.sender, _amount); } function setReferralCode(bytes32 _code) public returns (bytes32) { require(_code != ""); require(refCodeOwners[_code] == address(0)); require(oldContract.referralCodeOwners(_code) == address(0)); require(userReferralCodes(msg.sender) == ""); userRefCodes[msg.sender] = _code; refCodeOwners[_code] = msg.sender; return _code; } function referralCodeOwners(bytes32 _code) public view returns (address owner) { address refCodeOwner = refCodeOwners[_code]; if(refCodeOwner == address(0)) { return oldContract.referralCodeOwners(_code); } else { return refCodeOwner; } } function userReferralCodes(address _address) public view returns (bytes32) { bytes32 code = oldContract.userReferralCodes(_address); if(code != "") { return code; } else { return userRefCodes[_address]; } } function referrals(address _address) public view returns (address) { address refInOldContract = oldContract.referrals(_address); if(refInOldContract != address(0)) { return refInOldContract; } else { return refs[_address]; } } function setReferral(bytes32 _code) public { require(refCodeOwners[_code] != address(0)); require(referrals(msg.sender) == address(0)); require(oldContract.referrals(msg.sender) == address(0)); address referrer = refCodeOwners[_code]; require(referrer != msg.sender, "Can not invite yourself"); refs[msg.sender] = referrer; inviteeCount[referrer] = inviteeCount[referrer].add(1); emit SetReferral(msg.sender, referrer); } function transferWithComment(address _to, uint256 _value, bytes _comment) public returns (bool) { emit TransferComment(_to, _value, _comment); return transfer(_to, _value); } /** * Create a clan */ function createClan(uint256 epochLength) public returns (address clanAddress) { require(epochLength >= 175200); //min epoch length about a month //check if there is a clan already. If so, throw require(userClans[msg.sender] == address(0x0)); //check if user has at least 10 invitees require(inviteeCount[msg.sender] >= 10); //instantiate new instance of contract Clan clan = new Clan(msg.sender, this, epochLength); //register clan to mapping userClans[msg.sender] = clan; clanRegistry[clan] = true; return clan; } function joinClan(address clanAddress) public { //ensure than such clan exists require(clanRegistry[clanAddress]); require(joinedClans[msg.sender] == address(0x0)); //join user to clan Clan clan = Clan(clanAddress); clan.join(msg.sender); //set clan to user joinedClans[msg.sender] = clanAddress; } function leaveClan() public { address clanAddress = joinedClans[msg.sender]; require(clanAddress != address(0x0)); Clan clan = Clan(clanAddress); clan.leaveClan(msg.sender); //unregister user from clan joinedClans[msg.sender] = address(0x0); } /** * Update invitees count */ function updateInviteesCount(address invitee, uint256 count) public onlyOwner { inviteeCount[invitee] = count; } /** * @dev Gets the balance of specified address (amount of tokens on main balance * plus amount of tokens on mining balance). * @param _owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner].add(miningBalances[_owner]); } /** * @dev Gets the mining balance if caller. * @param _owner The address to query the balance of. * @return An uint256 representing the amount of tokens of caller's mining balance */ function miningBalanceOf(address _owner) public view returns (uint balance) { return miningBalances[_owner]; } /** * @dev Moves specified amount of tokens from main balance to mining balance * @param _amount An uint256 representing the amount of tokens to transfer to main balance */ function depositToMiningBalance(uint _amount) public { require(balances[msg.sender] >= _amount, "not enough tokens"); require(getCurrentDayDeposited().add(_amount) <= DAY_MINING_DEPOSIT_LIMIT, "Day mining deposit exceeded"); require(miningTotalDeposited.add(_amount) <= TOTAL_MINING_DEPOSIT_LIMIT, "Total mining deposit exceeded"); balances[msg.sender] = balances[msg.sender].sub(_amount); miningBalances[msg.sender] = miningBalances[msg.sender].add(_amount); miningTotalDeposited = miningTotalDeposited.add(_amount); updateCurrentDayDeposited(_amount); lastMiningBalanceUpdateTime[msg.sender] = now; emit MiningBalanceUpdated(msg.sender, _amount, true); } /** * @dev Moves specified amount of tokens from mining balance to main balance * @param _amount An uint256 representing the amount of tokens to transfer to mining balance */ function withdrawFromMiningBalance(uint _amount) public { require(miningBalances[msg.sender] >= _amount, "not enough mining tokens"); miningBalances[msg.sender] = miningBalances[msg.sender].sub(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); //updating mining limits miningTotalDeposited = miningTotalDeposited.sub(_amount); lastMiningBalanceUpdateTime[msg.sender] = now; emit MiningBalanceUpdated(msg.sender, _amount, false); } /** * @dev Mine tokens. For every 24h for each user�s token on mining balance, * 1% is burnt on mining balance and Reward % is minted to the main balance. 15% fee of difference * between minted coins and burnt coins goes to system address. */ function mine() public { require(totalSupply_ < MAX_SUPPLY, "mining is over"); uint reward = getReward(totalSupply_); uint daysForReward = getDaysForReward(); uint mintedAmount = miningBalances[msg.sender].mul(reward.sub(1000000000)) .mul(daysForReward).div(100000000000); require(mintedAmount != 0); uint amountToBurn = miningBalances[msg.sender].mul(daysForReward).div(100); //check exceeding max number of tokens if(totalSupply_.add(mintedAmount) > MAX_SUPPLY) { uint availableToMint = MAX_SUPPLY.sub(totalSupply_); amountToBurn = availableToMint.div(mintedAmount).mul(amountToBurn); mintedAmount = availableToMint; } totalSupply_ = totalSupply_.add(mintedAmount); miningBalances[msg.sender] = miningBalances[msg.sender].sub(amountToBurn); balances[msg.sender] = balances[msg.sender].add(amountToBurn); uint userReward; uint referrerReward = 0; address referrer = referrals(msg.sender); if(referrer == address(0)) { userReward = mintedAmount.mul(85).div(100); } else { userReward = mintedAmount.mul(86).div(100); referrerReward = mintedAmount.div(100); balances[referrer] = balances[referrer].add(referrerReward); emit Mine(referrer, referrerReward); emit Transfer(address(0), referrer, referrerReward); } balances[msg.sender] = balances[msg.sender].add(userReward); emit Mine(msg.sender, userReward); emit Transfer(address(0), msg.sender, userReward); //update limits miningTotalDeposited = miningTotalDeposited.sub(amountToBurn); emit MiningBalanceUpdated(msg.sender, amountToBurn, false); //set system fee uint systemFee = mintedAmount.sub(userReward).sub(referrerReward); balances[systemAddress] = balances[systemAddress].add(systemFee); emit Mine(systemAddress, systemFee); emit Transfer(address(0), systemAddress, systemFee); lastMiningBalanceUpdateTime[msg.sender] = now; //assign to clan address mintClanReward(mintedAmount.mul(5).div(1000)); } function mintClanReward(uint reward) private { //check if user has a clan address clanAddress = joinedClans[msg.sender]; if(clanAddress != address(0x0)) { // check if this clan is registered require(clanRegistry[clanAddress], "clan is not registered"); // send appropriate amount of EMCO to clan address balances[clanAddress] = balances[clanAddress].add(reward); Clan clan = Clan(clanAddress); clan.replenish(reward); totalSupply_ = totalSupply_.add(reward); } } /** * @dev Set system address * @param _systemAddress An address to set */ function setSystemAddress(address _systemAddress) public onlyOwner { systemAddress = _systemAddress; } /** * @dev Get sum of deposits to mining accounts for current day */ function getCurrentDayDeposited() public view returns (uint) { if(now / 1 days == currentDay) { return currentDayDeposited; } else { return 0; } } /** * @dev Get number of days for reward on mining. Maximum 100 days. * @return An uint256 representing number of days user will get reward for. */ function getDaysForReward() public view returns (uint rewardDaysNum){ if(lastMiningBalanceUpdateTime[msg.sender] == 0) { return 0; } else { uint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days); if(value > 100) { return 100; } else { return value; } } } /** * @dev Calculate current mining reward based on total supply of tokens * @return An uint256 representing reward in percents multiplied by 1000000000 */ function getReward(uint _totalSupply) public pure returns (uint rewardPercent){ uint rewardFactor = 1000000 * (10 ** uint256(decimals)); uint decreaseFactor = 41666666; if(_totalSupply < 23 * rewardFactor) { return 2000000000 - (decreaseFactor.mul(_totalSupply.div(rewardFactor))); } if(_totalSupply < MAX_SUPPLY) { return 1041666666; } else { return 1000000000; } } function updateCurrentDayDeposited(uint _addedTokens) private { if(now / 1 days == currentDay) { currentDayDeposited = currentDayDeposited.add(_addedTokens); } else { currentDay = now / 1 days; currentDayDeposited = _addedTokens; } } }
Get sum of deposits to mining accounts for current day/
function getCurrentDayDeposited() public view returns (uint) { if(now / 1 days == currentDay) { return currentDayDeposited; return 0; } }
12,540,325
// SPDX-License-Identifier: MIT pragma solidity >0.6.10; //import "@opengsn/gsn/contracts/BaseRelayRecipient.sol"; import "./IERC20.sol"; import "./opengsn/BaseRelayRecipient.sol"; import "./opengsn/interfaces/IKnowForwarderAddress.sol"; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract SendMoney is BaseRelayRecipient, IKnowForwarderAddress { string public override versionRecipient = "0.0.1"; constructor(address _forwarder) public { trustedForwarder = _forwarder; } /** * @param tokenAddr contract address of ERC20 token * @param receiver address of receiver * @param amount amount token amount in smallest denomination value */ function sendCoin(address tokenAddr, address receiver, uint amount) public returns(bool sufficient) { IERC20 token = IERC20(tokenAddr); token.approve(_msgSender(), amount); token.transferFrom(_msgSender(), receiver, amount); return true; } function getTrustedForwarder() public view override returns(address) { return trustedForwarder; } }
tokenAddr contract address of ERC20 token receiver address of receiver amount amount token amount in smallest denomination value/
function sendCoin(address tokenAddr, address receiver, uint amount) public returns(bool sufficient) { IERC20 token = IERC20(tokenAddr); token.approve(_msgSender(), amount); token.transferFrom(_msgSender(), receiver, amount); return true; }
6,352,341
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; //Interfaces import './interfaces/IUniswapV2Router02.sol'; //OpenZeppelin import "./openzeppelin-solidity/contracts/ERC20/SafeERC20.sol"; import "./openzeppelin-solidity/contracts/ERC20/IERC20.sol"; import "./openzeppelin-solidity/contracts/Ownable.sol"; contract SeedLiquidity is Ownable { using SafeERC20 for IERC20; IUniswapV2Router02 public immutable ubeswapRouter; IERC20 public immutable CELO; IERC20 public TGEN; constructor(address _ubeswapRouter, address _CELO) Ownable() { require(_ubeswapRouter != address(0), "SeedLiquidity: Invalid address for Ubeswap router."); require(_CELO != address(0), "SeedLiquidity: Invalid address for CELO."); ubeswapRouter = IUniswapV2Router02(_ubeswapRouter); CELO = IERC20(_CELO); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Sets the address of TGEN. * @dev The TGEN address is initialized outside of the constructor because the TradegenToken contract * expects this contract to already be deployed. */ function setTGEN(address _TGEN) external onlyOwner { require(address(TGEN) == address(0), "SeedLiquidity: Already set TGEN."); TGEN = IERC20(_TGEN); emit SetTGEN(_TGEN); } /** * @notice Supplies TGEN-CELO seed liquidity with the contract's available TGEN and CELO. */ function supplySeedLiquidity() external onlyOwner { require(address(TGEN) != address(0), "SeedLiquidity: TGEN is not set."); require(TGEN.balanceOf(address(this)) > 0, "SeedLiquidity: Not enough TGEN."); require(CELO.balanceOf(address(this)) > 0, "SeedLiquidity: Not enough CELO."); TGEN.approve(address(ubeswapRouter), TGEN.balanceOf(address(this))); CELO.approve(address(ubeswapRouter), CELO.balanceOf(address(this))); (uint256 amountOfTGEN, uint256 amountOfCELO, uint256 numberOfLPTokens) = ubeswapRouter.addLiquidity(address(TGEN), address(CELO), TGEN.balanceOf(address(this)), CELO.balanceOf(address(this)), 0, 0, address(this), block.timestamp + 10000); renounceOwnership(); emit SuppliedLiquidity(amountOfTGEN, amountOfCELO, numberOfLPTokens); } /* ========== EVENTS ========== */ event SetTGEN(address tokenAddress); event SuppliedLiquidity(uint256 amountOfTGEN, uint256 amountOfCELO, uint256 numberOfLPTokens); }
Sets the address of TGEN. The TGEN address is initialized outside of the constructor because the TradegenToken contract expects this contract to already be deployed./
function setTGEN(address _TGEN) external onlyOwner { require(address(TGEN) == address(0), "SeedLiquidity: Already set TGEN."); TGEN = IERC20(_TGEN); emit SetTGEN(_TGEN); }
879,592
./full_match/80001/0xf4Bf35F8f17cAf2ee780e9BD6Ee4a6c5Eb61b6C2/sources/project:/contracts/superfluid/FlowNFTBase.sol
@inheritdoc IERC721
function transferFrom(address from, address to, uint256 tokenId) external virtual override { if (!_isApprovedOrOwner(msg.sender, tokenId)) { revert CFA_NFT_TRANSFER_CALLER_NOT_OWNER_OR_APPROVED_FOR_ALL(); } _transfer(from, to, tokenId); }
9,524,880
./partial_match/1/0x82a90C0FF84F8cEe692C9C6C7351DA28bB331154/sources/lib/mip21-toolkit/src/conduits/RwaSwapOutputConduit.sol
Updates a contract parameter. what The changed parameter name. `"quitTo", "psm"`. data The new value of the parameter./ Revoke approval for the old PSM Give unlimited approval to the new PSM
function file(bytes32 what, address data) external auth { if (what == "quitTo") { quitTo = data; require(PsmAbstract(data).dai() == address(dai), "RwaSwapOutputConduit/wrong-dai-for-psm"); require( GemJoinAbstract(PsmAbstract(data).gemJoin()).gem() == address(gem), "RwaSwapOutputConduit/wrong-gem-for-psm" ); dai.approve(address(psm), 0); dai.approve(data, type(uint256).max); psm = PsmAbstract(data); revert("RwaSwapOutputConduit/unrecognised-param"); } emit File(what, data); }
3,691,857
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } 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); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/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"); } } } // Dependency file: contracts/interfaces/IDePayRouterV1Plugin.sol // pragma solidity >=0.7.5 <0.8.0; pragma abicoder v2; interface IDePayRouterV1Plugin { function execute( address[] calldata path, uint[] calldata amounts, address[] calldata addresses, string[] calldata data ) external payable returns(bool); function delegate() external returns(bool); } // Dependency file: contracts/libraries/Helper.sol // Helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library Helper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Helper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Helper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Helper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'Helper::safeTransferETH: ETH transfer failed'); } } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/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. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: contracts/DePayRouterV1Configuration.sol // pragma solidity >=0.7.5 <0.8.0; // import "@openzeppelin/contracts/access/Ownable.sol"; // Prevents unwanted access to configuration in DePayRouterV1 // Potentially occuring through delegatecall(ing) plugins. contract DePayRouterV1Configuration is Ownable { // List of approved plugins. Use approvePlugin to add new plugins. mapping (address => address) public approvedPlugins; // Approves the provided plugin. function approvePlugin(address plugin) external onlyOwner returns(bool) { approvedPlugins[plugin] = plugin; emit PluginApproved(plugin); return true; } // Event to emit newly approved plugin. event PluginApproved( address indexed pluginAddress ); // Disapproves the provided plugin. function disapprovePlugin(address plugin) external onlyOwner returns(bool) { approvedPlugins[plugin] = address(0); emit PluginDisapproved(plugin); return true; } // Event to emit disapproved plugin. event PluginDisapproved( address indexed pluginAddress ); } // Root file: contracts/DePayRouterV1.sol pragma solidity >=0.7.5 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import 'contracts/interfaces/IDePayRouterV1Plugin.sol'; // import 'contracts/libraries/Helper.sol'; // import 'contracts/DePayRouterV1Configuration.sol'; contract DePayRouterV1 { using SafeMath for uint; using SafeERC20 for IERC20; // Address representating ETH (e.g. in payment routing paths) address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Instance of DePayRouterV1Configuration DePayRouterV1Configuration public immutable configuration; // Pass immutable instance to configuration. // This protects from potential delegatecall and access overlay attacks: // https://github.com/DePayFi/depay-ethereum-payments/blob/master/docs/Audit3.md#H02 constructor ( address _configuration ) public { configuration = DePayRouterV1Configuration(_configuration); } // Proxy modifier to DePayRouterV1Configuration modifier onlyOwner() { require(configuration.owner() == msg.sender, "Ownable: caller is not the owner"); _; } receive() external payable { // Accepts ETH payments which is require in order // to swap from and to ETH // especially unwrapping WETH as part of token swaps. } // The main function to route transactions. function route( // The path of the token conversion. address[] calldata path, // Amounts passed to proccessors: // e.g. [amountIn, amountOut, deadline] uint[] calldata amounts, // Addresses passed to plugins: // e.g. [receiver] address[] calldata addresses, // List and order of plugins to be executed for this payment: // e.g. [Uniswap,paymentPlugin] to swap and pay address[] calldata plugins, // Data passed to plugins: // e.g. ["signatureOfSmartContractFunction(address,uint)"] receiving the payment string[] calldata data ) external payable returns(bool) { uint balanceBefore = _balanceBefore(path[path.length-1]); _ensureTransferIn(path[0], amounts[0]); _execute(path, amounts, addresses, plugins, data); _ensureBalance(path[path.length-1], balanceBefore); return true; } // Returns the balance for a token (or ETH) before the payment is executed. // In case of ETH we need to deduct what has been payed in as part of the transaction itself. function _balanceBefore(address token) private returns (uint balance) { balance = _balance(token); if(token == ETH) { balance -= msg.value; } } // This makes sure that the sender has payed in the token (or ETH) // required to perform the payment. function _ensureTransferIn(address tokenIn, uint amountIn) private { if(tokenIn == ETH) { require(msg.value >= amountIn, 'DePay: Insufficient ETH amount payed in!'); } else { Helper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); } } // Executes plugins in the given order. function _execute( address[] calldata path, uint[] calldata amounts, address[] calldata addresses, address[] calldata plugins, string[] calldata data ) internal { for (uint i = 0; i < plugins.length; i++) { require(_isApproved(plugins[i]), 'DePay: Plugin not approved!'); IDePayRouterV1Plugin plugin = IDePayRouterV1Plugin(configuration.approvedPlugins(plugins[i])); if(plugin.delegate()) { (bool success, bytes memory returnData) = address(plugin).delegatecall(abi.encodeWithSelector( plugin.execute.selector, path, amounts, addresses, data )); require(success, string(returnData)); } else { (bool success, bytes memory returnData) = address(plugin).call(abi.encodeWithSelector( plugin.execute.selector, path, amounts, addresses, data )); require(success, string(returnData)); } } } // This makes sure that the balance after the payment not less than before. // Prevents draining of the contract. function _ensureBalance(address tokenOut, uint balanceBefore) private view { require(_balance(tokenOut) >= balanceBefore, 'DePay: Insufficient balance after payment!'); } // Returns the balance of the payment plugin contract for a token (or ETH). function _balance(address token) private view returns(uint) { if(token == ETH) { return address(this).balance; } else { return IERC20(token).balanceOf(address(this)); } } // Function to check if a plugin address is approved. function isApproved( address pluginAddress ) external view returns(bool){ return _isApproved(pluginAddress); } // Internal function to check if a plugin address is approved. function _isApproved( address pluginAddress ) internal view returns(bool) { return (configuration.approvedPlugins(pluginAddress) != address(0)); } // Allows to withdraw accidentally sent ETH or tokens. function withdraw( address token, uint amount ) external onlyOwner returns(bool) { if(token == ETH) { Helper.safeTransferETH(payable(configuration.owner()), amount); } else { Helper.safeTransfer(token, payable(configuration.owner()), amount); } return true; } }
Executes plugins in the given order.
function _execute( address[] calldata path, uint[] calldata amounts, address[] calldata addresses, address[] calldata plugins, string[] calldata data ) internal { for (uint i = 0; i < plugins.length; i++) { require(_isApproved(plugins[i]), 'DePay: Plugin not approved!'); IDePayRouterV1Plugin plugin = IDePayRouterV1Plugin(configuration.approvedPlugins(plugins[i])); if(plugin.delegate()) { (bool success, bytes memory returnData) = address(plugin).delegatecall(abi.encodeWithSelector( plugin.execute.selector, path, amounts, addresses, data )); require(success, string(returnData)); (bool success, bytes memory returnData) = address(plugin).call(abi.encodeWithSelector( plugin.execute.selector, path, amounts, addresses, data )); require(success, string(returnData)); } } }
197,310
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "./Interfaces.sol"; contract Ticker { ENSRegistryWithFallback ens; constructor() { ens = ENSRegistryWithFallback(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); // The ens registry address is shared across testnets and mainnet } // Enter 'uni' to lookup uni.tkn.eth function addressFor(string calldata _name) public view returns (address) { bytes32 namehash = 0x0000000000000000000000000000000000000000000000000000000000000000; namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked('eth'))) ); namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked('tkn'))) ); namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked(_name))) ); address resolverAddr = ens.resolver(namehash); PublicResolver resolver = PublicResolver(resolverAddr); return resolver.addr(namehash); } struct Metadata { address contractAddress; string name; string url; string avatar; string description; string notice; string twitter; string github; } function infoFor(string calldata _name) public view returns (Metadata memory) { bytes32 namehash = 0x0000000000000000000000000000000000000000000000000000000000000000; namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked('eth'))) ); namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked('tkn'))) ); namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked(_name))) ); address resolverAddr = ens.resolver(namehash); PublicResolver resolver = PublicResolver(resolverAddr); return Metadata( resolver.addr(namehash), resolver.text(namehash, "name"), resolver.text(namehash, "url"), resolver.text(namehash, "avatar"), resolver.text(namehash, "description"), resolver.text(namehash, "notice"), resolver.text(namehash, "com.twitter"), resolver.text(namehash, "com.github") ); } // Calculate the namehash offchain using eth-ens-namehash to save gas costs. // Better for write queries that require gas // Library: https://npm.runkit.com/eth-ens-namehash function gasEfficientFetch(bytes32 namehash) public view returns (address) { address resolverAddr = ens.resolver(namehash); PublicResolver resolver = PublicResolver(resolverAddr); return resolver.addr(namehash); } // Get an account's balance using a ticker symbol function balanceWithTicker(address user, string calldata tickerSymbol) public view returns (uint) { IERC20 tokenContract = IERC20(addressFor(tickerSymbol)); return tokenContract.balanceOf(user); } } interface ETHRegistrarController { function MIN_REGISTRATION_DURATION ( ) external view returns ( uint256 ); function available ( string calldata name ) external view returns ( bool ); function commit ( bytes32 commitment ) external; function commitments ( bytes32 ) external view returns ( uint256 ); function isOwner ( ) external view returns ( bool ); function makeCommitment ( string calldata name, address owner, bytes32 secret ) external pure returns ( bytes32 ); function makeCommitmentWithConfig ( string calldata name, address owner, bytes32 secret, address resolver, address addr ) external pure returns ( bytes32 ); function maxCommitmentAge ( ) external view returns ( uint256 ); function minCommitmentAge ( ) external view returns ( uint256 ); function owner ( ) external view returns ( address ); function register ( string calldata name, address owner, uint256 duration, bytes32 secret ) external payable; function registerWithConfig ( string calldata name, address owner, uint256 duration, bytes32 secret, address resolver, address addr ) external payable; function renew ( string calldata name, uint256 duration ) external payable; function renounceOwnership ( ) external; function rentPrice ( string calldata name, uint256 duration ) external view returns ( uint256 ); function setCommitmentAges ( uint256 _minCommitmentAge, uint256 _maxCommitmentAge ) external; function setPriceOracle ( address _prices ) external; function supportsInterface ( bytes4 interfaceID ) external pure returns ( bool ); function transferOwnership ( address newOwner ) external; function valid ( string calldata name ) external pure returns ( bool ); function withdraw ( ) external; } interface BaseRegistrarImplementation { function GRACE_PERIOD ( ) external view returns ( uint256 ); function addController ( address controller ) external; function approve ( address to, uint256 tokenId ) external; function available ( uint256 id ) external view returns ( bool ); function balanceOf ( address owner ) external view returns ( uint256 ); function baseNode ( ) external view returns ( bytes32 ); function controllers ( address ) external view returns ( bool ); function ens ( ) external view returns ( address ); function getApproved ( uint256 tokenId ) external view returns ( address ); function isApprovedForAll ( address owner, address operator ) external view returns ( bool ); function isOwner ( ) external view returns ( bool ); function nameExpires ( uint256 id ) external view returns ( uint256 ); function owner ( ) external view returns ( address ); function ownerOf ( uint256 tokenId ) external view returns ( address ); function reclaim ( uint256 id, address owner ) external; function register ( uint256 id, address owner, uint256 duration ) external returns ( uint256 ); function registerOnly ( uint256 id, address owner, uint256 duration ) external returns ( uint256 ); function removeController ( address controller ) external; function renew ( uint256 id, uint256 duration ) external returns ( uint256 ); function renounceOwnership ( ) external; function safeTransferFrom ( address from, address to, uint256 tokenId ) external; function safeTransferFrom ( address from, address to, uint256 tokenId, bytes calldata _data ) external; function setApprovalForAll ( address to, bool approved ) external; function setResolver ( address resolver ) external; function supportsInterface ( bytes4 interfaceID ) external view returns ( bool ); function transferFrom ( address from, address to, uint256 tokenId ) external; function transferOwnership ( address newOwner ) external; } interface ENSRegistryWithFallback { function isApprovedForAll ( address owner, address operator ) external view returns ( bool ); function old ( ) external view returns ( address ); function owner ( bytes32 node ) external view returns ( address ); function recordExists ( bytes32 node ) external view returns ( bool ); function resolver ( bytes32 node ) external view returns ( address ); function setApprovalForAll ( address operator, bool approved ) external; function setOwner ( bytes32 node, address owner ) external; function setRecord ( bytes32 node, address owner, address resolver, uint64 ttl ) external; function setResolver ( bytes32 node, address resolver ) external; function setSubnodeOwner ( bytes32 node, bytes32 label, address owner ) external returns ( bytes32 ); function setSubnodeRecord ( bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl ) external; function setTTL ( bytes32 node, uint64 ttl ) external; function ttl ( bytes32 node ) external view returns ( uint64 ); } pragma experimental ABIEncoderV2; interface PublicResolver { function ABI ( bytes32 node, uint256 contentTypes ) external view returns ( uint256, bytes memory ); function addr ( bytes32 node ) external view returns ( address ); function addr ( bytes32 node, uint256 coinType ) external view returns ( bytes memory ); function authorisations ( bytes32, address, address ) external view returns ( bool ); function clearDNSZone ( bytes32 node ) external; function contenthash ( bytes32 node ) external view returns ( bytes memory ); function dnsRecord ( bytes32 node, bytes32 name, uint16 resource ) external view returns ( bytes memory ); function hasDNSRecords ( bytes32 node, bytes32 name ) external view returns ( bool ); function interfaceImplementer ( bytes32 node, bytes4 interfaceID ) external view returns ( address ); function multicall ( bytes[] calldata data ) external returns ( bytes[] memory results ); function name ( bytes32 node ) external view returns ( string memory ); function pubkey ( bytes32 node ) external view returns ( bytes32 x, bytes32 y ); function setABI ( bytes32 node, uint256 contentType, bytes calldata data ) external; function setAddr ( bytes32 node, uint256 coinType, bytes calldata a ) external; function setAddr ( bytes32 node, address a ) external; function setAuthorisation ( bytes32 node, address target, bool isAuthorised ) external; function setContenthash ( bytes32 node, bytes calldata hash ) external; function setDNSRecords ( bytes32 node, bytes calldata data ) external; function setInterface ( bytes32 node, bytes4 interfaceID, address implementer ) external; function setName ( bytes32 node, string calldata name ) external; function setPubkey ( bytes32 node, bytes32 x, bytes32 y ) external; function setText ( bytes32 node, string calldata key, string calldata value ) external; function supportsInterface ( bytes4 interfaceID ) external pure returns ( bool ); function text ( bytes32 node, string calldata key ) external view returns ( string memory ); } // Chainlink Gas Price Oracle // Authorized proxy link contract from: https://docs.chain.link/docs/ethereum-addresses#config contract EACAggregatorProxy { function acceptOwnership ( ) external { } function accessController ( ) external view returns ( address ) { } function aggregator ( ) external view returns ( address ) { } function confirmAggregator ( address _aggregator ) external { } function decimals ( ) external view returns ( uint8 ) { } function description ( ) external view returns ( string memory ) { } function getAnswer ( uint256 _roundId ) external view returns ( int256 ) { } function getRoundData ( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { } function getTimestamp ( uint256 _roundId ) external view returns ( uint256 ) { } function latestAnswer ( ) external view returns ( int256 ) { // Stub out 55 gwei static gas price for querying on testnet return 55555555555; // return 0x0000000000000000000000000000000000000000000000000000000d4576fa00; } function latestRound ( ) external view returns ( uint256 ) { } function latestRoundData ( ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { } function latestTimestamp ( ) external view returns ( uint256 ) { } function owner ( ) external view returns ( address ) { } function phaseAggregators ( uint16 ) external view returns ( address ) { } function phaseId ( ) external view returns ( uint16 ) { } function proposeAggregator ( address _aggregator ) external { } function proposedAggregator ( ) external view returns ( address ) { } function proposedGetRoundData ( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { } function proposedLatestRoundData ( ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { } function setController ( address _accessController ) external { } function transferOwnership ( address _to ) external { } function version ( ) external view returns ( uint256 ) { } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
13,695,531
./full_match/5/0x5137ABFf24ad5b7f8079F7f9BfCDB5645e490526/sources/project_/contracts/ERC1644/IERC1644.sol
Controller Operation Controller Events
interface IERC1644 { function isControllable() external view returns (bool); function controllerTransfer(address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external; function controllerRedeem(address _tokenHolder, uint256 _value, bytes calldata _data, bytes calldata _operatorData) external; event ControllerTransfer( address _controller, address indexed _from, address indexed _to, uint256 _value, bytes _data, bytes _operatorData ); event ControllerRedemption( address _controller, address indexed _tokenHolder, uint256 _value, bytes _data, bytes _operatorData ); }
11,594,547
pragma solidity ^0.4.0; contract MindMathGame { event GameCreated(int game_score, int game_power_up, address game_address ); event GameUpdated(int game_score, int game_power_up, address game_address ); struct game { int game_score; //Store game score int game_power_up; //Store game pwoer up, possible v alues 1, 10, 100, 1000, 10000, 100000 } // Store fore each user account score and last PowerUp bought mapping (address => game) games; address owner; // Only owner is allowed to modify data in the contract but evryone can view it // Init contract owner. Only owner is allowed to update the values function MindMathGameSetOwner() public { owner = msg.sender; } // Create new game function createGame( address game_address ) public returns (address) { // If it is not owner, don't allow game creation if (msg.sender != owner) return; games[game_address].game_score = 0; games[game_address].game_power_up = 1; emit GameCreated(games[game_address].game_score, games[game_address].game_power_up, game_address); // Send event back to game client that game is created return game_address; } // Update game score function updateGameScore(int score_new, address game_address ) public returns (bool updated) { // If it is not owner, don't allow game creation if (msg.sender != owner) return; // Allow only positive socre to be stored here if( score_new >= 0 ) { games[game_address].game_score = score_new; emit GameUpdated(games[game_address].game_score, games[game_address].game_power_up, game_address); // Send event back to game client that game is updated return true; } return false; } // Read the game details for address function getGameDetails( address game_address ) public returns (int score) { emit GameUpdated(games[game_address].game_score, games[game_address].game_power_up, game_address); // Send event back to game client that game is updated return games[game_address].game_score; } /// Buy power up if player has enough score points in the account. function buyPowerUp(int power_up_amount, address game_address ) public returns (bool sufficient) { // If it is not owner, don't allow game creation if (msg.sender != owner) return; if( power_up_amount > 0 ) { if( games[game_address].game_score - power_up_amount < 0 ) return false; // Insuficenet Funds games[game_address].game_score = games[game_address].game_score - power_up_amount; games[game_address].game_power_up = power_up_amount; emit GameUpdated(games[game_address].game_score, games[game_address].game_power_up, game_address); // Send event back to game client that game is updated return true; // PowerUp successfully bought } return false; // Negaitve PowerUpAmmount not supported } }
Read the game details for address
function getGameDetails( address game_address ) public returns (int score) { return games[game_address].game_score; }
12,777,999
./partial_match/1/0x508efB44A06a64Bd4020e8c5e8Ecf1A9236C75aE/sources/wallet.sol
Confirm pending removal of whitelisted addresses. Require that the pending whitelist is not empty and the operation has been submitted. Require that confirmation hash and the hash of the pending whitelist removal match Remove pending addresses. check if it exists
function confirmWhitelistRemoval(bytes32 _hash) external onlyController { require(submittedWhitelistRemoval, "no pending submission"); require(_hash == calculateHash(_pendingWhitelistRemoval), "non-matching pending whitelist hash"); for (uint256 i = 0; i < _pendingWhitelistRemoval.length; i++) { if (whitelistMap[_pendingWhitelistRemoval[i]]) { whitelistMap[_pendingWhitelistRemoval[i]] = false; for (uint256 j = 0; j < whitelistArray.length.sub(1); j++) { if (whitelistArray[j] == _pendingWhitelistRemoval[i]) { whitelistArray[j] = whitelistArray[whitelistArray.length - 1]; break; } } whitelistArray.length--; } } }
3,597,830
./full_match/97/0x0e6d132D60D7af9fC948F75f93745094c35B15CA/sources/contracts/SmartTestament.sol
Delete testament for message sender
function deleteTestament() external { require( getTestamentState(msg.sender) < TestamentState.Unlocked, "alive only" ); delete testaments[msg.sender]; emit TestamentDeleted(msg.sender); }
5,036,378
//---------------------------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2016-2019 zOS Global Limited // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //---------------------------------------------------------------------------------------------- pragma solidity ^0.5.2; import "./ERC721Basic.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ contract ERC721Burnable is ERC721Basic { /** * @dev Burns a specific ERC721 token. * @param tokenId uint256 id of the ERC721 token to be burned. */ function burn(uint256 tokenId) public { require(_isValidSpender(msg.sender, tokenId)); _burn(tokenId); } }
Burns a specific ERC721 token. tokenId uint256 id of the ERC721 token to be burned./
function burn(uint256 tokenId) public { require(_isValidSpender(msg.sender, tokenId)); _burn(tokenId); }
13,107,294
pragma solidity >0.5.4; import "@daostack/arc/contracts/controller/Avatar.sol"; import "@daostack/arc/contracts/controller/ControllerInterface.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../../identity/Identity.sol"; import "../../identity/IdentityGuard.sol"; import "../../token/GoodDollar.sol"; import "./ActivePeriod.sol"; import "./FeelessScheme.sol"; /* @title Base contract template for UBI scheme */ contract AbstractUBI is ActivePeriod, FeelessScheme { using SafeMath for uint256; uint256 initialReserve; uint256 public claimDistribution; struct Day { mapping(address => bool) hasClaimed; uint256 amountOfClaimers; uint256 claimAmount; } mapping(uint256 => Day) claimDay; mapping(address => uint256) public lastClaimed; uint256 public currentDay; event UBIStarted(uint256 balance, uint256 time); event UBIClaimed(address indexed claimer, uint256 amount); event UBIEnded(uint256 claimers, uint256 claimamount); /** * @dev Constructor. Checks if avatar is a zero address * and if periodEnd variable is after periodStart. * @param _avatar the avatar contract * @param _periodStart period from when the contract is able to start * @param _periodEnd period from when the contract is able to end */ constructor( Avatar _avatar, Identity _identity, uint256 _initialReserve, uint256 _periodStart, uint256 _periodEnd ) public ActivePeriod(_periodStart, _periodEnd, _avatar) FeelessScheme(_identity, _avatar) { initialReserve = _initialReserve; } /** * @dev function that returns an uint256 that * represents the amount each claimer can claim. * @param reserve the account balance to calculate from * @return The distribution for each claimer */ function distributionFormula(uint256 reserve, address user) internal returns (uint256); /* @dev function that gets the amount of people who claimed on the given day * @param day the day to get claimer count from, with 0 being the starting day * @return an integer indicating the amount of people who claimed that day */ function getClaimerCount(uint256 day) public view returns (uint256) { return claimDay[day].amountOfClaimers; } /* @dev function that gets the amount that was claimed on the given day * @param day the day to get claimer count from, with 0 being the starting day * @return an integer indicating the amount that has been claimed on the given day */ function getClaimAmount(uint256 day) public view returns (uint256) { return claimDay[day].claimAmount; } /* @dev function that gets count of claimers and amount claimed for the current day * @return the amount of claimers and the amount claimed. */ function getDailyStats() public view returns (uint256 count, uint256 amount) { uint256 today = (now.sub(periodStart)) / 1 days; return (getClaimerCount(today), getClaimAmount(today)); } /* @dev Function that commences distribution period on contract. * Can only be called after periodStart and before periodEnd and * can only be done once. The reserve is sent * to this contract to allow claimers to claim from said reserve. * The claim distribution is then calculated and true is returned * to indicate that claiming can be done. */ function start() public onlyRegistered { super.start(); addRights(); currentDay = now.sub(periodStart) / 1 days; // Transfer the fee reserve to this contract DAOToken token = avatar.nativeToken(); if (initialReserve > 0) { require( initialReserve <= token.balanceOf(address(avatar)), "Not enough funds to start" ); controller.genericCall( address(token), abi.encodeWithSignature( "transfer(address,uint256)", address(this), initialReserve ), avatar, 0 ); } emit UBIStarted(token.balanceOf(address(this)), now); } /** * @dev Function that ends the claiming period. Can only be done if * Contract has been started and periodEnd is passed. * Sends the remaining funds on contract back to the avatar contract * address */ function end() public requirePeriodEnd { DAOToken token = avatar.nativeToken(); uint256 remainingReserve = token.balanceOf(address(this)); if (remainingReserve > 0) { require( token.transfer(address(avatar), remainingReserve), "end transfer failed" ); } removeRights(); super.end(); } /* @dev UBI claiming function. Can only be called by users that were * whitelisted before start of contract * Each claimer can only claim once per UBI contract * @return true if the user claimed successfully */ function claim() public requireActive onlyWhitelisted onlyAddedBefore(periodStart) returns (bool) { require(!claimDay[currentDay].hasClaimed[msg.sender], "has already claimed"); claimDay[currentDay].hasClaimed[msg.sender] = true; GoodDollar token = GoodDollar(address(avatar.nativeToken())); claimDay[currentDay].amountOfClaimers = claimDay[currentDay].amountOfClaimers.add( 1 ); claimDay[currentDay].claimAmount = claimDay[currentDay].claimAmount.add( claimDistribution ); lastClaimed[msg.sender] = now; require(token.transfer(msg.sender, claimDistribution), "claim transfer failed"); emit UBIClaimed(msg.sender, claimDistribution); return true; } } /* @title UBI scheme contract responsible for calculating a distribution * based on amount of whitelisted users */ contract UBI is AbstractUBI { uint256 claimers; /* @dev Constructor. Checks if avatar is a zero address * and if periodEnd variable is after periodStart. * @param _avatar the avatar contract * @param _identity the identity contract * @param _periodStart period from when the contract is able to start * @param _periodEnd period from when the contract is able to end */ constructor( Avatar _avatar, Identity _identity, uint256 _initialReserve, uint256 _periodStart, uint256 _periodEnd ) public AbstractUBI(_avatar, _identity, _initialReserve, _periodStart, _periodEnd) { claimers = (identity.whitelistedCount()).sub(identity.whitelistedContracts()); } /* @dev function that calculated the amount each claimer can claim. * amount to claim is the amount of GoodDollar contract holds * divided by amount of eligible claimers * @param reserve the account balance to calculate from * @return The reserve divided by the amount of registered claimers */ function distributionFormula( uint256 reserve, address /*user*/ ) internal returns (uint256) { return reserve.div(claimers); } /* @dev starts scheme and calculates distribution of UBI */ function start() public { super.start(); DAOToken token = avatar.nativeToken(); claimDistribution = distributionFormula( token.balanceOf(address(this)), address(0) ); } }
function that gets count of claimers and amount claimed for the current day return the amount of claimers and the amount claimed./
function getDailyStats() public view returns (uint256 count, uint256 amount) { uint256 today = (now.sub(periodStart)) / 1 days; return (getClaimerCount(today), getClaimAmount(today)); }
5,351,699
./partial_match/4/0x13845842390067045a22a00d7Dd2f9bd6ead2Df9/sources/GalaxyNFT.sol
Withdraw NFT tokens from Interstellar.
function withdraw(uint256 _pid, uint256 _amount, bytes calldata _data) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accMilkPerShare).div(1e12).sub(user.rewardDebt); safeMilkTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accMilkPerShare).div(1e12); NFTToken.safeTransferFrom(address(msg.sender), address(this), pool.nftId, _amount, _data); emit Withdraw(msg.sender, _pid, _amount); }
16,973,366
./full_match/77/0xcA47f86f29Ab274257792a2Cf24B7299d449cF06/sources/deploy/contracts/synthereum-pool/v5/LiquidityPool.sol
Get the synthetic token associated to this pool return syntheticCurrency The ERC20 synthetic token/
function syntheticToken() external view override returns (IERC20 syntheticCurrency) { syntheticCurrency = poolStorage.syntheticToken; }
5,047,240
./partial_match/3/0xE5dD5466314a590680d107B2Dea8114cd694BBfd/sources/Strategy.sol
Used to change `maxReportDelay`. `maxReportDelay` is the maximum number of blocks that should pass for `harvest()` to be called. For external keepers (such as the Keep3r network), this is the maximum time between jobs to wait. (see `harvestTrigger()` for more details.) This may only be called by governance or the strategist. _delay The maximum number of seconds to wait between harvests./
function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedReportDelay(_delay); }
5,277,467
./full_match/1/0x640216Ea5b2aC018b1d1FDB3F0a206F652C92574/sources/contracts/MemberRegistry/MemberRegistry.sol
Returns the token URI associated with the given token ID. tokenId_ The token ID for which to get the associated token URI. return The token URI associated with the token ID as a string. This function is overridden from the ERC721 standard./
function tokenURI( uint256 tokenId_ ) public view virtual override returns (string memory) { if (!_exists(tokenId_)) revert URIQueryForNonexistentToken(); return IMemberTokenURI(_router.route(IMemberRouter.RouterKey.TOKEN_URI)) .tokenURI(address(this), tokenId_); }
9,808,470
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./interfaces/IModuleBase.sol"; /// @notice An abstract contract to be inherited by module contracts abstract contract ModuleBase is IModuleBase, UUPSUpgradeable, ERC165 { IDAOAccessControl public accessControl; address public moduleFactory; string internal _name; /// @notice Requires that a function caller has the associated role modifier authorized() { if ( !accessControl.actionIsAuthorized( msg.sender, address(this), msg.sig ) ) { revert NotAuthorized(); } _; } /// @notice Function for initializing the contract that can only be called once /// @param _accessControl The address of the access control contract /// @param _moduleFactory The address of the factory deploying the module /// @param __name Human readable string of the module name function __initBase(address _accessControl, address _moduleFactory, string memory __name) internal onlyInitializing { accessControl = IDAOAccessControl(_accessControl); moduleFactory = _moduleFactory; _name = __name; __UUPSUpgradeable_init(); } /// @dev Applies authorized modifier so that an upgrade require the caller to have the correct role /// @param newImplementation The address of the new implementation contract being upgraded to function _authorizeUpgrade(address newImplementation) internal override authorized {} /// @notice Returns the module name /// @return The module name function name() public view virtual returns (string memory) { return _name; } /// @notice Returns whether a given interface ID is supported /// @param interfaceId An interface ID bytes4 as defined by ERC-165 /// @return bool Indicates whether the interface is supported function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IModuleBase) returns (bool) { return interfaceId == type(IModuleBase).interfaceId || super.supportsInterface(interfaceId); } }
Returns whether a given interface ID is supported interfaceId An interface ID bytes4 as defined by ERC-165 return bool Indicates whether the interface is supported
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IModuleBase) returns (bool) { return interfaceId == type(IModuleBase).interfaceId || super.supportsInterface(interfaceId); }
936,582
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens interface ERC721 { // Required methods function totalSupply() external view returns (uint256 total); function balanceOf(address _owner) external view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of pony 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of dad /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); // calculate the cooldown of child pony function processCooldown(uint16 childGen, uint256 targetBlock) public returns (uint16); // calculate the result for upgrading pony function upgradePonyResult(uint8 unicornation, uint256 targetBlock) public returns (bool); function setMatingSeason(bool _isMatingSeason) public returns (bool); } /// @title Interface for contracts conforming to ERC-20 interface ERC20 { //core ERC20 functions function transfer(address _to, uint _value) external returns (bool success); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool success); function transferPreSigned(bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce) external returns (bool); function recoverSigner(bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce) external view returns (address); } /** * @title Signature verifier * @dev To verify C level actions */ contract SignatureVerifier { function splitSignature(bytes sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recover(bytes32 hash, bytes sig) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables (v, r, s) = splitSignature(sig); // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); return ecrecover(prefixedHash, v, r, s); } } } /** * @title A DEKLA token access control * @author DEKLA (https://www.dekla.io) * @dev The Dekla token has 3 C level address to manage. * They can execute special actions but it need to be approved by another C level address. */ contract AccessControl is SignatureVerifier { using SafeMath for uint256; // C level address that can execute special actions. address public ceoAddress; address public cfoAddress; address public cooAddress; address public systemAddress; uint256 public CLevelTxCount_ = 0; mapping(address => uint256) nonces; // @dev C level transaction must be approved with another C level address modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } // @dev return true if transaction already signed by a C Level address // @param _message The string to be verify function signedByCLevel( bytes32 _message, bytes _sig ) internal view onlyCLevel returns (bool) { address signer = recover(_message, _sig); require(signer != msg.sender); return ( signer == cooAddress || signer == ceoAddress || signer == cfoAddress ); } // @dev return true if transaction already signed by a C Level address // @param _message The string to be verify // @param _sig the signature from signing the _message with system key function signedBySystem( bytes32 _message, bytes _sig ) internal view returns (bool) { address signer = recover(_message, _sig); require(signer != msg.sender); return ( signer == systemAddress ); } /** * @notice Hash (keccak256) of the payload used by setCEO * @param _newCEO address The address of the new CEO * @param _nonce uint256 setCEO transaction number. */ function getCEOHashing(address _newCEO, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E94), _newCEO, _nonce)); } // @dev Assigns a new address to act as the CEO. The C level transaction, must verify. // @param _newCEO The address of the new CEO // @param _sig the signature from signing the _message with CEO key function setCEO( address _newCEO, bytes _sig ) external onlyCLevel { require( _newCEO != address(0) && _newCEO != cfoAddress && _newCEO != cooAddress ); bytes32 hashedTx = getCEOHashing(_newCEO, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; ceoAddress = _newCEO; CLevelTxCount_++; } /** * @notice Hash (keccak256) of the payload used by setCFO * @param _newCFO address The address of the new CFO * @param _nonce uint256 setCFO transaction number. */ function getCFOHashing(address _newCFO, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E95), _newCFO, _nonce)); } // @dev Assigns a new address to act as the CFO. The C level transaction, must verify. // @param _newCFO The address of the new CFO function setCFO( address _newCFO, bytes _sig ) external onlyCLevel { require( _newCFO != address(0) && _newCFO != ceoAddress && _newCFO != cooAddress ); bytes32 hashedTx = getCFOHashing(_newCFO, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; cfoAddress = _newCFO; CLevelTxCount_++; } /** * @notice Hash (keccak256) of the payload used by setCOO * @param _newCOO address The address of the new COO * @param _nonce uint256 setCO transaction number. */ function getCOOHashing(address _newCOO, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E96), _newCOO, _nonce)); } // @dev Assigns a new address to act as the COO. The C level transaction, must verify. // @param _newCOO The address of the new COO, _sig signature used to verify COO address // @param _sig the signature from signing the _newCOO with 1 of the C-level key function setCOO( address _newCOO, bytes _sig ) external onlyCLevel { require( _newCOO != address(0) && _newCOO != ceoAddress && _newCOO != cfoAddress ); bytes32 hashedTx = getCOOHashing(_newCOO, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; cooAddress = _newCOO; CLevelTxCount_++; } function getNonces(address _sender) public view returns (uint256) { return nonces[_sender]; } } /// @title A facet of PonyCore that manages special access privileges. contract PonyAccessControl is AccessControl { /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBase is PonyAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new pony comes into existence. This obviously /// includes any time a pony is created through the giveBirth method, but it is also called /// when a new gen0 pony is created. event Birth(address owner, uint256 ponyId, uint256 matronId, uint256 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a pony /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Pony struct. Every pony in MyEtherPonies is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Pony { // The Pony's genetic code is packed into these 256-bits, the format is // sooper-sekret! A pony's genes never change. uint256 genes; // The timestamp from the block when this pony came into existence. uint64 birthTime; // The minimum timestamp after which this pony can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this Pony, set to 0 for gen0 ponies. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion ponies. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire pony for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a pony // is pregnant. Used to retrieve the genetic material for the new // pony when the birth transpires. uint32 matingWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Pony. This starts at zero // for gen0 ponies, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this ponies is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this pony. ponies minted by the EP contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other ponies is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; uint16 txCount; uint8 unicornation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a pony /// is bred, encouraging owners not to just keep breeding the same pony over /// and over again. Caps out at one week (a pony can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[10] public cooldowns = [ uint32(1 minutes), uint32(5 minutes), uint32(30 minutes), uint32(1 hours), uint32(4 hours), uint32(8 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; uint8[5] public incubators = [ uint8(5), uint8(10), uint8(15), uint8(20), uint8(25) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Pony struct for all Ponies in existence. The ID /// of each pony is actually an index into this array. Note that ID 0 is a genesispony, /// the unPony, the mythical beast that is the parent of all gen0 ponies. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, pony ID 0 is invalid... ;-) Pony[] ponies; /// @dev A mapping from ponies IDs to the address that owns them. All ponies have /// some valid owner address, even gen0 ponies are created with a non-zero owner. mapping(uint256 => address) public ponyIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping(address => uint256) ownershipTokenCount; /// @dev A mapping from PonyIDs to an address that has been approved to call /// transferFrom(). Each Pony can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping(uint256 => address) public ponyIndexToApproved; /// @dev A mapping from PonyIDs to an address that has been approved to use /// this Pony for siring via breedWith(). Each Pony can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping(uint256 => address) public matingAllowedToAddress; mapping(address => bool) public hasIncubator; /// @dev The address of the ClockAuction contract that handles sales of Ponies. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; BiddingClockAuction public biddingAuction; /// @dev Assigns ownership of a specific Pony to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of ponies is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership ponyIndexToOwner[_tokenId] = _to; // When creating new ponies _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the pony is transferred also clear sire allowances delete matingAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete ponyIndexToApproved[_tokenId]; } // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new Pony and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The Pony ID of the matron of this pony (zero for gen0) /// @param _sireId The Pony ID of the sire of this pony (zero for gen0) /// @param _generation The generation number of this pony, must be computed by caller. /// @param _genes The Pony's genetic code. /// @param _owner The inital owner of this pony, must be non-zero (except for the unPony, ID 0) function _createPony( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner, uint16 _cooldownIndex ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createPony() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); Pony memory _pony = Pony({ genes : _genes, birthTime : uint64(now), cooldownEndBlock : 0, matronId : uint32(_matronId), sireId : uint32(_sireId), matingWithId : 0, cooldownIndex : _cooldownIndex, generation : uint16(_generation), unicornation : 0, txCount : 0 }); uint256 newPonyId = ponies.push(_pony) - 1; require(newPonyId == uint256(uint32(newPonyId))); // emit the birth event emit Birth( _owner, newPonyId, uint256(_pony.matronId), uint256(_pony.sireId), _pony.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newPonyId); return newPonyId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The facet of the EtherPonies core contract that manages ownership, ERC-721 (draft) compliant. /// @author Dekla (https://www.dekla.io) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyOwnership is PonyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "EtherPonies"; string public constant symbol = "EP"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Pony. /// @param _claimant the address we are validating against. /// @param _tokenId pony id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ponyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Pony. /// @param _claimant the address we are confirming pony is approved for. /// @param _tokenId pony id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ponyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Ponies on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { ponyIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Ponies owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Pony to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// EtherPonies specifically) or your Pony may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Pony to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any ponies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // You can only send your own pony. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Pony via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Pony that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Pony owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Pony to be transfered. /// @param _to The address that should take ownership of the Pony. Can be any address, /// including the caller. /// @param _tokenId The ID of the Pony to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Ponies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Ponies currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return ponies.length - 1; } /// @notice Returns the address currently assigned ownership of a given Pony. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ponyIndexToOwner[_tokenId]; } /// @notice Returns a list of all Pony IDs assigned to an address. /// @param _owner The owner whose Ponies we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Pony array looking for ponies belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPonies = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all ponies have IDs starting at 1 and increasing // sequentially up to the totalPony count. uint256 ponyId; for (ponyId = 1; ponyId <= totalPonies; ponyId++) { if (ponyIndexToOwner[ponyId] == _owner) { result[resultIndex] = ponyId; resultIndex++; } } return result; } } function transferPreSignedHashing( address _token, address _to, uint256 _id, uint256 _nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E97), _token, _to, _id, _nonce)); } function transferPreSigned( bytes _signature, address _to, uint256 _id, uint256 _nonce ) public { require(_to != address(0)); // require(signatures[_signature] == false); bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _id, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); require(_to != address(this)); // You can only send your own pony. require(_owns(from, _id)); nonces[from]++; // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(from, _to, _id); } function approvePreSignedHashing( address _token, address _spender, uint256 _tokenId, uint256 _nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(_token, _spender, _tokenId, _nonce)); } function approvePreSigned( bytes _signature, address _spender, uint256 _tokenId, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); // require(signatures[_signature] == false); bytes32 hashedTx = approvePreSignedHashing(address(this), _spender, _tokenId, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); // Only an owner can grant transfer approval. require(_owns(from, _tokenId)); nonces[from]++; // Register the approval (replacing any previous approval). _approve(_tokenId, _spender); // Emit approval event. emit Approval(from, _spender, _tokenId); return true; } } /// @title A facet of PonyCore that manages Pony siring, gestation, and birth. /// @author Dekla (https://www.dekla.io) /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBreeding is PonyOwnership { /// @dev The Pregnant event is fired when two ponies successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant Ponies. uint256 public pregnantPonies; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given pony is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToMate(Pony _pon) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the pony has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_pon.matingWithId == 0) && (_pon.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isMatingPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = ponyIndexToOwner[_matronId]; address sireOwner = ponyIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || matingAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Pony, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _pony A reference to the Pony in storage which needs its timer started. function _triggerCooldown(Pony storage _pony) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _pony.cooldownEndBlock = uint64((cooldowns[_pony.cooldownIndex] / secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_pony.cooldownIndex < 13) { _pony.cooldownIndex += 1; } } function _triggerPregnant(Pony storage _pony, uint8 _incubator) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). if (_incubator > 0) { uint64 initialCooldown = uint64(cooldowns[_pony.cooldownIndex] / secondsPerBlock); _pony.cooldownEndBlock = uint64((initialCooldown - (initialCooldown * incubators[_incubator] / 100)) + block.number); } else { _pony.cooldownEndBlock = uint64((cooldowns[_pony.cooldownIndex] / secondsPerBlock) + block.number); } // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_pony.cooldownIndex < 13) { _pony.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Ponies. /// @param _addr The address that will be able to sire with your Pony. Set to /// address(0) to clear all siring approvals for this Pony. /// @param _sireId A Pony that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); matingAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Pony is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Pony _matron) private view returns (bool) { return (_matron.matingWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given pony is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _ponyId reference the id of the pony, any user can inquire about it function isReadyToMate(uint256 _ponyId) public view returns (bool) { require(_ponyId > 0); Pony storage pon = ponies[_ponyId]; return _isReadyToMate(pon); } /// @dev Checks whether a Pony is currently pregnant. /// @param _ponyId reference the id of the pony, any user can inquire about it function isPregnant(uint256 _ponyId) public view returns (bool) { require(_ponyId > 0); // A Pony is pregnant if and only if this field is set return ponies[_ponyId].matingWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Pony struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Pony struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Pony storage _matron, uint256 _matronId, Pony storage _sire, uint256 _sireId ) private view returns (bool) { // A Pony can't breed with itself! if (_matronId == _sireId) { return false; } // Ponies can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either pony is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Ponies can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function canMateWithViaAuction(uint256 _matronId, uint256 _sireId) public view returns (bool) { Pony storage matron = ponies[_matronId]; Pony storage sire = ponies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two ponies can breed together, including checks for /// ownership and siring approvals. Does NOT check that both ponies are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canMateWith(uint256 _matronId, uint256 _sireId) external view returns (bool) { require(_matronId > 0); require(_sireId > 0); Pony storage matron = ponies[_matronId]; Pony storage sire = ponies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isMatingPermitted(_sireId, _matronId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _mateWith(uint256 _matronId, uint256 _sireId, uint8 _incubator) internal { // Grab a reference to the Ponies from storage. Pony storage sire = ponies[_sireId]; Pony storage matron = ponies[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.matingWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerPregnant(matron, _incubator); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete matingAllowedToAddress[_matronId]; delete matingAllowedToAddress[_sireId]; // Every time a Pony gets pregnant, counter is incremented. pregnantPonies++; // Emit the pregnancy event. emit Pregnant(ponyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } function getIncubatorHashing( address _sender, uint8 _incubator, uint256 txCount ) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E98), _sender, _incubator, txCount)); } /// @notice Breed a Pony you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your pony pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Pony acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Pony acting as sire (will begin its siring cooldown if successful) function mateWithAuto(uint256 _matronId, uint256 _sireId, uint8 _incubator, bytes _sig) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); require(_isMatingPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Pony storage matron = ponies[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToMate(matron)); // Grab a reference to the potential sire Pony storage sire = ponies[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToMate(sire)); // Test that these ponies are a valid mating pair. require( _isValidMatingPair(matron, _matronId, sire, _sireId) ); if (_incubator == 0 && hasIncubator[msg.sender]) { _mateWith(_matronId, _sireId, _incubator); } else { bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); nonces[msg.sender]++; // All checks passed, Pony gets pregnant! if (!hasIncubator[msg.sender]) { hasIncubator[msg.sender] = true; } _mateWith(_matronId, _sireId, _incubator); } } /// @notice Have a pregnant Pony give birth! /// @param _matronId A Pony ready to give birth. /// @return The Pony ID of the new pony. /// @dev Looks at a given Pony and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new pony. The new Pony is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new pony will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new pony always goes to the mother's owner. function giveBirth(uint256 _matronId) external whenNotPaused returns (uint256) { // Grab a reference to the matron in storage. Pony storage matron = ponies[_matronId]; // Check that the matron is a valid pony. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.matingWithId; Pony storage sire = ponies[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // New Pony starts with the same cooldown as parent gen/20 uint16 cooldownIndex = geneScience.processCooldown(parentGen + 1, block.number); if (cooldownIndex > 13) { cooldownIndex = 13; } // Make the new pony! address owner = ponyIndexToOwner[_matronId]; uint256 ponyId = _createPony(_matronId, matron.matingWithId, parentGen + 1, childGenes, owner, cooldownIndex); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.matingWithId; // Every time a Pony gives birth counter is decremented. pregnantPonies--; // Send the balance fee to the person who made birth happen. msg.sender.transfer(autoBirthFee); // return the new pony's ID return ponyId; } function setMatingSeason(bool _isMatingSeason) external onlyCLevel { geneScience.setMatingSeason(_isMatingSeason); } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; uint256 price; bool allowPayDekla; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; ERC20 public tokens; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut = 500; // Map from token ID to their corresponding auction. mapping(uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId) ); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidEth(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; require(!auction.allowPayDekla); // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = auction.price; require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidDkl(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.allowPayDekla); // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = auction.price; require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; tokens.transfer(seller, sellerProceeds); } // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.price > 0); } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is AccessControl{ event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyCEO whenNotPaused public returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyCEO whenPaused public returns (bool) { paused = false; emit Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. constructor(address _nftAddress, address _tokenAddress) public { ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); tokens = ERC20(_tokenAddress); nonFungibleContract = candidateContract; } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyCEO external { Auction storage auction = tokenIdToAuction[_tokenId]; _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 price, bool allowPayDekla ) { Auction storage auction = tokenIdToAuction[_tokenId]; return ( auction.seller, auction.price, auction.allowPayDekla ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return auction.price; } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; uint256 public prizeCut = 100; uint256 public tokenDiscount = 100; address prizeAddress; // Delegate constructor constructor(address _nftAddr, address _tokenAddress, address _prizeAddress) public ClockAuction(_nftAddr, _tokenAddress) { prizeAddress = _prizeAddress; } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createEthAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); require(_price > 0); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, false ); _addAuction(_tokenId, auction); } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createDklAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); require(_price > 0); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, true ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the PonyCore contract because all bid methods /// should be wrapped. Also returns the pony to the /// seller rather than the winner. function bidEth(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bidEth(_tokenId, msg.value); // We transfer the pony back to the seller, the winner will get // the offspring uint256 prizeAmount = (msg.value * prizeCut) / 10000; prizeAddress.transfer(prizeAmount); _transfer(seller, _tokenId); } function bidDkl(uint256 _tokenId, uint256 _price, uint256 _fee, bytes _signature, uint256 _nonce) external whenNotPaused { address seller = tokenIdToAuction[_tokenId].seller; tokens.transferPreSigned(_signature, address(this), _price, _fee, _nonce); // _bid will throw if the bid or funds transfer fails _bidDkl(_tokenId, _price); tokens.transfer(msg.sender, _fee); address spender = tokens.recoverSigner(_signature, address(this), _price, _fee, _nonce); uint256 discountAmount = (_price * tokenDiscount) / 10000; uint256 prizeAmount = (_price * prizeCut) / 10000; tokens.transfer(prizeAddress, prizeAmount); tokens.transfer(spender, discountAmount); _transfer(seller, _tokenId); } function setCut(uint256 _prizeCut, uint256 _tokenDiscount) external { require(msg.sender == address(nonFungibleContract)); require(_prizeCut + _tokenDiscount < ownerCut); prizeCut = _prizeCut; tokenDiscount = _tokenDiscount; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); nftAddress.transfer(address(this).balance); } function withdrawDklBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); tokens.transfer(nftAddress, tokens.balanceOf(this)); } } /// @title Clock auction modified for sale of Ponies /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; uint256 public prizeCut = 100; uint256 public tokenDiscount = 100; address prizeAddress; // Tracks last 5 sale price of gen0 Pony sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor constructor(address _nftAddr, address _token, address _prizeAddress) public ClockAuction(_nftAddr, _token) { prizeAddress = _prizeAddress; } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createEthAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, false ); _addAuction(_tokenId, auction); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createDklAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, true ); _addAuction(_tokenId, auction); } function bidEth(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bidEth(_tokenId, msg.value); uint256 prizeAmount = (msg.value * prizeCut) / 10000; prizeAddress.transfer(prizeAmount); _transfer(msg.sender, _tokenId); } function bidDkl(uint256 _tokenId, uint256 _price, uint256 _fee, bytes _signature, uint256 _nonce) external whenNotPaused { address buyer = tokens.recoverSigner(_signature, address(this), _price, _fee, _nonce); tokens.transferPreSigned(_signature, address(this), _price, _fee, _nonce); // _bid will throw if the bid or funds transfer fails _bidDkl(_tokenId, _price); uint256 prizeAmount = (_price * prizeCut) / 10000; uint256 discountAmount = (_price * tokenDiscount) / 10000; tokens.transfer(buyer, discountAmount); tokens.transfer(prizeAddress, prizeAmount); _transfer(buyer, _tokenId); } function setCut(uint256 _prizeCut, uint256 _tokenDiscount) external { require(msg.sender == address(nonFungibleContract)); require(_prizeCut + _tokenDiscount < ownerCut); prizeCut = _prizeCut; tokenDiscount = _tokenDiscount; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); nftAddress.transfer(address(this).balance); } function withdrawDklBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); tokens.transfer(nftAddress, tokens.balanceOf(this)); } } /// @title Handles creating auctions for sale and siring of Ponies. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract PonyAuction is PonyBreeding { // @notice The auction contract variables are defined in PonyBase to allow // us to refer to them in PonyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of Ponies. // `siringAuction` refers to the auction for siring rights of Ponies. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Sets the reference to the bidding auction. /// @param _address - Address of bidding contract. function setBiddingAuctionAddress(address _address) external onlyCEO { BiddingClockAuction candidateContract = BiddingClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isBiddingClockAuction()); // Set the new contract address biddingAuction = candidateContract; } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function createEthSaleAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_PonyId)); _approve(_PonyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createEthAuction( _PonyId, msg.sender, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function delegateDklSaleAuction( uint256 _tokenId, uint256 _price, bytes _ponySig, uint256 _nonce ) external whenNotPaused { bytes32 hashedTx = approvePreSignedHashing(address(this), saleAuction, _tokenId, _nonce); address from = recover(hashedTx, _ponySig); // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(from, _tokenId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_tokenId)); approvePreSigned(_ponySig, saleAuction, _tokenId, _nonce); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createDklAuction( _tokenId, from, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function delegateDklSiringAuction( uint256 _tokenId, uint256 _price, bytes _ponySig, uint256 _nonce ) external whenNotPaused { bytes32 hashedTx = approvePreSignedHashing(address(this), siringAuction, _tokenId, _nonce); address from = recover(hashedTx, _ponySig); // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(from, _tokenId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_tokenId)); approvePreSigned(_ponySig, siringAuction, _tokenId, _nonce); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createDklAuction( _tokenId, from, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function delegateDklBidAuction( uint256 _tokenId, uint256 _price, bytes _ponySig, uint256 _nonce, uint16 _durationIndex ) external whenNotPaused { bytes32 hashedTx = approvePreSignedHashing(address(this), biddingAuction, _tokenId, _nonce); address from = recover(hashedTx, _ponySig); // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(from, _tokenId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_tokenId)); approvePreSigned(_ponySig, biddingAuction, _tokenId, _nonce); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. biddingAuction.createDklAuction(_tokenId, from, _durationIndex, _price); } /// @dev Put a Pony up for auction to be sire. /// Performs checks to ensure the Pony can be sired, then /// delegates to reverse auction. function createEthSiringAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); require(isReadyToMate(_PonyId)); _approve(_PonyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createEthAuction( _PonyId, msg.sender, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function createDklSaleAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_PonyId)); _approve(_PonyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createDklAuction( _PonyId, msg.sender, _price ); } /// @dev Put a Pony up for auction to be sire. /// Performs checks to ensure the Pony can be sired, then /// delegates to reverse auction. function createDklSiringAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); require(isReadyToMate(_PonyId)); _approve(_PonyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createDklAuction( _PonyId, msg.sender, _price ); } function createEthBidAuction( uint256 _ponyId, uint256 _price, uint16 _durationIndex ) external whenNotPaused { require(_owns(msg.sender, _ponyId)); _approve(_ponyId, biddingAuction); biddingAuction.createETHAuction(_ponyId, msg.sender, _durationIndex, _price); } function createDeklaBidAuction( uint256 _ponyId, uint256 _price, uint16 _durationIndex ) external whenNotPaused { require(_owns(msg.sender, _ponyId)); _approve(_ponyId, biddingAuction); biddingAuction.createDklAuction(_ponyId, msg.sender, _durationIndex, _price); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnEthSiringAuction( uint256 _sireId, uint256 _matronId, uint8 _incubator, bytes _sig ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToMate(_matronId)); require(canMateWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bidEth.value(msg.value - autoBirthFee)(_sireId); if (_incubator == 0 && hasIncubator[msg.sender]) { _mateWith(_matronId, _sireId, _incubator); } else { bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); nonces[msg.sender]++; // All checks passed, Pony gets pregnant! if (!hasIncubator[msg.sender]) { hasIncubator[msg.sender] = true; } _mateWith(_matronId, _sireId, _incubator); } } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnDklSiringAuction( uint256 _sireId, uint256 _matronId, uint8 _incubator, bytes _incubatorSig, uint256 _price, uint256 _fee, bytes _delegateSig, uint256 _nonce ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToMate(_matronId)); require(canMateWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= autoBirthFee); require(_price >= currentPrice); // Siring auction will throw if the bid fails. siringAuction.bidDkl(_sireId, _price, _fee, _delegateSig, _nonce); if (_incubator == 0 && hasIncubator[msg.sender]) { _mateWith(_matronId, _sireId, _incubator); } else { bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]); require(signedBySystem(hashedTx, _incubatorSig)); nonces[msg.sender]++; // All checks passed, Pony gets pregnant! if (!hasIncubator[msg.sender]) { hasIncubator[msg.sender] = true; } _mateWith(_matronId, _sireId, _incubator); } } /// @dev Transfers the balance of the sale auction contract /// to the PonyCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); biddingAuction.withdrawBalance(); } function withdrawAuctionDklBalance() external onlyCLevel { saleAuction.withdrawDklBalance(); siringAuction.withdrawDklBalance(); biddingAuction.withdrawDklBalance(); } function setBiddingRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel { biddingAuction.setCut(_prizeCut, _tokenDiscount); } function setSaleRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel { saleAuction.setCut(_prizeCut, _tokenDiscount); } function setSiringRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel { siringAuction.setCut(_prizeCut, _tokenDiscount); } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract BiddingAuctionBase { // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Duration (in seconds) of auction uint16 durationIndex; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; uint64 auctionEndBlock; // Price (in wei) at beginning of auction uint256 startingPrice; bool allowPayDekla; } uint32[4] public auctionDuration = [ //production uint32(2 days), uint32(3 days), uint32(4 days), uint32(5 days) ]; // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; uint256 public ownerCut = 500; // Map from token ID to their corresponding auction. mapping(uint256 => Auction) public tokenIdToAuction; event AuctionCreated(uint256 tokenId); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract BiddingAuction is Pausable, BiddingAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. constructor(address _nftAddress) public { ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } function cancelAuctionHashing( uint256 _tokenId, uint64 _endblock ) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E9E), _tokenId, _endblock)); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction( uint256 _tokenId, bytes _sig ) external { Auction storage auction = tokenIdToAuction[_tokenId]; address seller = auction.seller; uint64 endblock = auction.auctionEndBlock; require(msg.sender == seller); require(endblock < block.number); bytes32 hashedTx = cancelAuctionHashing(_tokenId, endblock); require(signedBySystem(hashedTx, _sig)); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyCLevel external { Auction storage auction = tokenIdToAuction[_tokenId]; _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint64 startedAt, uint16 durationIndex, uint64 auctionEndBlock, uint256 startingPrice, bool allowPayDekla ) { Auction storage auction = tokenIdToAuction[_tokenId]; return ( auction.seller, auction.startedAt, auction.durationIndex, auction.auctionEndBlock, auction.startingPrice, auction.allowPayDekla ); } function setSecondsPerBlock(uint256 secs) external onlyCEO { secondsPerBlock = secs; } } contract BiddingWallet is AccessControl { //user balances is stored in this balances map and could be withdraw by owner at anytime mapping(address => uint) public EthBalances; mapping(address => uint) public DeklaBalances; ERC20 public tokens; //the limit of deposit and withdraw the minimum amount you can deposit is 0.05 eth //you also have to have at least 0.05 eth uint public EthLimit = 50000000000000000; uint public DeklaLimit = 100; uint256 public totalEthDeposit; uint256 public totalDklDeposit; event withdrawSuccess(address receiver, uint amount); event cancelPendingWithdrawSuccess(address sender); function getNonces(address _address) public view returns (uint256) { return nonces[_address]; } function setSystemAddress(address _systemAddress, address _tokenAddress) internal { systemAddress = _systemAddress; tokens = ERC20(_tokenAddress); } //user will be assign an equivalent amount of bidding credit to bid function depositETH() payable external { require(msg.value >= EthLimit); EthBalances[msg.sender] = EthBalances[msg.sender] + msg.value; totalEthDeposit = totalEthDeposit + msg.value; } function depositDekla( uint256 _amount, uint256 _fee, bytes _signature, uint256 _nonce) external { address sender = tokens.recoverSigner(_signature, address(this), _amount, _fee, _nonce); tokens.transferPreSigned(_signature, address(this), _amount, _fee, _nonce); DeklaBalances[sender] = DeklaBalances[sender] + _amount; totalDklDeposit = totalDklDeposit + _amount; } function withdrawAmountHashing(uint256 _amount, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E9B), _amount, _nonce)); } // Withdraw all available eth back to user wallet, need co-verify function withdrawEth( uint256 _amount, bytes _sig ) external { require(EthBalances[msg.sender] >= _amount); bytes32 hashedTx = withdrawAmountHashing(_amount, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); EthBalances[msg.sender] = EthBalances[msg.sender] - _amount; totalEthDeposit = totalEthDeposit - _amount; msg.sender.transfer(_amount); nonces[msg.sender]++; emit withdrawSuccess(msg.sender, _amount); } // Withdraw all available dekla back to user wallet, need co-verify function withdrawDekla( uint256 _amount, bytes _sig ) external { require(DeklaBalances[msg.sender] >= _amount); bytes32 hashedTx = withdrawAmountHashing(_amount, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); DeklaBalances[msg.sender] = DeklaBalances[msg.sender] - _amount; totalDklDeposit = totalDklDeposit - _amount; tokens.transfer(msg.sender, _amount); nonces[msg.sender]++; emit withdrawSuccess(msg.sender, _amount); } event valueLogger(uint256 value); //bidding success tranfer eth to seller wallet function winBidEth( address winner, address seller, uint256 sellerProceeds, uint256 auctioneerCut ) internal { require(EthBalances[winner] >= sellerProceeds + auctioneerCut); seller.transfer(sellerProceeds); EthBalances[winner] = EthBalances[winner] - (sellerProceeds + auctioneerCut); } //bidding success tranfer eth to seller wallet function winBidDekla( address winner, address seller, uint256 sellerProceeds, uint256 auctioneerCut ) internal { require(DeklaBalances[winner] >= sellerProceeds + auctioneerCut); tokens.transfer(seller, sellerProceeds); DeklaBalances[winner] = DeklaBalances[winner] - (sellerProceeds + auctioneerCut); } function() public { revert(); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract BiddingClockAuction is BiddingAuction, BiddingWallet { address public prizeAddress; uint256 public prizeCut = 100; uint256 public tokenDiscount = 100; // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isBiddingClockAuction = true; modifier onlySystem() { require(msg.sender == systemAddress); _; } // Delegate constructor constructor( address _nftAddr, address _tokenAddress, address _prizeAddress, address _systemAddress, address _ceoAddress, address _cfoAddress, address _cooAddress) public BiddingAuction(_nftAddr) { // validate address require(_systemAddress != address(0)); require(_tokenAddress != address(0)); require(_ceoAddress != address(0)); require(_cooAddress != address(0)); require(_cfoAddress != address(0)); require(_prizeAddress != address(0)); setSystemAddress(_systemAddress, _tokenAddress); ceoAddress = _ceoAddress; cooAddress = _cooAddress; cfoAddress = _cfoAddress; prizeAddress = _prizeAddress; } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. function createETHAuction( uint256 _tokenId, address _seller, uint16 _durationIndex, uint256 _startingPrice ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 auctionEndBlock = uint64((auctionDuration[_durationIndex] / secondsPerBlock) + block.number); Auction memory auction = Auction( _seller, _durationIndex, uint64(now), auctionEndBlock, _startingPrice, false ); _addAuction(_tokenId, auction); } function setCut(uint256 _prizeCut, uint256 _tokenDiscount) external { require(msg.sender == address(nonFungibleContract)); require(_prizeCut + _tokenDiscount < ownerCut); prizeCut = _prizeCut; tokenDiscount = _tokenDiscount; } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. function createDklAuction( uint256 _tokenId, address _seller, uint16 _durationIndex, uint256 _startingPrice ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 auctionEndBlock = uint64((auctionDuration[_durationIndex] / secondsPerBlock) + block.number); Auction memory auction = Auction( _seller, _durationIndex, uint64(now), auctionEndBlock, _startingPrice, true ); _addAuction(_tokenId, auction); } function getNonces(address _address) public view returns (uint256) { return nonces[_address]; } function auctionEndHashing(uint _amount, uint256 _tokenId) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0F0E), _tokenId, _amount)); } function auctionEthEnd(address _winner, uint _amount, uint256 _tokenId, bytes _sig) public onlySystem { bytes32 hashedTx = auctionEndHashing(_amount, _tokenId); require(recover(hashedTx, _sig) == _winner); Auction storage auction = tokenIdToAuction[_tokenId]; uint64 endblock = auction.auctionEndBlock; require(endblock < block.number); require(!auction.allowPayDekla); uint256 prize = _amount * prizeCut / 10000; uint256 auctioneerCut = _computeCut(_amount) - prize; uint256 sellerProceeds = _amount - auctioneerCut; winBidEth(_winner, auction.seller, sellerProceeds, auctioneerCut); prizeAddress.transfer(prize); _removeAuction(_tokenId); _transfer(_winner, _tokenId); emit AuctionSuccessful(_tokenId, _amount, _winner); } function auctionDeklaEnd(address _winner, uint _amount, uint256 _tokenId, bytes _sig) public onlySystem { bytes32 hashedTx = auctionEndHashing(_amount, _tokenId); require(recover(hashedTx, _sig) == _winner); Auction storage auction = tokenIdToAuction[_tokenId]; uint64 endblock = auction.auctionEndBlock; require(endblock < block.number); require(auction.allowPayDekla); uint256 prize = _amount * prizeCut / 10000; uint256 discountAmount = _amount * tokenDiscount / 10000; uint256 auctioneerCut = _computeCut(_amount) - discountAmount - prizeCut; uint256 sellerProceeds = _amount - auctioneerCut; winBidDekla(_winner, auction.seller, sellerProceeds, auctioneerCut); tokens.transfer(prizeAddress, prize); tokens.transfer(_winner, discountAmount); _removeAuction(_tokenId); _transfer(_winner, _tokenId); emit AuctionSuccessful(_tokenId, _amount, _winner); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); nftAddress.transfer(address(this).balance - totalEthDeposit); } function withdrawDklBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); tokens.transfer(nftAddress, tokens.balanceOf(this) - totalDklDeposit); } } /// @title all functions related to creating ponies contract PonyMinting is PonyAuction { // Limits the number of ponies the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 50; uint256 public constant GEN0_CREATION_LIMIT = 4950; // Counts the number of ponies the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo ponies, up to a limit. Only callable by COO /// @param _genes the encoded genes of the pony to be created, any value is accepted /// @param _owner the future owner of the created ponies. Default to contract COO function createPromoPony(uint256 _genes, address _owner) external onlyCOO { address ponyOwner = _owner; if (ponyOwner == address(0)) { ponyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createPony(0, 0, 0, _genes, ponyOwner, 0); } /// @dev Creates a new gen0 Pony with the given genes and /// creates an auction for it. function createGen0(uint256 _genes, uint256 _price, uint16 _durationIndex, bool _saleDKL ) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 ponyId = _createPony(0, 0, 0, _genes, ceoAddress, 0); _approve(ponyId, biddingAuction); if(_saleDKL) { biddingAuction.createDklAuction(ponyId, ceoAddress, _durationIndex, _price); } else { biddingAuction.createETHAuction(ponyId, ceoAddress, _durationIndex, _price); } gen0CreatedCount++; } } contract PonyUpgrade is PonyMinting { event PonyUpgraded(uint256 upgradedPony, uint256 tributePony, uint8 unicornation); function upgradePonyHashing(uint256 _upgradeId, uint256 _txCount) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E9D), _upgradeId, _txCount)); } function upgradePony(uint256 _upgradeId, uint256 _tributeId, bytes _sig) external whenNotPaused { require(_owns(msg.sender, _upgradeId)); require(_upgradeId != _tributeId); Pony storage upPony = ponies[_upgradeId]; bytes32 hashedTx = upgradePonyHashing(_upgradeId, upPony.txCount); require(signedBySystem(hashedTx, _sig)); upPony.txCount += 1; if (upPony.unicornation == 0) { if (geneScience.upgradePonyResult(upPony.unicornation, block.number)) { upPony.unicornation += 1; emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation); } } else if (upPony.unicornation > 0) { require(_owns(msg.sender, _tributeId)); if (geneScience.upgradePonyResult(upPony.unicornation, block.number)) { upPony.unicornation += 1; _transfer(msg.sender, address(0), _tributeId); emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation); } else if (upPony.unicornation == 2) { upPony.unicornation += 1; _transfer(msg.sender, address(0), _tributeId); emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation); } } } } /// @title EtherPonies: Collectible, breedable, and oh-so-adorable ponies on the Ethereum blockchain. /// @author Dekla (https://www.dekla.io) /// @dev The main EtherPonies contract, keeps track of ponies so they don't wander around and get lost. contract PonyCore is PonyUpgrade { event WithdrawEthBalanceSuccessful(address sender, uint256 amount); event WithdrawDeklaBalanceSuccessful(address sender, uint256 amount); // This is the main MyEtherPonies contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // Pony ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - PonyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - PonyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - PonyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - PonyBreeding: This file contains the methods necessary to breed ponies together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - PonyAuctions: Here we have the public methods for auctioning or bidding on ponies or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - PonyMinting: This final facet contains the functionality we use for creating new gen0 ponies. // We can make up to 5000 "promo" ponies that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 ponies. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; // ERC20 basic token contract being held ERC20 public token; /// @notice Creates the main EtherPonies smart contract instance. constructor( address _ceoAddress, address _cfoAddress, address _cooAddress, address _systemAddress, address _tokenAddress ) public { // validate address require(_ceoAddress != address(0)); require(_cooAddress != address(0)); require(_cfoAddress != address(0)); require(_systemAddress != address(0)); require(_tokenAddress != address(0)); // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = _ceoAddress; cfoAddress = _cfoAddress; cooAddress = _cooAddress; systemAddress = _systemAddress; token = ERC20(_tokenAddress); // start with the mythical pony 0 - so we don't have generation-0 parent issues _createPony(0, 0, 0, uint256(- 1), address(0), 0); } //check that the token is set modifier validToken() { require(token != address(0)); _; } function getTokenAddressHashing(address _token, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A1216), _token, _nonce)); } function setTokenAddress(address _token, bytes _sig) external onlyCLevel { bytes32 hashedTx = getTokenAddressHashing(_token, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; token = ERC20(_token); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { } /// @notice Returns all the relevant information about a specific Pony. /// @param _id The ID of the Pony of interest. function getPony(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes, uint16 upgradeIndex, uint8 unicornation ) { Pony storage pon = ponies[_id]; // if this variable is 0 then it's not gestating isGestating = (pon.matingWithId != 0); isReady = (pon.cooldownEndBlock <= block.number); cooldownIndex = uint256(pon.cooldownIndex); nextActionAt = uint256(pon.cooldownEndBlock); siringWithId = uint256(pon.matingWithId); birthTime = uint256(pon.birthTime); matronId = uint256(pon.matronId); sireId = uint256(pon.sireId); generation = uint256(pon.generation); genes = pon.genes; upgradeIndex = pon.txCount; unicornation = pon.unicornation; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } function withdrawBalanceHashing(address _address, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A1217), _address, _nonce)); } function withdrawEthBalance(address _withdrawWallet, bytes _sig) external onlyCLevel { bytes32 hashedTx = withdrawBalanceHashing(_withdrawWallet, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); uint256 balance = address(this).balance; // Subtract all the currently pregnant ponies we have, plus 1 of margin. uint256 subtractFees = (pregnantPonies + 1) * autoBirthFee; require(balance > 0); require(balance > subtractFees); nonces[msg.sender]++; _withdrawWallet.transfer(balance - subtractFees); emit WithdrawEthBalanceSuccessful(_withdrawWallet, balance - subtractFees); } function withdrawDeklaBalance(address _withdrawWallet, bytes _sig) external validToken onlyCLevel { bytes32 hashedTx = withdrawBalanceHashing(_withdrawWallet, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); uint256 balance = token.balanceOf(this); require(balance > 0); nonces[msg.sender]++; token.transfer(_withdrawWallet, balance); emit WithdrawDeklaBalanceSuccessful(_withdrawWallet, balance); } }
Creates and begins a new auction. _tokenId - ID of token to auction, sender must be owner. _seller - Seller, if not the message sender
function createDklAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, true ); _addAuction(_tokenId, auction); }
6,389,673
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; } } /** * @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; } } /** * @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; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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 { } } /** * @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); } } /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } /** * @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)); } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional 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); } /** * @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); } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } contract SingleStaking is ERC721, Ownable { using Counters for Counters.Counter; using SafeMath for uint256; Counters.Counter private _tokenIds; string public tokenURI; ERC20 htg; address public htgAddress; mapping (address => uint256) public htgDeposited; mapping (address => uint256) public blocksToRedeem; mapping (address => uint256) public lastRedeemed; constructor (address _htgAddress, string memory _tokenURI) public ERC721("CryptoCurrent NFT", "CRNT") { tokenURI = _tokenURI; htg = ERC20(_htgAddress); htgAddress = _htgAddress; } function changeTokenURI (string memory _tokenURI) external onlyOwner { tokenURI = _tokenURI; } function stake (uint256 _htgAmount) external payable returns (uint256) { // add liquidity here htg.transferFrom(msg.sender, address(this), _htgAmount); htgDeposited[msg.sender] = htgDeposited[msg.sender].add(_htgAmount); // Determine blocks to redeem blocksToRedeem[msg.sender] = uint256(45000).mul(1 ether).mul(172800) .div(htgDeposited[msg.sender]); lastRedeemed[msg.sender] = block.number; } function unstake () external returns (uint256) { require (htgDeposited[msg.sender] > 0, "Some htg tokens must be deposited"); htg.transfer(msg.sender, htgDeposited[msg.sender]); // HTG deposited is now removed htgDeposited[msg.sender] = 0; // Blocks To Redeem blocksToRedeem[msg.sender] = 0; // Last Redeemed lastRedeemed[msg.sender] = 0; } function getRedeemBlock (address _staker) external view returns (uint256) { return lastRedeemed[_staker].add(blocksToRedeem[_staker]); } function redeem () external returns (uint256) { require (htgDeposited[msg.sender] >= 0, "Redeemer must have deposited HTG"); require (blocksToRedeem[msg.sender] != 0, "Blocks to Redeem must have some value"); require (block.number >= lastRedeemed[msg.sender].add(blocksToRedeem[msg.sender]), "Can't Redeem yet"); lastRedeemed[msg.sender] = block.number; return mintNFT(msg.sender); } function getHTGDeposited (address _staker) external view returns (uint256) { return htgDeposited[_staker]; } function mintNFT(address recipient) internal returns (uint256) { // Incrementing the token id _tokenIds.increment(); // Retreiving the nftId uint256 newItemId = _tokenIds.current(); // Changed this to be safeMint from Mint _safeMint(recipient, newItemId); _setTokenURI(newItemId, tokenURI); // Returning the token id of the NFT return newItemId; } }
Incrementing the token id Retreiving the nftId Changed this to be safeMint from Mint Returning the token id of the NFT
function mintNFT(address recipient) internal returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _safeMint(recipient, newItemId); _setTokenURI(newItemId, tokenURI); return newItemId; }
12,236,322
./full_match/1/0x6a507c08574ea9FdfBD2FE55acf42ad9995aE54b/sources/contracts/GovernanceToken.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, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes("1")), 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), "ESVSP::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "ESVSP::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "ESVSP::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
3,014,845
./full_match/1/0x686595a70b77f761F891BD50BD398be913b12a6C/sources/contracts/Collections/ERC1155/LazyMintERC1155.sol
Redeems an NFTVoucher for an actual NFT, creating it in the process. redeemer The address of the account which will receive the NFT upon success. voucher A signed NFTVoucher that describes the NFT to be redeemed. make sure signature is valid and get the address of the signer make sure that the redeemer is paying enough to cover the buyer's cost first assign the token to the signer, to establish provenance on-chain transfer the token to the redeemer record payment to signer's withdrawal balance
function redeem( address redeemer, NFTVoucher memory voucher, uint256 tokenId ) internal returns (uint256) { address signer = _verify(voucher); require(msg.value >= voucher.minPrice, "Insufficient funds to redeem"); _mint(signer, tokenId, voucher.quantity, bytes(voucher.uri)); _setTokenURI(tokenId, voucher.uri); _safeTransferFrom( signer, redeemer, tokenId, voucher.quantity, bytes(voucher.uri) ); pendingWithdrawals[signer] += msg.value; return voucher.royalty; }
16,572,635
/** *Submitted for verification at Etherscan.io on 2021-02-19 */ pragma solidity ^0.5.16; /** * @title Bird's BController Interface */ contract BControllerInterface { /// @notice Indicator that this is a BController contract (for inspection) bool public constant isBController = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata bTokens) external returns (uint[] memory); function exitMarket(address bToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address bToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address bToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address bToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address bToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address bToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address bToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed(address bToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify(address bToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address bToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address bToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens(address bTokenBorrowed, address bTokenCollateral, uint repayAmount) external view returns (uint, uint); } /** * @title Bird's InterestRateModel Interface */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } /** * @title Bird's BToken Storage */ contract BTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-bToken operations */ BControllerInterface public bController; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first BTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } /** * @title Bird's BToken Interface */ contract BTokenInterface is BTokenStorage { /** * @notice Indicator that this is a BToken contract (for inspection) */ bool public constant isBToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterestToken(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event MintToken(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event RedeemToken(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event BorrowToken(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrowToken(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrowToken(address liquidator, address borrower, uint repayAmount, address bTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when bController is changed */ event NewBController(BControllerInterface oldBController, BControllerInterface newBController); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketTokenInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewTokenReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setBController(BControllerInterface newBController) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } /** * @title Bird's BErc20 Storage */ contract BErc20Storage { /** * @notice Underlying asset for this BToken */ address public underlying; } /** * @title Bird's BErc20 Interface */ contract BErc20Interface is BErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } /** * @title Bird's BDelegation Storage */ contract BDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } /** * @title Bird's BDelegator Interface */ contract BDelegatorInterface is BDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } /** * @title Bird's BDelegate Interface */ contract BDelegateInterface is BDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } contract BControllerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BCONTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, BCONTROLLER_REJECTION, BCONTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_BCONTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_BCONTROLLER_REJECTION, LIQUIDATE_BCONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_BCONTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_BCONTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_BCONTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_BCONTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_BCONTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_BCONTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } /** * @title Exponential module for storing fixed-precision decimals * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @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 * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } /** * @title Bird's BToken Contract * @notice Abstract base for BTokens */ contract BToken is BTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param bController_ The address of the BController * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(BControllerInterface bController_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the bController uint err = _setBController(bController_); require(err == uint(Error.NO_ERROR), "setting bController failed"); // Initialize block number and borrow index (block number mocks depend on bController being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = bController.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.TRANSFER_BCONTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint scrTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, scrTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = scrTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); bController.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by bController to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint bTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), bTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this bToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this bToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the BToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the BToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this bToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterestToken(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives bTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives bTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = bController.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.MINT_BCONTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The bToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the bToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of bTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of bTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit MintToken(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ bController.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems bTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of bTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems bTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming bTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems bTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of bTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming bTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = bController.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REDEEM_BCONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The bToken must handle variations between ERC-20 and ETH underlying. * On success, the bToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit RedeemToken(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ bController.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = bController.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.BORROW_BCONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The bToken must handle variations between ERC-20 and ETH underlying. * On success, the bToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit BorrowToken(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ bController.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = bController.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_BCONTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The bToken must handle variations between ERC-20 and ETH underlying. * On success, the bToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrowToken event */ emit RepayBorrowToken(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ bController.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this bToken to be liquidated * @param bTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = bTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, bTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this bToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param bTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, BTokenInterface bTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = bController.liquidateBorrowAllowed(address(this), address(bTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.LIQUIDATE_BCONTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify bTokenCollateral market's block number equals current block number */ if (bTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = bController.liquidateCalculateSeizeTokens(address(this), address(bTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_BCONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(bTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(bTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = bTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrowToken event */ emit LiquidateBorrowToken(liquidator, borrower, actualRepayAmount, address(bTokenCollateral), seizeTokens); /* We call the defense hook */ bController.liquidateBorrowVerify(address(this), address(bTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another bToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed bToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of bTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another BToken. * Its absolutely critical to use msg.sender as the seizer bToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed bToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of bTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = bController.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_BCONTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ bController.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new bController for the market * @dev Admin function to set a new bController * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setBController(BControllerInterface newBController) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_BCONTROLLER_OWNER_CHECK); } BControllerInterface oldBController = bController; // Ensure invoke bController.isBController() returns true require(newBController.isBController(), "marker method returned false"); // Set market's bController to newBController bController = newBController; // Emit NewBController(oldBController, newBController) emit NewBController(oldBController, newBController); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewTokenReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The bToken must handle variations between ERC-20 and ETH underlying. * On success, the bToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } /** * @title Bird's BErc20 Contract * @notice BTokens which wrap an EIP-20 underlying */ contract BErc20 is BToken, BErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param bController_ The address of the BController * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, BControllerInterface bController_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // BToken initialize does the bulk of the work super.initialize(bController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives bTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems bTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of bTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems bTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this bToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param bTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, bTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } /** * @title Bird's BErc20LINKDelegate Contract * @notice BTokens which wrap an EIP-20 underlying and are delegated to */ contract BErc20LINKDelegate is BErc20, BDelegateInterface { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _resignImplementation"); } }
Get a snapshot of the account's balances, and the cached exchange rate This is used by bController to more efficiently perform liquidity checks. account Address of the account to snapshot return (possible error, token balance, borrow balance, exchange rate mantissa)/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint bTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), bTokenBalance, borrowBalance, exchangeRateMantissa); }
285,883
./full_match/5/0x32ff4D05236E95FF60299E9b7BaB351179138389/sources/contracts/core/libraries/Linkedlist.sol
Insert a new value to the linked list given its lower value that is inside the linked list newValue the new value to insert, it must not exist in the LinkedList lowerValue the nearest value which is <= newValue and is in the LinkedList
function insert( mapping(int24 => Linkedlist.Data) storage self, int24 newValue, int24 lowerValue, int24 nextValue ) internal { require(nextValue != self[lowerValue].previous, 'lower value is not initialized'); require(lowerValue < newValue && nextValue > newValue, 'invalid lower value'); self[newValue].next = nextValue; self[newValue].previous = lowerValue; self[nextValue].previous = newValue; self[lowerValue].next = newValue; }
1,940,684
// 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 DIV758(uint256 a, uint256 b) internal pure returns (uint256) {
12,917,668
./full_match/5/0x5dF6D53FA5D7f3C325D2b0E3109C55AbF2c289a5/sources/erc721a-upgradeable/contracts/ERC721AUpgradeable.sol
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) public virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } ERC721AStorage.layout()._tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); }
1,927,373
./full_match/1/0x567c09B55294998d7a6F2A3A948e8fD331531B88/sources/contracts/UMA/common/implementation/FixedPoint.sol
Whether `a` is equal to `b`. a a FixedPoint.Signed. b a FixedPoint.Signed. return True if equal, or False./
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; }
9,749,045
pragma solidity 0.6.12; import '@nextechlabs/nexdex-lib/contracts/math/SafeMath.sol'; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import '@nextechlabs/nexdex-lib/contracts/access/Ownable.sol'; import "./Xp.sol"; import "./BoostBar.sol"; // import "@nomiclabs/buidler/console.sol"; interface IMigratorGamer { // Perform LP token migration from legacy PanxpSwap to XpSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to PanxpSwap LP tokens. // XpSwap must mint EXACTLY the same amount of XpSwap LP tokens or // else something bad will happen. Traditional PanxpSwap does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterGamer is the master of Xp. He can make Xp and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once XP is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterGamer is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of XPs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accXpPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accXpPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. XPs to distribute per block. uint256 lastRewardBlock; // Last block number that XPs distribution occurs. uint256 accXpPerShare; // Accumulated XPs per share, times 1e12. See below. } // The XP TOKEN! Xp public xp; // The SYRUP TOKEN! BoostBar public boost; // Dev address. address public devaddr; // XP tokens created per block. uint256 public xpPerBlock; // Bonus muliplier for early xp makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorGamer public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when XP mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( Xp _xp, BoostBar _boost, address _devaddr, uint256 _xpPerBlock, uint256 _startBlock ) public { xp = _xp; boost = _boost; devaddr = _devaddr; xpPerBlock = _xpPerBlock; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _xp, allocPoint: 1000, lastRewardBlock: startBlock, accXpPerShare: 0 })); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accXpPerShare: 0 })); updateStakingPool(); } // Update the given pool's XP allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorGamer _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending XPs on frontend. function pendingXp(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accXpPerShare = pool.accXpPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 xpReward = multiplier.mul(xpPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accXpPerShare = accXpPerShare.add(xpReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accXpPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 xpReward = multiplier.mul(xpPerBlock).mul(pool.allocPoint).div(totalAllocPoint); xp.mint(devaddr, xpReward.div(10)); // devs xp.mint(address(boost), xpReward); // amount for pools xp.lock(address(boost), xpReward.mul(99).div(100)); // lock 99 % pool.accXpPerShare = pool.accXpPerShare.add(xpReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterGamer for XP allocation. function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit XP by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeXpTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accXpPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterGamer. function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw XP by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeXpTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accXpPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Stake XP tokens to MasterGamer function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeXpTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accXpPerShare).div(1e12); boost.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // Withdraw XP tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeXpTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accXpPerShare).div(1e12); boost.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe xp transfer function, just in case if rounding error causes pool to not have enough XPs. function safeXpTransfer(address _to, uint256 _amount) internal { boost.safeXpTransfer(_to, _amount); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Stake XP tokens to MasterGamer
function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeXpTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accXpPerShare).div(1e12); boost.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); }
1,029,195
./full_match/4/0x3F9C6D6EBcBeDEB9cCff83a30377D2E2579D5878/sources/Users/blood/Documents/Working/BlockChain/Ethereum/contract/contracts/Lands.sol
Mints more tokens, can only be called by contract creator and all newly minted tokens will belong to creator. check if token id is duplicated, or null or burned. Throw if msg.sender is not creator tokenId array of extra tokens to mint. amount number of token.
function issueToken(address to, string memory tokenId, uint256 amount) public override whenNotPaused { require(msg.sender == _creator || _authorised[_creator][msg.sender], "issueToken: sender does not have permission."); require(address(0) != to, "issueToken: issue token for zero address"); require(bytes(tokenId).length > 0, "issueToken: token id is null"); if (!_created[tokenId]) { _created[tokenId] = true; _tokenIndexes[tokenId] = _tokenIDs.length; _tokenIDs.push(tokenId); _totalSupply.totalIdSupplies = _totalSupply.totalIdSupplies.add(1); } _totalSupply.totalTokenSupples = _totalSupply.totalTokenSupples.add(amount); _ownerTotalTokenBalance[to] = _ownerTotalTokenBalance[to].add(amount); if (!_isOwners[to][tokenId]) { _isOwners[to][tokenId] = true; Tokens memory token; token.id = tokenId; token.balance = amount; token.timestamp = uint64(block.timestamp % 2**64); _ownerTokenIndexes[to][tokenId] = _ownerTokens[to].length; _ownerTokens[to].push(token); uint256 index = _ownerTokenIndexes[to][tokenId]; _ownerTokens[to][index].balance = _ownerTokens[to][index].balance.add(amount); _ownerTokens[to][index].timestamp = uint64(block.timestamp % 2**64); } emit Transfer(msg.sender, to, tokenId, amount); }
12,370,300
// contract that takes and gives Azimuth points pragma solidity 0.4.24; import './Ecliptic.sol'; import './ReadsAzimuth.sol'; contract TakesPoints is ReadsAzimuth { constructor(Azimuth _azimuth) ReadsAzimuth(_azimuth) public { // } // takePoint(): transfer _point to this contract. if _clean is true, require // that the point be unlinked. // returns true if this succeeds, false otherwise. // function takePoint(uint32 _point, bool _clean) internal returns (bool success) { Ecliptic ecliptic = Ecliptic(azimuth.owner()); // There are two ways for a contract to get a point. // One way is for a prefix point to grant the contract permission to // spawn its points. // The contract will spawn the point directly to itself. // uint16 prefix = azimuth.getPrefix(_point); if ( azimuth.isOwner(_point, 0x0) && azimuth.isOwner(prefix, msg.sender) && azimuth.isSpawnProxy(prefix, this) && (ecliptic.getSpawnLimit(prefix, now) > azimuth.getSpawnCount(prefix)) ) { // first model: spawn _point to :this contract // ecliptic.spawn(_point, this); return true; } // The second way is to accept existing points, optionally // requiring they be unlinked. // To deposit a point this way, the owner grants the contract // permission to transfer ownership of the point. // The contract will transfer the point to itself. // if ( (!_clean || !azimuth.hasBeenLinked(_point)) && azimuth.isOwner(_point, msg.sender) && azimuth.canTransfer(_point, this) ) { // second model: transfer active, unlinked _point to :this contract // ecliptic.transferPoint(_point, this, true); return true; } // point is not for us to take // return false; } // givePoint(): transfer a _point we own to _to, optionally resetting. // returns true if this succeeds, false otherwise. // // Note that _reset is unnecessary if the point was taken // using this contract's takePoint() function, which always // resets, and not touched since. // function givePoint(uint32 _point, address _to, bool _reset) internal returns (bool success) { // only give points we've taken, points we fully own // if (azimuth.isOwner(_point, this)) { Ecliptic(azimuth.owner()).transferPoint(_point, _to, _reset); return true; } // point is not for us to give // return false; } }
takePoint(): transfer _point to this contract. if _clean is true, require that the point be unlinked. returns true if this succeeds, false otherwise. There are two ways for a contract to get a point. One way is for a prefix point to grant the contract permission to spawn its points. The contract will spawn the point directly to itself. first model: spawn _point to :this contract second model: transfer active, unlinked _point to :this contract
function takePoint(uint32 _point, bool _clean) internal returns (bool success) { Ecliptic ecliptic = Ecliptic(azimuth.owner()); uint16 prefix = azimuth.getPrefix(_point); if ( azimuth.isOwner(_point, 0x0) && azimuth.isOwner(prefix, msg.sender) && azimuth.isSpawnProxy(prefix, this) && (ecliptic.getSpawnLimit(prefix, now) > azimuth.getSpawnCount(prefix)) ) { ecliptic.spawn(_point, this); return true; } azimuth.isOwner(_point, msg.sender) && azimuth.canTransfer(_point, this) ) { ecliptic.transferPoint(_point, this, true); return true; } }
890,449
//Address: 0xacb677dacac7c7b1ee4131cd071c89bad6c852f4 //Contract name: ExoTownToken //Balance: 0 Ether //Verification Date: 11/26/2017 //Transacion Count: 0 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ contract SafeMath { function mul(uint a, uint b) constant internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) constant 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) constant internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) constant internal returns (uint) { uint c = a + b; assert(c >= a); return c; } // Volume bonus calculation function volumeBonus(uint etherValue) constant internal returns (uint) { if(etherValue >= 500000000000000000000) return 10; // 500 ETH +10% tokens if(etherValue >= 300000000000000000000) return 7; // 300 ETH +7% tokens if(etherValue >= 100000000000000000000) return 5; // 100 ETH +5% tokens if(etherValue >= 50000000000000000000) return 3; // 50 ETH +3% tokens if(etherValue >= 20000000000000000000) return 2; // 20 ETH +2% tokens if(etherValue >= 10000000000000000000) return 1; // 10 ETH +1% tokens return 0; } } /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 /// @title Abstract token contract - Functions to be implemented by token contracts. contract AbstractToken { // This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions 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); event Issuance(address indexed to, uint value); } contract IcoLimits { uint constant privateSaleStart = 1511740800; // 11/27/2017 @ 12:00am (UTC) uint constant privateSaleEnd = 1512172799; // 12/01/2017 @ 11:59pm (UTC) uint constant presaleStart = 1512172800; // 12/02/2017 @ 12:00am (UTC) uint constant presaleEnd = 1513987199; // 12/22/2017 @ 11:59pm (UTC) uint constant publicSaleStart = 1516320000; // 01/19/2018 @ 12:00am (UTC) uint constant publicSaleEnd = 1521158399; // 03/15/2018 @ 11:59pm (UTC) uint constant foundersTokensUnlock = 1558310400; // 05/20/2019 @ 12:00am (UTC) modifier afterPublicSale() { require(now > publicSaleEnd); _; } uint constant privateSalePrice = 4000; // SNEK tokens per 1 ETH uint constant preSalePrice = 3000; // SNEK tokens per 1 ETH uint constant publicSalePrice = 2000; // SNEK tokens per 1 ETH uint constant privateSaleSupplyLimit = 600 * privateSalePrice * 1000000000000000000; uint constant preSaleSupplyLimit = 1200 * preSalePrice * 1000000000000000000; uint constant publicSaleSupplyLimit = 5000 * publicSalePrice * 1000000000000000000; } contract StandardToken is AbstractToken, IcoLimits { /* * Data structures */ mapping (address => uint) balances; mapping (address => bool) ownerAppended; mapping (address => mapping (address => uint)) allowed; uint public totalSupply; address[] public owners; /* * Read and write storage functions */ /// @dev Transfers sender's tokens to a given address. Returns success. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. function transfer(address _to, uint _value) afterPublicSale returns (bool success) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(msg.sender, _to, _value); return true; } else { return false; } } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. function transferFrom(address _from, address _to, uint _value) afterPublicSale returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(_from, _to, _value); return true; } else { return false; } } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. function approve(address _spender, uint _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* * Read storage functions */ /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract ExoTownToken is StandardToken, SafeMath { /* * Token meta data */ string public constant name = "ExoTown token"; string public constant symbol = "SNEK"; uint public constant decimals = 18; address public icoContract = 0x0; /* * Modifiers */ modifier onlyIcoContract() { // only ICO contract is allowed to proceed require(msg.sender == icoContract); _; } /* * Contract functions */ /// @dev Contract is needed in icoContract address /// @param _icoContract Address of account which will be mint tokens function ExoTownToken(address _icoContract) { require(_icoContract != 0x0); icoContract = _icoContract; } /// @dev Burns tokens from address. It can be applied by account with address this.icoContract /// @param _from Address of account, from which will be burned tokens /// @param _value Amount of tokens, that will be burned function burnTokens(address _from, uint _value) onlyIcoContract { require(_value > 0); balances[_from] = sub(balances[_from], _value); totalSupply -= _value; } /// @dev Adds tokens to address. It can be applied by account with address this.icoContract /// @param _to Address of account to which the tokens will pass /// @param _value Amount of tokens function emitTokens(address _to, uint _value) onlyIcoContract { require(totalSupply + _value >= totalSupply); balances[_to] = add(balances[_to], _value); totalSupply += _value; if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(0x0, _to, _value); } function getOwner(uint index) constant returns (address, uint) { return (owners[index], balances[owners[index]]); } function getOwnerCount() constant returns (uint) { return owners.length; } } contract ExoTownIco is SafeMath, IcoLimits { /* * ICO meta data */ ExoTownToken public exotownToken; enum State { Pause, Running } State public currentState = State.Pause; uint public privateSaleSoldTokens = 0; uint public preSaleSoldTokens = 0; uint public publicSaleSoldTokens = 0; uint public privateSaleEtherRaised = 0; uint public preSaleEtherRaised = 0; uint public publicSaleEtherRaised = 0; // Address of manager address public icoManager; address public founderWallet; // Address from which tokens could be burned address public buyBack; // Purpose address public developmentWallet; address public marketingWallet; address public teamWallet; address public bountyOwner; // Mediator wallet is used for tracking user payments and reducing users' fee address public mediatorWallet; bool public sentTokensToBountyOwner = false; bool public sentTokensToFounders = false; /* * Modifiers */ modifier whenInitialized() { // only when contract is initialized require(currentState >= State.Running); _; } modifier onlyManager() { // only ICO manager can do this action require(msg.sender == icoManager); _; } modifier onIco() { require( isPrivateSale() || isPreSale() || isPublicSale() ); _; } modifier hasBountyCampaign() { require(bountyOwner != 0x0); _; } function isPrivateSale() constant internal returns (bool) { return now >= privateSaleStart && now <= privateSaleEnd; } function isPreSale() constant internal returns (bool) { return now >= presaleStart && now <= presaleEnd; } function isPublicSale() constant internal returns (bool) { return now >= publicSaleStart && now <= publicSaleEnd; } function getPrice() constant internal returns (uint) { if (isPrivateSale()) return privateSalePrice; if (isPreSale()) return preSalePrice; if (isPublicSale()) return publicSalePrice; return publicSalePrice; } function getStageSupplyLimit() constant returns (uint) { if (isPrivateSale()) return privateSaleSupplyLimit; if (isPreSale()) return preSaleSupplyLimit; if (isPublicSale()) return publicSaleSupplyLimit; return 0; } function getStageSoldTokens() constant returns (uint) { if (isPrivateSale()) return privateSaleSoldTokens; if (isPreSale()) return preSaleSoldTokens; if (isPublicSale()) return publicSaleSoldTokens; return 0; } function addStageTokensSold(uint _amount) internal { if (isPrivateSale()) privateSaleSoldTokens = add(privateSaleSoldTokens, _amount); if (isPreSale()) preSaleSoldTokens = add(preSaleSoldTokens, _amount); if (isPublicSale()) publicSaleSoldTokens = add(publicSaleSoldTokens, _amount); } function addStageEtherRaised(uint _amount) internal { if (isPrivateSale()) privateSaleEtherRaised = add(privateSaleEtherRaised, _amount); if (isPreSale()) preSaleEtherRaised = add(preSaleEtherRaised, _amount); if (isPublicSale()) publicSaleEtherRaised = add(publicSaleEtherRaised, _amount); } function getStageEtherRaised() constant returns (uint) { if (isPrivateSale()) return privateSaleEtherRaised; if (isPreSale()) return preSaleEtherRaised; if (isPublicSale()) return publicSaleEtherRaised; return 0; } function getTokensSold() constant returns (uint) { return privateSaleSoldTokens + preSaleSoldTokens + publicSaleSoldTokens; } function getEtherRaised() constant returns (uint) { return privateSaleEtherRaised + preSaleEtherRaised + publicSaleEtherRaised; } /// @dev Constructor of ICO. Requires address of icoManager, /// @param _icoManager Address of ICO manager function ExoTownIco(address _icoManager) { require(_icoManager != 0x0); exotownToken = new ExoTownToken(this); icoManager = _icoManager; } /// Initialises addresses of founder, target wallets /// @param _founder Address of Founder /// @param _dev Address of Development wallet /// @param _pr Address of Marketing wallet /// @param _team Address of Team wallet /// @param _buyback Address of wallet used for burning tokens /// @param _mediator Address of Mediator wallet function init( address _founder, address _dev, address _pr, address _team, address _buyback, address _mediator ) onlyManager { require(currentState == State.Pause); require(_founder != 0x0); require(_dev != 0x0); require(_pr != 0x0); require(_team != 0x0); require(_buyback != 0x0); require(_mediator != 0x0); founderWallet = _founder; developmentWallet = _dev; marketingWallet = _pr; teamWallet = _team; buyBack = _buyback; mediatorWallet = _mediator; currentState = State.Running; exotownToken.emitTokens(icoManager, 0); } /// @dev Sets new state /// @param _newState Value of new state function setState(State _newState) public onlyManager { currentState = _newState; } /// @dev Sets new manager. Only manager can do it /// @param _newIcoManager Address of new ICO manager function setNewManager(address _newIcoManager) onlyManager { require(_newIcoManager != 0x0); icoManager = _newIcoManager; } /// @dev Sets bounty owner. Only manager can do it /// @param _bountyOwner Address of Bounty owner function setBountyCampaign(address _bountyOwner) onlyManager { require(_bountyOwner != 0x0); bountyOwner = _bountyOwner; } /// @dev Sets new Mediator wallet. Only manager can do it /// @param _mediator Address of Mediator wallet function setNewMediator(address _mediator) onlyManager { require(_mediator != 0x0); mediatorWallet = _mediator; } /// @dev Buy quantity of tokens depending on the amount of sent ethers. /// @param _buyer Address of account which will receive tokens function buyTokens(address _buyer) private { require(_buyer != 0x0); require(msg.value > 0); uint tokensToEmit = msg.value * getPrice(); uint volumeBonusPercent = volumeBonus(msg.value); if (volumeBonusPercent > 0) { tokensToEmit = mul(tokensToEmit, 100 + volumeBonusPercent) / 100; } uint stageSupplyLimit = getStageSupplyLimit(); uint stageSoldTokens = getStageSoldTokens(); require(add(stageSoldTokens, tokensToEmit) <= stageSupplyLimit); exotownToken.emitTokens(_buyer, tokensToEmit); // Public statistics addStageTokensSold(tokensToEmit); addStageEtherRaised(msg.value); distributeEtherByStage(); } /// @dev Buy tokens to specified wallet function giftToken(address _to) public payable onIco { buyTokens(_to); } /// @dev Fall back function function () payable onIco { buyTokens(msg.sender); } function distributeEtherByStage() private { uint _balance = this.balance; uint _balance_div = _balance / 100; uint _devAmount = _balance_div * 65; uint _prAmount = _balance_div * 25; uint total = _devAmount + _prAmount; if (total > 0) { // Top up Mediator wallet with 1% of Development amount = 0.65% of contribution amount. // It will cover tracking transaction fee (if any). uint _mediatorAmount = _devAmount / 100; mediatorWallet.transfer(_mediatorAmount); developmentWallet.transfer(_devAmount - _mediatorAmount); marketingWallet.transfer(_prAmount); teamWallet.transfer(_balance - _devAmount - _prAmount); } } /// @dev Partial withdraw. Only manager can do it function withdrawEther(uint _value) onlyManager { require(_value > 0); require(_value * 1000000000000000 <= this.balance); // send 1234 to get 1.234 icoManager.transfer(_value * 1000000000000000); // 10^15 } ///@dev Send tokens to bountyOwner depending on crowdsale results. Can be sent only after public sale. function sendTokensToBountyOwner() onlyManager whenInitialized hasBountyCampaign afterPublicSale { require(!sentTokensToBountyOwner); //Calculate bounty tokens depending on total tokens sold uint bountyTokens = getTokensSold() / 40; // 2.5% exotownToken.emitTokens(bountyOwner, bountyTokens); sentTokensToBountyOwner = true; } /// @dev Send tokens to founders. Can be sent only after May 20th, 2019. function sendTokensToFounders() onlyManager whenInitialized afterPublicSale { require(!sentTokensToFounders); require(now >= foundersTokensUnlock); //Calculate founder reward depending on total tokens sold uint founderReward = getTokensSold() / 10; // 10% exotownToken.emitTokens(founderWallet, founderReward); sentTokensToFounders = true; } // Anyone could burn tokens by sending it to buyBack address and calling this function. function burnTokens(uint _amount) afterPublicSale { exotownToken.burnTokens(buyBack, _amount); } }
Volume bonus calculation
function volumeBonus(uint etherValue) constant internal returns (uint) { return 0; }
1,808,410
./full_match/137/0xEF583ce9bdc952fC383E9Fe84A8b6d1E1cE8Ce82/sources/interfaces/IERC20.sol
SPDX-License-Identifier: GPL-3.0-or-later
interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
3,767,425
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // &#39;BCP&#39; CROWDSALE token contract // // Deployed to : 0xbcc48a07d2c3bb879857f0ed6e9ff80252202e77 // Symbol : BCP // Name : BitCash Platform // Total supply: 2100000000 // Decimals : 18 // // Enjoy. // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract BitCashPlatform is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public bonusEnds; uint public endDate; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function BitCashPlatform() public { symbol = "BCP"; name = "BitCash Platform"; decimals = 18; bonusEnds = now + 7 weeks; endDate = now + 15 weeks; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to `to` account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // 2100000 BitCashPlatform per 1 ETH // ------------------------------------------------------------------------ function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 2100000; } else { tokens = msg.value * 950000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
------------------------------------------------------------------------ 2100000 BitCashPlatform per 1 ETH ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 2100000; tokens = msg.value * 950000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); }
14,966,920
pragma solidity ^0.4.20; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.11;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){ bool match_ = true; for (var i=0; i<prefix.length; i++){ if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> contract BettingControllerInterface { function remoteBettingClose() external; function depositHouseTakeout() external payable; } contract Betting is usingOraclize { using SafeMath for uint256; //using safemath uint countdown=3; // variable to check if all prices are received address public owner; //owner address uint public winnerPoolTotal; string public constant version = "0.2.2"; BettingControllerInterface internal bettingControllerInstance; struct chronus_info { bool betting_open; // boolean: check if betting is open bool race_start; //boolean: check if race has started bool race_end; //boolean: check if race has ended bool voided_bet; //boolean: check if race has been voided uint32 starting_time; // timestamp of when the race starts uint32 betting_duration; uint32 race_duration; // duration of the race uint32 voided_timestamp; } struct horses_info{ int32 BTC_delta; //horses.BTC delta value int32 ETH_delta; //horses.ETH delta value int32 LTC_delta; //horses.LTC delta value bytes32 BTC; //32-bytes equivalent of horses.BTC bytes32 ETH; //32-bytes equivalent of horses.ETH bytes32 LTC; //32-bytes equivalent of horses.LTC uint customGasLimit; } struct bet_info{ bytes32 horse; // coin on which amount is bet on uint amount; // amount bet by Bettor } struct coin_info{ uint256 pre; // locking price uint256 post; // ending price uint160 total; // total coin pool uint32 count; // number of bets bool price_check; bytes32 preOraclizeId; bytes32 postOraclizeId; } struct voter_info { uint160 total_bet; //total amount of bet placed bool rewarded; // boolean: check for double spending mapping(bytes32=>uint) bets; //array of bets } mapping (bytes32 => bytes32) oraclizeIndex; // mapping oraclize IDs with coins mapping (bytes32 => coin_info) coinIndex; // mapping coins with pool information mapping (address => voter_info) voterIndex; // mapping voter address with Bettor information uint public total_reward; // total reward to be awarded uint32 total_bettors; mapping (bytes32 => bool) public winner_horse; // tracking events event newOraclizeQuery(string description); event newPriceTicker(uint price); event Deposit(address _from, uint256 _value, bytes32 _horse, uint256 _date); event Withdraw(address _to, uint256 _value); // constructor function Betting() public payable { oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); owner = msg.sender; // oraclize_setCustomGasPrice(10000000000 wei); horses.BTC = bytes32("BTC"); horses.ETH = bytes32("ETH"); horses.LTC = bytes32("LTC"); horses.customGasLimit = 300000; bettingControllerInstance = BettingControllerInterface(owner); } // data access structures horses_info public horses; chronus_info public chronus; // modifiers for restricting access to methods modifier onlyOwner { require(owner == msg.sender); _; } modifier duringBetting { require(chronus.betting_open); _; } modifier beforeBetting { require(!chronus.betting_open && !chronus.race_start); _; } modifier afterRace { require(chronus.race_end); _; } //function to change owner function changeOwnership(address _newOwner) onlyOwner external { owner = _newOwner; } //oraclize callback method function __callback(bytes32 myid, string result, bytes proof) public { require (msg.sender == oraclize_cbAddress()); require (!chronus.race_end); bytes32 coin_pointer; // variable to differentiate different callbacks chronus.race_start = true; chronus.betting_open = false; bettingControllerInstance.remoteBettingClose(); coin_pointer = oraclizeIndex[myid]; if (myid == coinIndex[coin_pointer].preOraclizeId) { if (coinIndex[coin_pointer].pre > 0) { } else if (now >= chronus.starting_time+chronus.betting_duration+ 15 minutes) { forceVoidRace(); } else { coinIndex[coin_pointer].pre = stringToUintNormalize(result); emit newPriceTicker(coinIndex[coin_pointer].pre); } } else if (myid == coinIndex[coin_pointer].postOraclizeId){ if (coinIndex[coin_pointer].pre > 0 ){ if (coinIndex[coin_pointer].post > 0) { } else if (now >= chronus.starting_time+chronus.race_duration+ 15 minutes) { forceVoidRace(); } else { coinIndex[coin_pointer].post = stringToUintNormalize(result); coinIndex[coin_pointer].price_check = true; emit newPriceTicker(coinIndex[coin_pointer].post); if (coinIndex[horses.ETH].price_check && coinIndex[horses.BTC].price_check && coinIndex[horses.LTC].price_check) { reward(); } } } else { forceVoidRace(); } } } // place a bet on a coin(horse) lockBetting function placeBet(bytes32 horse) external duringBetting payable { require(msg.value >= 0.01 ether); if (voterIndex[msg.sender].total_bet==0) { total_bettors+=1; } uint _newAmount = voterIndex[msg.sender].bets[horse] + msg.value; voterIndex[msg.sender].bets[horse] = _newAmount; voterIndex[msg.sender].total_bet += uint160(msg.value); uint160 _newTotal = coinIndex[horse].total + uint160(msg.value); uint32 _newCount = coinIndex[horse].count + 1; coinIndex[horse].total = _newTotal; coinIndex[horse].count = _newCount; emit Deposit(msg.sender, msg.value, horse, now); } // fallback method for accepting payments function () private payable {} // method to place the oraclize queries function setupRace(uint delay, uint locking_duration) onlyOwner beforeBetting public payable returns(bool) { // if (oraclize_getPrice("URL") > (this.balance)/6) { if (oraclize_getPrice("URL")*3 + oraclize_getPrice("URL", horses.customGasLimit)*3 > address(this).balance) { emit newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); return false; } else { chronus.starting_time = uint32(block.timestamp); chronus.betting_open = true; bytes32 temp_ID; // temp variable to store oraclize IDs emit newOraclizeQuery("Oraclize query was sent, standing by for the answer.."); // bets open price query chronus.betting_duration = uint32(delay); temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd"); oraclizeIndex[temp_ID] = horses.ETH; coinIndex[horses.ETH].preOraclizeId = temp_ID; temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd"); oraclizeIndex[temp_ID] = horses.LTC; coinIndex[horses.LTC].preOraclizeId = temp_ID; temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd"); oraclizeIndex[temp_ID] = horses.BTC; coinIndex[horses.BTC].preOraclizeId = temp_ID; //bets closing price query delay = delay.add(locking_duration); temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd",horses.customGasLimit); oraclizeIndex[temp_ID] = horses.ETH; coinIndex[horses.ETH].postOraclizeId = temp_ID; temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/litecoin/).0.price_usd",horses.customGasLimit); oraclizeIndex[temp_ID] = horses.LTC; coinIndex[horses.LTC].postOraclizeId = temp_ID; temp_ID = oraclize_query(delay, "URL", "json(https://api.coinmarketcap.com/v1/ticker/bitcoin/).0.price_usd",horses.customGasLimit); oraclizeIndex[temp_ID] = horses.BTC; coinIndex[horses.BTC].postOraclizeId = temp_ID; chronus.race_duration = uint32(delay); return true; } } // method to calculate reward (called internally by callback) function reward() internal { /* calculating the difference in price with a precision of 5 digits not using safemath since signed integers are handled */ horses.BTC_delta = int32(coinIndex[horses.BTC].post - coinIndex[horses.BTC].pre)*100000/int32(coinIndex[horses.BTC].pre); horses.ETH_delta = int32(coinIndex[horses.ETH].post - coinIndex[horses.ETH].pre)*100000/int32(coinIndex[horses.ETH].pre); horses.LTC_delta = int32(coinIndex[horses.LTC].post - coinIndex[horses.LTC].pre)*100000/int32(coinIndex[horses.LTC].pre); total_reward = (coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total); if (total_bettors <= 1) { forceVoidRace(); } else { uint house_fee = total_reward.mul(5).div(100); require(house_fee < address(this).balance); total_reward = total_reward.sub(house_fee); bettingControllerInstance.depositHouseTakeout.value(house_fee)(); } if (horses.BTC_delta > horses.ETH_delta) { if (horses.BTC_delta > horses.LTC_delta) { winner_horse[horses.BTC] = true; winnerPoolTotal = coinIndex[horses.BTC].total; } else if(horses.LTC_delta > horses.BTC_delta) { winner_horse[horses.LTC] = true; winnerPoolTotal = coinIndex[horses.LTC].total; } else { winner_horse[horses.BTC] = true; winner_horse[horses.LTC] = true; winnerPoolTotal = coinIndex[horses.BTC].total + (coinIndex[horses.LTC].total); } } else if(horses.ETH_delta > horses.BTC_delta) { if (horses.ETH_delta > horses.LTC_delta) { winner_horse[horses.ETH] = true; winnerPoolTotal = coinIndex[horses.ETH].total; } else if (horses.LTC_delta > horses.ETH_delta) { winner_horse[horses.LTC] = true; winnerPoolTotal = coinIndex[horses.LTC].total; } else { winner_horse[horses.ETH] = true; winner_horse[horses.LTC] = true; winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.LTC].total); } } else { if (horses.LTC_delta > horses.ETH_delta) { winner_horse[horses.LTC] = true; winnerPoolTotal = coinIndex[horses.LTC].total; } else if(horses.LTC_delta < horses.ETH_delta){ winner_horse[horses.ETH] = true; winner_horse[horses.BTC] = true; winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.BTC].total); } else { winner_horse[horses.LTC] = true; winner_horse[horses.ETH] = true; winner_horse[horses.BTC] = true; winnerPoolTotal = coinIndex[horses.ETH].total + (coinIndex[horses.BTC].total) + (coinIndex[horses.LTC].total); } } chronus.race_end = true; } // method to calculate an invidual's reward function calculateReward(address candidate) internal afterRace constant returns(uint winner_reward) { voter_info storage bettor = voterIndex[candidate]; if(chronus.voided_bet) { winner_reward = bettor.total_bet; } else { uint winning_bet_total; if(winner_horse[horses.BTC]) { winning_bet_total += bettor.bets[horses.BTC]; } if(winner_horse[horses.ETH]) { winning_bet_total += bettor.bets[horses.ETH]; } if(winner_horse[horses.LTC]) { winning_bet_total += bettor.bets[horses.LTC]; } winner_reward += (((total_reward.mul(10000000)).div(winnerPoolTotal)).mul(winning_bet_total)).div(10000000); } } // method to just check the reward amount function checkReward() afterRace external constant returns (uint) { require(!voterIndex[msg.sender].rewarded); return calculateReward(msg.sender); } // method to claim the reward amount function claim_reward() afterRace external { require(!voterIndex[msg.sender].rewarded); uint transfer_amount = calculateReward(msg.sender); require(address(this).balance >= transfer_amount); voterIndex[msg.sender].rewarded = true; msg.sender.transfer(transfer_amount); emit Withdraw(msg.sender, transfer_amount); } function forceVoidRace() internal { chronus.voided_bet=true; chronus.race_end = true; chronus.voided_timestamp=uint32(now); } // utility function to convert string to integer with precision consideration function stringToUintNormalize(string s) internal pure returns (uint result) { uint p =2; bool precision=false; bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { if (precision) {p = p-1;} if (uint(b[i]) == 46){precision = true;} uint c = uint(b[i]); if (c >= 48 && c <= 57) {result = result * 10 + (c - 48);} if (precision && p == 0){return result;} } while (p!=0) { result = result*10; p=p-1; } } // exposing the coin pool details for DApp function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint) { return (coinIndex[index].total, coinIndex[index].pre, coinIndex[index].post, coinIndex[index].price_check, voterIndex[candidate].bets[index]); } // exposing the total reward amount for DApp function reward_total() external constant returns (uint) { return ((coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total)); } // in case of any errors in race, enable full refund for the Bettors to claim function refund() external onlyOwner { require(now > chronus.starting_time + chronus.race_duration); require((chronus.betting_open && !chronus.race_start) || (chronus.race_start && !chronus.race_end)); chronus.voided_bet = true; chronus.race_end = true; chronus.voided_timestamp=uint32(now); bettingControllerInstance.remoteBettingClose(); } // method to claim unclaimed winnings after 30 day notice period function recovery() external onlyOwner{ require((chronus.race_end && now > chronus.starting_time + chronus.race_duration + (30 days)) || (chronus.voided_bet && now > chronus.voided_timestamp + (30 days))); bettingControllerInstance.depositHouseTakeout.value(address(this).balance)(); } }
method to place the oraclize queries if (oraclize_getPrice("URL") > (this.balance)/6) { bets open price querybets closing price query
function setupRace(uint delay, uint locking_duration) onlyOwner beforeBetting public payable returns(bool) { if (oraclize_getPrice("URL")*3 + oraclize_getPrice("URL", horses.customGasLimit)*3 > address(this).balance) { emit newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); return false; chronus.starting_time = uint32(block.timestamp); chronus.betting_open = true; emit newOraclizeQuery("Oraclize query was sent, standing by for the answer.."); chronus.betting_duration = uint32(delay); oraclizeIndex[temp_ID] = horses.ETH; coinIndex[horses.ETH].preOraclizeId = temp_ID; oraclizeIndex[temp_ID] = horses.LTC; coinIndex[horses.LTC].preOraclizeId = temp_ID; oraclizeIndex[temp_ID] = horses.BTC; coinIndex[horses.BTC].preOraclizeId = temp_ID; delay = delay.add(locking_duration); oraclizeIndex[temp_ID] = horses.ETH; coinIndex[horses.ETH].postOraclizeId = temp_ID; oraclizeIndex[temp_ID] = horses.LTC; coinIndex[horses.LTC].postOraclizeId = temp_ID; oraclizeIndex[temp_ID] = horses.BTC; coinIndex[horses.BTC].postOraclizeId = temp_ID; chronus.race_duration = uint32(delay); return true; } }
1,131,244
// SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./IERC721Receiver.sol"; import "./Pausable.sol"; import "./IWoolf.sol"; import "./MutantPeach.sol"; contract Forest is Ownable, IERC721Receiver, Pausable { // maximum alpha score for a Wolf uint8 public constant MAX_ALPHA = 8; // struct to store a stake's token, owner, and earning values struct Stake { uint16 tokenId; uint80 value; address owner; } event TokenStaked(address owner, uint256 tokenId, uint256 value); event ApeClaimed(uint256 tokenId, uint256 earned, bool unstaked); event WolfClaimed(uint256 tokenId, uint256 earned, bool unstaked); // reference to the IWoolf NFT contract IWoolf woolf; // reference to the $MutantPeach contract for minting $MutantPeach earnings MutantPeach mutantPeach; // maps tokenId to stake mapping(uint256 => Stake) public forest; // maps alpha to all Wolf stakes with that alpha mapping(uint256 => Stake[]) public pack; // tracks location of each Wolf in Pack mapping(uint256 => uint256) public packIndices; // total alpha scores staked uint256 public totalAlphaStaked = 0; // any rewards distributed when no wolves are staked uint256 public unaccountedRewards = 0; // amount of $MutantPeach due for each alpha point staked uint256 public woolPerAlpha = 0; // ape earn 5000 $MutantPeach per day uint256 public constant DAILY_MP_RATE = 5000 ether; // ape must have 2 days worth of $MutantPeach to unstake or else it's too cold uint256 public constant MINIMUM_TO_EXIT = 4 days; // wolves take a 20% tax on all $MutantPeach claimed uint256 public constant MP_CLAIM_TAX_PERCENTAGE = 20; // there will only ever be (roughly) 2.4 billion $MutantPeach earned through staking uint256 public constant MAXIMUM_GLOBAL_MP = 2400000000 ether; // amount of $MutantPeach earned so far uint256 public totalWoolEarned; // number of Ape staked in the Forest uint256 public totalApeStaked; // the last time $MutantPeach was claimed uint256 public lastClaimTimestamp; // emergency rescue to allow unstaking without any checks but without $MutantPeach bool public rescueEnabled = false; /** * @param _woolf reference to the IWoolf NFT contract * @param _peach reference to the $MutantPeach token */ constructor(address _woolf, address _peach) { woolf = IWoolf(_woolf); mutantPeach = MutantPeach(_peach); } /** STAKING */ /** * adds Ape and Wolves to the Forest and Pack * @param account the address of the staker * @param tokenIds the IDs of the Ape and Wolves to stake */ function addManyToForestAndPack(address account, uint16[] calldata tokenIds) external { require(account == _msgSender() || _msgSender() == address(woolf), "DONT GIVE YOUR TOKENS AWAY"); for (uint256 i = 0; i < tokenIds.length; i++) { if (_msgSender() != address(woolf)) { // dont do this step if its a mint + stake require(woolf.ownerOf(tokenIds[i]) == _msgSender(), "AINT YO TOKEN"); woolf.transferFrom(_msgSender(), address(this), tokenIds[i]); } else if (tokenIds[i] == 0) { continue; // there may be gaps in the array for stolen tokens } if (isApe(tokenIds[i])) _addApeToForest(account, tokenIds[i]); else _addWolfToPack(account, tokenIds[i]); } } /** * adds a single Ape to the Forest * @param account the address of the staker * @param tokenId the ID of the Ape to add to the Forest */ function _addApeToForest(address account, uint256 tokenId) internal whenNotPaused _updateEarnings { forest[tokenId] = Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(block.timestamp) }); totalApeStaked += 1; emit TokenStaked(account, tokenId, block.timestamp); } /** * adds a single Wolf to the Pack * @param account the address of the staker * @param tokenId the ID of the Wolf to add to the Pack */ function _addWolfToPack(address account, uint256 tokenId) internal { uint256 alpha = _alphaForWolf(tokenId); totalAlphaStaked += alpha; // Portion of earnings ranges from 8 to 5 packIndices[tokenId] = pack[alpha].length; // Store the location of the wolf in the Pack pack[alpha].push(Stake({ owner: account, tokenId: uint16(tokenId), value: uint80(woolPerAlpha) })); // Add the wolf to the Pack emit TokenStaked(account, tokenId, woolPerAlpha); } /** CLAIMING / UNSTAKING */ /** * realize $MutantPeach earnings and optionally unstake tokens from the Forest / Pack * to unstake a Ape it will require it has 2 days worth of $MutantPeach unclaimed * @param tokenIds the IDs of the tokens to claim earnings from * @param unstake whether or not to unstake ALL of the tokens listed in tokenIds */ function claimManyFromForestAndPack(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings { uint256 owed = 0; for (uint256 i = 0; i < tokenIds.length; i++) { if (isApe(tokenIds[i])) owed += _claimApeFromForest(tokenIds[i], unstake); else owed += _claimWolfFromPack(tokenIds[i], unstake); } if (owed == 0) return; mutantPeach.mint(_msgSender(), owed); } /** * realize $MutantPeach earnings for a single Ape and optionally unstake it * if not unstaking, pay a 20% tax to the staked Wolves * if unstaking, there is a 50% chance all $MutantPeach is stolen * @param tokenId the ID of the Ape to claim earnings from * @param unstake whether or not to unstake the Ape * @return owed - the amount of $MutantPeach earned */ function _claimApeFromForest(uint256 tokenId, bool unstake) internal returns (uint256 owed) { Stake memory stake = forest[tokenId]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S MutantPeach"); if (totalWoolEarned < MAXIMUM_GLOBAL_MP) { owed = ((block.timestamp - stake.value) * DAILY_MP_RATE) / 1 days; } else if (stake.value > lastClaimTimestamp) { owed = 0; // $MutantPeach production stopped already } else { owed = ((lastClaimTimestamp - stake.value) * DAILY_MP_RATE) / 1 days; // stop earning additional $MutantPeach if it's all been earned } if (unstake) { if (random(tokenId) & 1 == 1) { // 50% chance of all $MutantPeach stolen _payWolfTax(owed); owed = 0; } woolf.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Ape delete forest[tokenId]; totalApeStaked -= 1; } else { _payWolfTax((owed * MP_CLAIM_TAX_PERCENTAGE) / 100); // percentage tax to staked wolves owed = (owed * (100 - MP_CLAIM_TAX_PERCENTAGE)) / 100; // remainder goes to Ape owner forest[tokenId] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(block.timestamp) }); // reset stake } emit ApeClaimed(tokenId, owed, unstake); } /** * realize $MutantPeach earnings for a single Wolf and optionally unstake it * Wolves earn $MutantPeach proportional to their Alpha rank * @param tokenId the ID of the Wolf to claim earnings from * @param unstake whether or not to unstake the Wolf * @return owed - the amount of $MutantPeach earned */ function _claimWolfFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) { require(woolf.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK"); uint256 alpha = _alphaForWolf(tokenId); Stake memory stake = pack[alpha][packIndices[tokenId]]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); owed = (alpha) * (woolPerAlpha - stake.value); // Calculate portion of tokens based on Alpha if (unstake) { totalAlphaStaked -= alpha; // Remove Alpha from total staked woolf.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Wolf Stake memory lastStake = pack[alpha][pack[alpha].length - 1]; pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Wolf to current position packIndices[lastStake.tokenId] = packIndices[tokenId]; pack[alpha].pop(); // Remove duplicate delete packIndices[tokenId]; // Delete old mapping } else { pack[alpha][packIndices[tokenId]] = Stake({ owner: _msgSender(), tokenId: uint16(tokenId), value: uint80(woolPerAlpha) }); // reset stake } emit WolfClaimed(tokenId, owed, unstake); } /** * emergency unstake tokens * @param tokenIds the IDs of the tokens to claim earnings from */ function rescue(uint256[] calldata tokenIds) external { require(rescueEnabled, "RESCUE DISABLED"); uint256 tokenId; Stake memory stake; Stake memory lastStake; uint256 alpha; for (uint256 i = 0; i < tokenIds.length; i++) { tokenId = tokenIds[i]; if (isApe(tokenId)) { stake = forest[tokenId]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); woolf.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Ape delete forest[tokenId]; totalApeStaked -= 1; emit ApeClaimed(tokenId, 0, true); } else { alpha = _alphaForWolf(tokenId); stake = pack[alpha][packIndices[tokenId]]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); totalAlphaStaked -= alpha; // Remove Alpha from total staked woolf.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Wolf lastStake = pack[alpha][pack[alpha].length - 1]; pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Wolf to current position packIndices[lastStake.tokenId] = packIndices[tokenId]; pack[alpha].pop(); // Remove duplicate delete packIndices[tokenId]; // Delete old mapping emit WolfClaimed(tokenId, 0, true); } } } /** ACCOUNTING */ /** * add $MutantPeach to claimable pot for the Pack * @param amount $MutantPeach to add to the pot */ function _payWolfTax(uint256 amount) internal { if (totalAlphaStaked == 0) { // if there's no staked wolves unaccountedRewards += amount; // keep track of $MutantPeach due to wolves return; } // makes sure to include any unaccounted $MutantPeach woolPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked; unaccountedRewards = 0; } /** * tracks $MutantPeach earnings to ensure it stops once 2.4 billion is eclipsed */ modifier _updateEarnings() { if (totalWoolEarned < MAXIMUM_GLOBAL_MP) { totalWoolEarned += ((block.timestamp - lastClaimTimestamp) * totalApeStaked * DAILY_MP_RATE) / 1 days; lastClaimTimestamp = block.timestamp; } _; } /** ADMIN */ /** * allows owner to enable "rescue mode" * simplifies accounting, prioritizes tokens out in emergency */ function setRescueEnabled(bool _enabled) external onlyOwner { rescueEnabled = _enabled; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } function getPackByAlphaAndID(uint256 alpha, uint256 tokenId) public view returns (Stake memory) { return pack[alpha][packIndices[tokenId]]; } function getForestStakeByID(uint256 id) public view returns (Stake memory) { return forest[id]; } /** READ ONLY */ /** * checks if a token is a Ape * @param tokenId the ID of the token to check * @return ape - whether or not a token is a Ape */ function isApe(uint256 tokenId) public view returns (bool ape) { // (ape, , , , , , ) = woolf.getTokenTraits(tokenId); IWoolf.ApeWolf memory obj = woolf.getTokenTraits(tokenId); return obj.isApe; } /** * gets the alpha score for a Wolf * @param tokenId the ID of the Wolf to get the alpha score for * @return the alpha score of the Wolf (5-8) */ function _alphaForWolf(uint256 tokenId) internal view returns (uint8) { IWoolf.ApeWolf memory obj = woolf.getTokenTraits(tokenId); return MAX_ALPHA - obj.alphaIndex; // alpha index is 0-3 } /** * chooses a random Wolf thief when a newly minted token is stolen * @param seed a random value to choose a Wolf from * @return the owner of the randomly selected Wolf thief */ function randomWolfOwner(uint256 seed) external view returns (address) { if (totalAlphaStaked == 0) return address(0x0); uint256 bucket = (seed & 0xFFFFFFFF) % totalAlphaStaked; // choose a value from 0 to total alpha staked uint256 cumulative; seed >>= 32; // loop through each bucket of Wolves with the same alpha score for (uint256 i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { cumulative += pack[i].length * i; // if the value is not inside of that bucket, keep going if (bucket >= cumulative) continue; // get the address of a random Wolf with that alpha score return pack[i][seed % pack[i].length].owner; } return address(0x0); } /** * generates a pseudorandom number * @param seed a value ensure different outcomes for different sources in the same block * @return a pseudorandom value */ function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(tx.origin, blockhash(block.number - 1), block.timestamp, seed))); } function setWolfAddress(address _address) external onlyOwner { woolf = IWoolf(_address); } function setWoolAddress(address _address) external onlyOwner { mutantPeach = MutantPeach(_address); } function onERC721Received( address, address from, uint256, bytes calldata ) external pure override returns (bytes4) { require(from == address(0x0), "Cannot send tokens to Forest directly"); return IERC721Receiver.onERC721Received.selector; } }
realize $MutantPeach earnings for a single Ape and optionally unstake it if not unstaking, pay a 20% tax to the staked Wolves if unstaking, there is a 50% chance all $MutantPeach is stolen tokenId the ID of the Ape to claim earnings from unstake whether or not to unstake the Ape return owed - the amount of $MutantPeach earned/ 50% chance of all $MutantPeach stolen
function _claimApeFromForest(uint256 tokenId, bool unstake) internal returns (uint256 owed) { Stake memory stake = forest[tokenId]; require(stake.owner == _msgSender(), "SWIPER, NO SWIPING"); require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S MutantPeach"); if (totalWoolEarned < MAXIMUM_GLOBAL_MP) { owed = ((block.timestamp - stake.value) * DAILY_MP_RATE) / 1 days; } if (unstake) { if (random(tokenId) & 1 == 1) { _payWolfTax(owed); owed = 0; } delete forest[tokenId]; totalApeStaked -= 1; } emit ApeClaimed(tokenId, owed, unstake); }
12,198,913
./full_match/8453/0xc61272050032D42faBD2F36c5E5EbF397c1A4684/sources/contracts/interface/IERC721Metadata.sol
ERC-721 Non-Fungible Token Standard, optional metadata extension/
interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint tokenId) external view returns (string memory); }
11,543,256
pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "admin only"); require(accrualBlockNumber == 0 && borrowIndex == 0, "initialized"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "invalid exchange rate"); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "set comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "set IRM failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = getCTokenBalanceInternal(account); uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */ function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves); } /** * @notice Returns the estimated per-block supply interest rate for this cToken after some change * @return The supply interest rate per block, scaled by 1e18 */ function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { accrueInterest(); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { accrueInterest(); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { accrueInterest(); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ uint256 blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint256 totalReservesNew = mul_ScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh( address payable borrower, uint256 borrowAmount, bool isNative ) internal returns (uint256) { /* Fail if borrow not allowed */ require(comptroller.borrowAllowed(address(this), borrower, borrowAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Reverts if protocol has insufficient cash */ require(getCashPrior() >= borrowAmount, "insufficient cash"); BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal( address borrower, uint256 repayAmount, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ require(comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); require(cTokenCollateral.accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative); } struct LiquidateBorrowLocalVars { uint256 repayBorrowError; uint256 actualRepayAmount; uint256 amountSeizeError; uint256 seizeTokens; } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ require( comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ) == 0, "rejected" ); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Verify cTokenCollateral market's block number equals current block number */ require(cTokenCollateral.accrualBlockNumber() == getBlockNumber(), "market is stale"); /* Fail if borrower = liquidator */ require(borrower != liquidator, "invalid account pair"); /* Fail if repayAmount = 0 or repayAmount = -1 */ require(repayAmount > 0 && repayAmount != uint256(-1), "invalid amount"); LiquidateBorrowLocalVars memory vars; /* Fail if repayBorrow fails */ (vars.repayBorrowError, vars.actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative); require(vars.repayBorrowError == uint256(Error.NO_ERROR), "repay borrow failed"); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (vars.amountSeizeError, vars.seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), vars.actualRepayAmount ); require(vars.amountSeizeError == uint256(Error.NO_ERROR), "calculate seize amount failed"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= vars.seizeTokens, "seize too much"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, vars.seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, vars.seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, vars.actualRepayAmount, address(cTokenCollateral), vars.seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify( address(this), address(cTokenCollateral), liquidator, borrower, vars.actualRepayAmount, vars.seizeTokens ); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "not comptroller"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { accrueInterest(); // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (uint256 error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { accrueInterest(); // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in wrapped token. Implementations except `CWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, false); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { accrueInterest(); // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "invalid IRM"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256); /** * @notice Get the account's cToken balances */ function getCTokenBalanceInternal(address account) internal view returns (uint256); /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256); /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./ERC3156FlashBorrowerInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Implementation address for this contract */ address public implementation; } contract CSupplyCapStorage { /** * @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract CCollateralCapStorage { /** * @notice Total number of tokens used as collateral in circulation. */ uint256 public totalCollateralTokens; /** * @notice Record of token balances which could be treated as collateral for each account. * If collateral cap is not set, the value should be equal to accountTokens. */ mapping(address => uint256) public accountCollateralTokens; /** * @notice Check if accountCollateralTokens have been initialized. */ mapping(address => bool) public isCollateralTokenInit; /** * @notice Collateral cap for this CToken, zero for no cap. */ uint256 public collateralCap; } /*** Interface ***/ contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) public view returns (uint256); function exchangeRateCurrent() public returns (uint256); function exchangeRateStored() public view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() public returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256); function _acceptAdmin() external returns (uint256); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256); function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256); } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256); function _addReserves(uint256 addAmount) external returns (uint256); } contract CWrappedNativeInterface is CErc20Interface { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function mintNative() external payable returns (uint256); function redeemNative(uint256 redeemTokens) external returns (uint256); function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256); function borrowNative(uint256 borrowAmount) external returns (uint256); function repayBorrowNative() external payable returns (uint256); function repayBorrowBehalfNative(address borrower) external payable returns (uint256); function liquidateBorrowNative(address borrower, CTokenInterface cTokenCollateral) external payable returns (uint256); function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); function _addReservesNative() external payable returns (uint256); function collateralCap() external view returns (uint256); function totalCollateralTokens() external view returns (uint256); } contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function gulp() external; } contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage { /*** Admin Events ***/ /** * @notice Event emitted when collateral cap is set */ event NewCollateralCap(address token, uint256 newCap); /** * @notice Event emitted when user collateral is changed */ event UserCollateralChanged(address account, uint256 newCollateralTokens); /*** User Interface ***/ function registerCollateral(address account) external returns (uint256); function unregisterCollateral(address account) external; function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); /*** Admin Functions ***/ function _setCollateralCap(uint256 newCollateralCap) external; } contract CDelegatorInterface { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public; } contract CDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /*** External interface ***/ /** * @title Flash loan receiver interface */ interface IFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle/PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./LiquidityMiningInterface.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound (modified by Cream) */ contract Comptroller is ComptrollerV1Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an admin delists a market event MarketDelisted(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when liquidity mining module is changed event NewLiquidityMining(address oldLiquidityMining, address newLiquidityMining); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint256 newBorrowCap); /// @notice Emitted when supply cap for a cToken is changed event NewSupplyCap(CToken indexed cToken, uint256 newSupplyCap); /// @notice Emitted when protocol's credit limit has changed event CreditLimitChanged(address protocol, address market, uint256 creditLimit); /// @notice Emitted when cToken version is changed event NewCTokenVersion(CToken cToken, Version oldVersion, Version newVersion); /// @notice Emitted when credit limit manager is changed event NewCreditLimitManager(address oldCreditLimitManager, address newCreditLimitManager); // No collateralFactorMantissa may exceed this value uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint256[] memory) { uint256 len = cTokens.length; uint256[] memory results = new uint256[](len); for (uint256 i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint256(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; require(marketToJoin.isListed, "market not listed"); if (marketToJoin.version == Version.COLLATERALCAP) { // register collateral for the borrower if the token is CollateralCap version. CCollateralCapErc20Interface(address(cToken)).registerCollateral(borrower); } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ require(amountOwed == 0, "nonzero borrow balance"); /* Fail if the sender is not permitted to redeem all of their tokens */ require(redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld) == 0, "failed to exit market"); Market storage marketToExit = markets[cTokenAddress]; if (marketToExit.version == Version.COLLATERALCAP) { CCollateralCapErc20Interface(cTokenAddress).unregisterCollateral(msg.sender); } /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; if (assetIndex != storedList.length - 1) { storedList[assetIndex] = storedList[storedList.length - 1]; } storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice Return a specific market is listed or not * @param cTokenAddress The address of the asset to be checked * @return Whether or not the market is listed */ function isMarketListed(address cTokenAddress) public view returns (bool) { return markets[cTokenAddress].isListed; } /** * @notice Return the credit limit of a specific protocol * @dev This function shouldn't be called. It exists only for backward compatibility. * @param protocol The address of the protocol * @return The credit */ function creditLimits(address protocol) public view returns (uint256) { protocol; // Shh return 0; } /** * @notice Return the credit limit of a specific protocol for a specific market * @param protocol The address of the protocol * @param market The market * @return The credit */ function creditLimits(address protocol, address market) public view returns (uint256) { return _creditLimits[protocol][market]; } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); require(!isCreditAccount(minter, cToken), "credit account cannot mint"); require(isMarketListed(cToken), "market not listed"); uint256 supplyCap = supplyCaps[cToken]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint256 totalCash = CToken(cToken).getCash(); uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 totalReserves = CToken(cToken).totalReserves(); // totalSupplies = totalCash + totalBorrows - totalReserves (MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves); require(mathErr == MathError.NO_ERROR, "totalSupplies failed"); uint256 nextTotalSupplies = add_(totalSupplies, mintAmount); require(nextTotalSupplies < supplyCap, "market supply cap reached"); } return uint256(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify( address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256) { return redeemAllowedInternal(cToken, redeemer, redeemTokens); } function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { require(isMarketListed(cToken) || isMarkertDelisted[cToken], "market not listed"); require(!isCreditAccount(redeemer, cToken), "credit account cannot redeem"); /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall == 0, "insufficient liquidity"); return uint256(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); require(isMarketListed(cToken), "market not listed"); if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market require(addToMarketInternal(CToken(cToken), borrower) == Error.NO_ERROR, "failed to add market"); // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } require(oracle.getUnderlyingPrice(CToken(cToken)) != 0, "price error"); uint256 borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } uint256 creditLimit = _creditLimits[borrower][cToken]; // If the borrower is a credit account, check the credit limit instead of account liquidity. if (creditLimit > 0) { (uint256 oErr, , uint256 borrowBalance, ) = CToken(cToken).getAccountSnapshot(borrower); require(oErr == 0, "snapshot error"); require(creditLimit >= add_(borrowBalance, borrowAmount), "insufficient credit limit"); } else { (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall == 0, "insufficient liquidity"); } return uint256(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256) { // Shh - currently unused repayAmount; require(isMarketListed(cToken) || isMarkertDelisted[cToken], "market not listed"); if (isCreditAccount(borrower, cToken)) { require(borrower == payer, "cannot repay on behalf of credit account"); } return uint256(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint256 actualRepayAmount, uint256 borrowerIndex ) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { require(!isCreditAccount(borrower, cTokenBorrowed), "cannot liquidate credit account"); // Shh - currently unused liquidator; require(isMarketListed(cTokenBorrowed) && isMarketListed(cTokenCollateral), "market not listed"); /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall > 0, "insufficient shortfall"); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } return uint256(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 actualRepayAmount, uint256 seizeTokens ) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); require(!isCreditAccount(borrower, cTokenBorrowed), "cannot sieze from credit account"); // Shh - currently unused liquidator; seizeTokens; require(isMarketListed(cTokenBorrowed) && isMarketListed(cTokenCollateral), "market not listed"); require( CToken(cTokenCollateral).comptroller() == CToken(cTokenBorrowed).comptroller(), "comptroller mismatched" ); return uint256(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); require(!isCreditAccount(dst, cToken), "cannot transfer to a credit account"); // Shh - currently unused dst; // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(cToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param receiver The account which receives the tokens * @param amount The amount of the tokens * @param params The other parameters */ function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool) { return !flashloanGuardianPaused[cToken]; } /** * @notice Update CToken's version. * @param cToken Version of the asset being updated * @param newVersion The new version */ function updateCTokenVersion(address cToken, Version newVersion) external { require(msg.sender == cToken, "cToken only"); // This function will be called when a new CToken implementation becomes active. // If a new CToken is newly created, this market is not listed yet. The version of // this market will be taken care of when calling `_supportMarket`. if (isMarketListed(cToken)) { Version oldVersion = markets[cToken].version; markets[cToken].version = newVersion; emit NewCTokenVersion(CToken(cToken), oldVersion, newVersion); } } /** * @notice Check if the account is a credit account * @param account The account needs to be checked * @param cToken The market * @return The account is a credit account or not */ function isCreditAccount(address account, address cToken) public view returns (bool) { return _creditLimits[account][cToken] > 0; } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 cTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(0), 0, 0 ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns ( Error, uint256, uint256 ) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(cTokenModify), redeemTokens, borrowAmount ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint256 oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Skip the asset if it is not listed. if (!isMarketListed(address(asset))) { continue; } // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot( account ); require(oErr == 0, "snapshot error"); // Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed. // If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it. if (vars.cTokenBalance == 0 && vars.borrowBalance == 0 && asset != cTokenModify) { continue; } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); require(vars.oraclePriceMantissa > 0, "price error"); vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256, uint256) { /* Read oracle prices for borrowed and collateral markets */ uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); require(priceBorrowedMantissa > 0 && priceCollateralMantissa > 0, "price error"); /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint256 exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error Exp memory numerator = mul_( Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}) ); Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); Exp memory ratio = div_(numerator, denominator); uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint256(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint256(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } uint256 oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint256 newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint256(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @param version The version of the market (token) * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken, Version version) external returns (uint256) { require(msg.sender == admin, "admin only"); require(!isMarketListed(address(cToken)), "market already listed"); cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint256(Error.NO_ERROR); } /** * @notice Remove the market from the markets mapping * @param cToken The address of the market (token) to delist */ function _delistMarket(CToken cToken) external { require(msg.sender == admin, "admin only"); require(isMarketListed(address(cToken)), "market not listed"); require(markets[address(cToken)].collateralFactorMantissa == 0, "market has collateral"); cToken.isCToken(); // Sanity check to make sure its really a CToken isMarkertDelisted[address(cToken)] = true; delete markets[address(cToken)]; for (uint256 i = 0; i < allMarkets.length; i++) { if (allMarkets[i] == cToken) { allMarkets[i] = allMarkets[allMarkets.length - 1]; delete allMarkets[allMarkets.length - 1]; allMarkets.length--; break; } } emit MarketDelisted(cToken); } function _addMarketInternal(address cToken) internal { for (uint256 i = 0; i < allMarkets.length; i++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Set the given supply caps for the given cToken markets. Supplying that brings total supplys to or above supply cap will revert. * @dev Admin or pauseGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows * already exceeded the cap, it will prevent anyone to borrow. * @param cTokens The addresses of the markets (tokens) to change the supply caps for * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. */ function _setMarketSupplyCaps(CToken[] calldata cTokens, uint256[] calldata newSupplyCaps) external { require(msg.sender == admin || msg.sender == pauseGuardian, "admin or guardian only"); uint256 numMarkets = cTokens.length; uint256 numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { supplyCaps[address(cTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(cTokens[i], newSupplyCaps[i]); } } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or pauseGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies * already exceeded the cap, it will prevent anyone to mint. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint256[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == pauseGuardian, "admin or guardian only"); uint256 numMarkets = cTokens.length; uint256 numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint256(Error.NO_ERROR); } /** * @notice Admin function to set the liquidity mining module address * @dev Removing the liquidity mining module address could cause the inconsistency in the LM module. * @param newLiquidityMining The address of the new liquidity mining module */ function _setLiquidityMining(address newLiquidityMining) external { require(msg.sender == admin, "admin only"); require(LiquidityMiningInterface(newLiquidityMining).comptroller() == address(this), "mismatch comptroller"); // Save current value for inclusion in log address oldLiquidityMining = liquidityMining; // Store liquidityMining with value newLiquidityMining liquidityMining = newLiquidityMining; // Emit NewLiquidityMining(OldLiquidityMining, NewLiquidityMining) emit NewLiquidityMining(oldLiquidityMining, liquidityMining); } /** * @notice Admin function to set the credit limit manager address * @param newCreditLimitManager The address of the new credit limit manager */ function _setCreditLimitManager(address newCreditLimitManager) external { require(msg.sender == admin, "admin only"); // Save current value for inclusion in log address oldCreditLimitManager = creditLimitManager; // Store creditLimitManager with value newCreditLimitManager creditLimitManager = newCreditLimitManager; // Emit NewCreditLimitManager(oldCreditLimitManager, newCreditLimitManager) emit NewCreditLimitManager(oldCreditLimitManager, creditLimitManager); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setFlashloanPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); flashloanGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Flashloan", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "unitroller admin only"); require(unitroller._acceptImplementation() == 0, "unauthorized"); } /** * @notice Sets protocol's credit limit by market * @param protocol The address of the protocol * @param market The market * @param creditLimit The credit limit */ function _setCreditLimit( address protocol, address market, uint256 creditLimit ) public { require( msg.sender == admin || msg.sender == creditLimitManager || msg.sender == pauseGuardian, "admin or credit limit manager or pause guardian only" ); require(isMarketListed(market), "market not listed"); if (_creditLimits[protocol][market] == 0 && creditLimit != 0) { // Only admin or credit limit manager could set a new credit limit. require(msg.sender == admin || msg.sender == creditLimitManager, "admin or credit limit manager only"); } _creditLimits[protocol][market] = creditLimit; emit CreditLimitChanged(protocol, market, creditLimit); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint256) { return block.number; } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ComptrollerStorage.sol"; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } interface ComptrollerInterfaceExtension { function checkMembership(address account, CToken cToken) external view returns (bool); function updateCTokenVersion(address cToken, ComptrollerV1Storage.Version version) external; function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function supplyCaps(address market) external view returns (uint256); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle/PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; /** * @notice Per-account mapping of "assets you are in" */ mapping(address => CToken[]) public accountAssets; enum Version { VANILLA, COLLATERALCAP, WRAPPEDNATIVE } struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint256 collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice CToken version Version version; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The portion of compRate that each market currently receives /// @dev This storage is depreacted. mapping(address => uint256) public compSpeeds; /// @notice The COMP market supply state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user /// @dev This storage is depreacted. mapping(address => uint256) public compAccrued; /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint256) public borrowCaps; /// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market. address public supplyCapGuardian; /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint256) public supplyCaps; /// @notice creditLimits allowed specific protocols to borrow and repay without collateral. /// @dev This storage is depreacted. mapping(address => uint256) internal _oldCreditLimits; /// @notice flashloanGuardianPaused can pause flash loan as a safety mechanism. mapping(address => bool) public flashloanGuardianPaused; /// @notice liquidityMining the liquidity mining module that handles the LM rewards distribution. address public liquidityMining; /// @notice creditLimits allowed specific protocols to borrow and repay specific markets without collateral. mapping(address => mapping(address => uint256)) internal _creditLimits; /// @notice isMarkertDelisted records the market which has been delisted by us. mapping(address => bool) public isMarkertDelisted; /// @notice creditLimitManager is the role who is in charge of increasing the credit limit. address public creditLimitManager; } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @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 * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; interface ERC3156FlashBorrowerInterface { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ uint256 numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity ^0.5.16; contract Comp { /// @notice EIP-20 token name for this token string public constant name = "Cream"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CREAM"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public constant totalSupply = 9000000e18; // 9 million Comp /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @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 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 rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); 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 dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { 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), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::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 (uint96) { 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, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::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]; uint96 delegatorBalance = balances[delegator]; 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), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Comp::_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(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 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 pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } pragma solidity ^0.5.16; contract LiquidityMiningInterface { function comptroller() external view returns (address); function updateSupplyIndex(address cToken, address[] calldata accounts) external; function updateBorrowIndex(address cToken, address[] calldata accounts) external; } pragma solidity ^0.5.16; import "../CToken.sol"; contract PriceOracle { /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint256); } pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint256) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function() external payable { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } }
Divide a scalar by an Exp, returning a new Exp./
function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) { We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` uint256 numerator = mul_(expScale, scalar); }
333,423
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOG714(address p0, uint p1, uint p2) internal view {
14,087,711
pragma solidity 0.5.12; pragma experimental ABIEncoderV2; // File: @airswap/types/contracts/Types.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Types: Library of Swap Protocol Types and Hashes */ library Types { bytes constant internal EIP191_HEADER = "\x19\x01"; 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 } bytes32 constant internal DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); bytes32 constant internal ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "uint256 nonce,", "uint256 expiry,", "Party signer,", "Party sender,", "Party affiliate", ")", "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 amount,", "uint256 id", ")" )); bytes32 constant internal PARTY_TYPEHASH = keccak256(abi.encodePacked( "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 amount,", "uint256 id", ")" )); /** * @notice Hash an order into bytes32 * @dev EIP-191 header and domain separator included * @param order Order The order to be hashed * @param domainSeparator bytes32 * @return bytes32 A keccak256 abi.encodePacked value */ function hashOrder( Order calldata order, bytes32 domainSeparator ) external pure returns (bytes32) { return keccak256(abi.encodePacked( EIP191_HEADER, domainSeparator, keccak256(abi.encode( ORDER_TYPEHASH, order.nonce, order.expiry, keccak256(abi.encode( PARTY_TYPEHASH, order.signer.kind, order.signer.wallet, order.signer.token, order.signer.amount, order.signer.id )), keccak256(abi.encode( PARTY_TYPEHASH, order.sender.kind, order.sender.wallet, order.sender.token, order.sender.amount, order.sender.id )), keccak256(abi.encode( PARTY_TYPEHASH, order.affiliate.kind, order.affiliate.wallet, order.affiliate.token, order.affiliate.amount, order.affiliate.id )) )) )); } /** * @notice Hash domain parameters into bytes32 * @dev Used for signature validation (EIP-712) * @param name bytes * @param version bytes * @param verifyingContract address * @return bytes32 returns a keccak256 abi.encodePacked value */ function hashDomain( bytes calldata name, bytes calldata version, address verifyingContract ) external pure returns (bytes32) { return keccak256(abi.encode( DOMAIN_TYPEHASH, keccak256(name), keccak256(version), verifyingContract )); } } // File: @airswap/delegate/contracts/interfaces/IDelegate.sol /* Copyright 2020 Swap Holdings 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. */ interface IDelegate { struct Rule { uint256 maxSenderAmount; // The maximum amount of ERC-20 token the delegate would send uint256 priceCoef; // Number to be multiplied by 10^(-priceExp) - the price coefficient uint256 priceExp; // Indicates location of the decimal priceCoef * 10^(-priceExp) } event SetRule( address indexed owner, address indexed senderToken, address indexed signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ); event UnsetRule( address indexed owner, address indexed senderToken, address indexed signerToken ); event ProvideOrder( address indexed owner, address tradeWallet, address indexed senderToken, address indexed signerToken, uint256 senderAmount, uint256 priceCoef, uint256 priceExp ); function setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) external; function unsetRule( address senderToken, address signerToken ) external; function provideOrder( Types.Order calldata order ) external; function rules(address, address) external view returns (Rule memory); function getSignerSideQuote( uint256 senderAmount, address senderToken, address signerToken ) external view returns ( uint256 signerAmount ); function getSenderSideQuote( uint256 signerAmount, address signerToken, address senderToken ) external view returns ( uint256 senderAmount ); function getMaxQuote( address senderToken, address signerToken ) external view returns ( uint256 senderAmount, uint256 signerAmount ); function owner() external view returns (address); function tradeWallet() external view returns (address); } // File: @airswap/indexer/contracts/interfaces/IIndexer.sol /* Copyright 2020 Swap Holdings 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. */ interface IIndexer { event CreateIndex( address indexed signerToken, address indexed senderToken, bytes2 protocol, address indexAddress ); event Stake( address indexed staker, address indexed signerToken, address indexed senderToken, bytes2 protocol, uint256 stakeAmount ); event Unstake( address indexed staker, address indexed signerToken, address indexed senderToken, bytes2 protocol, uint256 stakeAmount ); event AddTokenToBlacklist( address token ); event RemoveTokenFromBlacklist( address token ); function setLocatorWhitelist( bytes2 protocol, address newLocatorWhitelist ) external; function createIndex( address signerToken, address senderToken, bytes2 protocol ) external returns (address); function addTokenToBlacklist( address token ) external; function removeTokenFromBlacklist( address token ) external; function setIntent( address signerToken, address senderToken, bytes2 protocol, uint256 stakingAmount, bytes32 locator ) external; function unsetIntent( address signerToken, address senderToken, bytes2 protocol ) external; function stakingToken() external view returns (address); function indexes(address, address, bytes2) external view returns (address); function tokenBlacklist(address) external view returns (bool); function getStakedAmount( address user, address signerToken, address senderToken, bytes2 protocol ) external view returns (uint256); function getLocators( address signerToken, address senderToken, bytes2 protocol, address cursor, uint256 limit ) external view returns ( bytes32[] memory, uint256[] memory, address ); } // File: @airswap/transfers/contracts/interfaces/ITransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title ITransferHandler: interface for token transfers */ interface ITransferHandler { /** * @notice Function to wrap token transfer for different token types * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256 Amount for ERC-20 * @param id token ID for ERC-721 * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token ) external returns (bool); } // File: openzeppelin-solidity/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ 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-solidity/contracts/ownership/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * 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: @airswap/transfers/contracts/TransferHandlerRegistry.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title TransferHandlerRegistry: holds registry of contract to * facilitate token transfers */ contract TransferHandlerRegistry is Ownable { event AddTransferHandler( bytes4 kind, address contractAddress ); // Mapping of bytes4 to contract interface type mapping (bytes4 => ITransferHandler) public transferHandlers; /** * @notice Adds handler to mapping * @param kind bytes4 Key value that defines a token type * @param transferHandler ITransferHandler */ function addTransferHandler(bytes4 kind, ITransferHandler transferHandler) external onlyOwner { require(address(transferHandlers[kind]) == address(0), "HANDLER_EXISTS_FOR_KIND"); transferHandlers[kind] = transferHandler; emit AddTransferHandler(kind, address(transferHandler)); } } // File: @airswap/swap/contracts/interfaces/ISwap.sol /* Copyright 2020 Swap Holdings 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. */ 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 (byte); function signerMinimumNonce(address) external view returns (uint256); function registry() external view returns (TransferHandlerRegistry); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @airswap/delegate/contracts/Delegate.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Delegate: Deployable Trading Rules for the AirSwap Network * @notice Supports fungible tokens (ERC-20) * @dev inherits IDelegate, Ownable uses SafeMath library */ contract Delegate is IDelegate, Ownable { using SafeMath for uint256; // The Swap contract to be used to settle trades ISwap public swapContract; // The Indexer to stake intent to trade on IIndexer public indexer; // Maximum integer for token transfer approval uint256 constant internal MAX_INT = 2**256 - 1; // Address holding tokens that will be trading through this delegate address public tradeWallet; // Mapping of senderToken to signerToken for rule lookup mapping (address => mapping (address => Rule)) public rules; // ERC-20 (fungible token) interface identifier (ERC-165) bytes4 constant internal ERC20_INTERFACE_ID = 0x36372b07; // The protocol identifier for setting intents on an Index bytes2 public protocol; /** * @notice Contract Constructor * @dev owner defaults to msg.sender if delegateContractOwner is provided as address(0) * @param delegateSwap address Swap contract the delegate will deploy with * @param delegateIndexer address Indexer contract the delegate will deploy with * @param delegateContractOwner address Owner of the delegate * @param delegateTradeWallet address Wallet the delegate will trade from * @param delegateProtocol bytes2 The protocol identifier for Delegate contracts */ constructor( ISwap delegateSwap, IIndexer delegateIndexer, address delegateContractOwner, address delegateTradeWallet, bytes2 delegateProtocol ) public { swapContract = delegateSwap; indexer = delegateIndexer; protocol = delegateProtocol; // If no delegate owner is provided, the deploying address is the owner. if (delegateContractOwner != address(0)) { transferOwnership(delegateContractOwner); } // If no trade wallet is provided, the owner's wallet is the trade wallet. if (delegateTradeWallet != address(0)) { tradeWallet = delegateTradeWallet; } else { tradeWallet = owner(); } // Ensure that the indexer can pull funds from delegate account. require( IERC20(indexer.stakingToken()) .approve(address(indexer), MAX_INT), "STAKING_APPROVAL_FAILED" ); } /** * @notice Set a Trading Rule * @dev only callable by the owner of the contract * @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send * @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient * @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp) */ function setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) external onlyOwner { _setRule( senderToken, signerToken, maxSenderAmount, priceCoef, priceExp ); } /** * @notice Unset a Trading Rule * @dev only callable by the owner of the contract, removes from a mapping * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send */ function unsetRule( address senderToken, address signerToken ) external onlyOwner { _unsetRule( senderToken, signerToken ); } /** * @notice sets a rule on the delegate and an intent on the indexer * @dev only callable by owner * @dev delegate needs to be given allowance from msg.sender for the newStakeAmount * @dev swap needs to be given permission to move funds from the delegate * @param senderToken address Token the delgeate will send * @param signerToken address Token the delegate will receive * @param rule Rule Rule to set on a delegate * @param newStakeAmount uint256 Amount to stake for an intent */ function setRuleAndIntent( address senderToken, address signerToken, Rule calldata rule, uint256 newStakeAmount ) external onlyOwner { _setRule( senderToken, signerToken, rule.maxSenderAmount, rule.priceCoef, rule.priceExp ); // get currentAmount staked or 0 if never staked uint256 oldStakeAmount = indexer.getStakedAmount(address(this), signerToken, senderToken, protocol); if (oldStakeAmount == newStakeAmount && oldStakeAmount > 0) { return; // forgo trying to reset intent with non-zero same stake amount } else if (oldStakeAmount < newStakeAmount) { // transfer only the difference from the sender to the Delegate. require( IERC20(indexer.stakingToken()) .transferFrom(msg.sender, address(this), newStakeAmount - oldStakeAmount), "STAKING_TRANSFER_FAILED" ); } indexer.setIntent( signerToken, senderToken, protocol, newStakeAmount, bytes32(uint256(address(this)) << 96) //NOTE: this will pad 0's to the right ); if (oldStakeAmount > newStakeAmount) { // return excess stake back require( IERC20(indexer.stakingToken()) .transfer(msg.sender, oldStakeAmount - newStakeAmount), "STAKING_RETURN_FAILED" ); } } /** * @notice unsets a rule on the delegate and removes an intent on the indexer * @dev only callable by owner * @param senderToken address Maker token in the token pair for rules and intents * @param signerToken address Taker token in the token pair for rules and intents */ function unsetRuleAndIntent( address senderToken, address signerToken ) external onlyOwner { _unsetRule(senderToken, signerToken); // Query the indexer for the amount staked. uint256 stakedAmount = indexer.getStakedAmount(address(this), signerToken, senderToken, protocol); indexer.unsetIntent(signerToken, senderToken, protocol); // Upon unstaking, the Delegate will be given the staking amount. // This is returned to the msg.sender. if (stakedAmount > 0) { require( IERC20(indexer.stakingToken()) .transfer(msg.sender, stakedAmount),"STAKING_RETURN_FAILED" ); } } /** * @notice Provide an Order * @dev Rules get reset with new maxSenderAmount * @param order Types.Order Order a user wants to submit to Swap. */ function provideOrder( Types.Order calldata order ) external { Rule memory rule = rules[order.sender.token][order.signer.token]; require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Ensure the order is for the trade wallet. require(order.sender.wallet == tradeWallet, "SENDER_WALLET_INVALID"); // Ensure the tokens are valid ERC20 tokens. require(order.signer.kind == ERC20_INTERFACE_ID, "SIGNER_KIND_MUST_BE_ERC20"); require(order.sender.kind == ERC20_INTERFACE_ID, "SENDER_KIND_MUST_BE_ERC20"); // Ensure that a rule exists. require(rule.maxSenderAmount != 0, "TOKEN_PAIR_INACTIVE"); // Ensure the order does not exceed the maximum amount. require(order.sender.amount <= rule.maxSenderAmount, "AMOUNT_EXCEEDS_MAX"); // Ensure the order is priced according to the rule. require(order.sender.amount <= _calculateSenderAmount(order.signer.amount, rule.priceCoef, rule.priceExp), "PRICE_INVALID"); // Overwrite the rule with a decremented maxSenderAmount. rules[order.sender.token][order.signer.token] = Rule({ maxSenderAmount: (rule.maxSenderAmount).sub(order.sender.amount), priceCoef: rule.priceCoef, priceExp: rule.priceExp }); // Perform the swap. swapContract.swap(order); emit ProvideOrder( owner(), tradeWallet, order.sender.token, order.signer.token, order.sender.amount, rule.priceCoef, rule.priceExp ); } /** * @notice Set a new trade wallet * @param newTradeWallet address Address of the new trade wallet */ function setTradeWallet(address newTradeWallet) external onlyOwner { require(newTradeWallet != address(0), "TRADE_WALLET_REQUIRED"); tradeWallet = newTradeWallet; } /** * @notice Get a Signer-Side Quote from the Delegate * @param senderAmount uint256 Amount of ERC-20 token the delegate would send * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @return uint256 signerAmount Amount of ERC-20 token the consumer would send */ function getSignerSideQuote( uint256 senderAmount, address senderToken, address signerToken ) external view returns ( uint256 signerAmount ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Ensure the senderAmount does not exceed maximum for the rule. if(senderAmount <= rule.maxSenderAmount) { signerAmount = _calculateSignerAmount(senderAmount, rule.priceCoef, rule.priceExp); // Return the quote. return signerAmount; } } return 0; } /** * @notice Get a Sender-Side Quote from the Delegate * @param signerAmount uint256 Amount of ERC-20 token the consumer would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param senderToken address Address of an ERC-20 token the delegate would send * @return uint256 senderAmount Amount of ERC-20 token the delegate would send */ function getSenderSideQuote( uint256 signerAmount, address signerToken, address senderToken ) external view returns ( uint256 senderAmount ) { Rule memory rule = rules[senderToken][signerToken]; // Ensure that a rule exists. if(rule.maxSenderAmount > 0) { // Calculate the senderAmount. senderAmount = _calculateSenderAmount(signerAmount, rule.priceCoef, rule.priceExp); // Ensure the senderAmount does not exceed the maximum trade amount. if(senderAmount <= rule.maxSenderAmount) { return senderAmount; } } return 0; } /** * @notice Get a Maximum Quote from the Delegate * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @return uint256 senderAmount Amount the delegate would send * @return uint256 signerAmount Amount the consumer would send */ function getMaxQuote( address senderToken, address signerToken ) external view returns ( uint256 senderAmount, uint256 signerAmount ) { Rule memory rule = rules[senderToken][signerToken]; senderAmount = rule.maxSenderAmount; // Ensure that a rule exists. if (senderAmount > 0) { // calculate the signerAmount signerAmount = _calculateSignerAmount(senderAmount, rule.priceCoef, rule.priceExp); // Return the maxSenderAmount and calculated signerAmount. return ( senderAmount, signerAmount ); } return (0, 0); } /** * @notice Set a Trading Rule * @dev only callable by the owner of the contract * @dev 1 senderToken = priceCoef * 10^(-priceExp) * signerToken * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send * @param maxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would send * @param priceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficient * @param priceExp uint256 Exponent of the price to indicate location of the decimal priceCoef * 10^(-priceExp) */ function _setRule( address senderToken, address signerToken, uint256 maxSenderAmount, uint256 priceCoef, uint256 priceExp ) internal { require(priceCoef > 0, "PRICE_COEF_INVALID"); rules[senderToken][signerToken] = Rule({ maxSenderAmount: maxSenderAmount, priceCoef: priceCoef, priceExp: priceExp }); emit SetRule( owner(), senderToken, signerToken, maxSenderAmount, priceCoef, priceExp ); } /** * @notice Unset a Trading Rule * @param senderToken address Address of an ERC-20 token the delegate would send * @param signerToken address Address of an ERC-20 token the consumer would send */ function _unsetRule( address senderToken, address signerToken ) internal { // using non-zero rule.priceCoef for rule existence check if (rules[senderToken][signerToken].priceCoef > 0) { // Delete the rule. delete rules[senderToken][signerToken]; emit UnsetRule( owner(), senderToken, signerToken ); } } /** * @notice Calculate the signer amount for a given sender amount and price * @param senderAmount uint256 The amount the delegate would send in the swap * @param priceCoef uint256 Coefficient of the token price defined in the rule * @param priceExp uint256 Exponent of the token price defined in the rule */ function _calculateSignerAmount( uint256 senderAmount, uint256 priceCoef, uint256 priceExp ) internal pure returns ( uint256 signerAmount ) { // Calculate the signer amount using the price formula uint256 multiplier = senderAmount.mul(priceCoef); signerAmount = multiplier.div(10 ** priceExp); // If the div rounded down, round up if (multiplier.mod(10 ** priceExp) > 0) { signerAmount++; } } /** * @notice Calculate the sender amount for a given signer amount and price * @param signerAmount uint256 The amount the signer would send in the swap * @param priceCoef uint256 Coefficient of the token price defined in the rule * @param priceExp uint256 Exponent of the token price defined in the rule */ function _calculateSenderAmount( uint256 signerAmount, uint256 priceCoef, uint256 priceExp ) internal pure returns ( uint256 senderAmount ) { // Calculate the sender anount using the price formula senderAmount = signerAmount .mul(10 ** priceExp) .div(priceCoef); } } // File: @airswap/delegate/contracts/interfaces/IDelegateFactory.sol /* Copyright 2020 Swap Holdings 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. */ interface IDelegateFactory { event CreateDelegate( address indexed delegateContract, address swapContract, address indexerContract, address indexed delegateContractOwner, address delegateTradeWallet ); /** * @notice Deploy a trusted delegate contract * @param delegateTradeWallet the wallet the delegate will trade from * @return delegateContractAddress address of the delegate contract created */ function createDelegate( address delegateTradeWallet ) external returns (address delegateContractAddress); } // File: @airswap/indexer/contracts/interfaces/ILocatorWhitelist.sol /* Copyright 2020 Swap Holdings 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. */ interface ILocatorWhitelist { function has( bytes32 locator ) external view returns (bool); } // File: @airswap/delegate/contracts/DelegateFactory.sol /* Copyright 2020 Swap Holdings 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. */ contract DelegateFactory is IDelegateFactory, ILocatorWhitelist { // Mapping specifying whether an address was deployed by this factory mapping(address => bool) internal _deployedAddresses; // The swap and indexer contracts to use in the deployment of Delegates ISwap public swapContract; IIndexer public indexerContract; bytes2 public protocol; /** * @notice Create a new Delegate contract * @dev swapContract is unable to be changed after the factory sets it * @param factorySwapContract address Swap contract the delegate will deploy with * @param factoryIndexerContract address Indexer contract the delegate will deploy with * @param factoryProtocol bytes2 Protocol type of the delegates the factory deploys */ constructor( ISwap factorySwapContract, IIndexer factoryIndexerContract, bytes2 factoryProtocol ) public { swapContract = factorySwapContract; indexerContract = factoryIndexerContract; protocol = factoryProtocol; } /** * @param delegateTradeWallet address Wallet the delegate will trade from * @return address delegateContractAddress Address of the delegate contract created */ function createDelegate( address delegateTradeWallet ) external returns (address delegateContractAddress) { delegateContractAddress = address( new Delegate(swapContract, indexerContract, msg.sender, delegateTradeWallet, protocol) ); _deployedAddresses[delegateContractAddress] = true; emit CreateDelegate( delegateContractAddress, address(swapContract), address(indexerContract), msg.sender, delegateTradeWallet ); return delegateContractAddress; } /** * @notice To check whether a locator was deployed * @dev Implements ILocatorWhitelist.has * @param locator bytes32 Locator of the delegate in question * @return bool True if the delegate was deployed by this contract */ function has(bytes32 locator) external view returns (bool) { return _deployedAddresses[address(bytes20(locator))]; } } // File: @airswap/indexer/contracts/Index.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Index: A List of Locators * @notice The Locators are sorted in reverse order based on the score * meaning that the first element in the list has the largest score * and final element has the smallest * @dev A mapping is used to mimic a circular linked list structure * where every mapping Entry contains a pointer to the next * and the previous */ contract Index is Ownable { // The number of entries in the index uint256 public length; // Identifier to use for the head of the list address constant internal HEAD = address(uint160(2**160-1)); // Mapping of an identifier to its entry mapping(address => Entry) public entries; /** * @notice Index Entry * @param score uint256 * @param locator bytes32 * @param prev address Previous address in the linked list * @param next address Next address in the linked list */ struct Entry { bytes32 locator; uint256 score; address prev; address next; } /** * @notice Contract Events */ event SetLocator( address indexed identifier, uint256 score, bytes32 indexed locator ); event UnsetLocator( address indexed identifier ); /** * @notice Contract Constructor */ constructor() public { // Create initial entry. entries[HEAD] = Entry(bytes32(0), 0, HEAD, HEAD); } /** * @notice Set a Locator * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function setLocator( address identifier, uint256 score, bytes32 locator ) external onlyOwner { // Ensure the entry does not already exist. require(!_hasEntry(identifier), "ENTRY_ALREADY_EXISTS"); _setLocator(identifier, score, locator); // Increment the index length. length = length + 1; emit SetLocator(identifier, score, locator); } /** * @notice Unset a Locator * @param identifier address On-chain address identifying the owner of a locator */ function unsetLocator( address identifier ) external onlyOwner { _unsetLocator(identifier); // Decrement the index length. length = length - 1; emit UnsetLocator(identifier); } /** * @notice Update a Locator * @dev score and/or locator do not need to be different from old values * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function updateLocator( address identifier, uint256 score, bytes32 locator ) external onlyOwner { // Don't need to update length as it is not used in set/unset logic _unsetLocator(identifier); _setLocator(identifier, score, locator); emit SetLocator(identifier, score, locator); } /** * @notice Get a Score * @param identifier address On-chain address identifying the owner of a locator * @return uint256 Score corresponding to the identifier */ function getScore( address identifier ) external view returns (uint256) { return entries[identifier].score; } /** * @notice Get a Locator * @param identifier address On-chain address identifying the owner of a locator * @return bytes32 Locator information */ function getLocator( address identifier ) external view returns (bytes32) { return entries[identifier].locator; } /** * @notice Get a Range of Locators * @dev start value of 0x0 starts at the head * @param cursor address Cursor to start with * @param limit uint256 Maximum number of locators to return * @return bytes32[] List of locators * @return uint256[] List of scores corresponding to locators * @return address The next cursor to provide for pagination */ function getLocators( address cursor, uint256 limit ) external view returns ( bytes32[] memory locators, uint256[] memory scores, address nextCursor ) { address identifier; // If a valid cursor is provided, start there. if (cursor != address(0) && cursor != HEAD) { // Check that the provided cursor exists. if (!_hasEntry(cursor)) { return (new bytes32[](0), new uint256[](0), address(0)); } // Set the starting identifier to the provided cursor. identifier = cursor; } else { identifier = entries[HEAD].next; } // Although it's not known how many entries are between `cursor` and the end // We know that it is no more than `length` uint256 size = (length < limit) ? length : limit; locators = new bytes32[](size); scores = new uint256[](size); // Iterate over the list until the end or size. uint256 i; while (i < size && identifier != HEAD) { locators[i] = entries[identifier].locator; scores[i] = entries[identifier].score; i = i + 1; identifier = entries[identifier].next; } return (locators, scores, identifier); } /** * @notice Internal function to set a Locator * @param identifier address On-chain address identifying the owner of a locator * @param score uint256 Score for the locator being set * @param locator bytes32 Locator */ function _setLocator( address identifier, uint256 score, bytes32 locator ) internal { // Disallow locator set to 0x0 to ensure list integrity. require(locator != bytes32(0), "LOCATOR_MUST_BE_SENT"); // Find the first entry with a lower score. address nextEntry = _getEntryLowerThan(score); // Link the new entry between previous and next. address prevEntry = entries[nextEntry].prev; entries[prevEntry].next = identifier; entries[nextEntry].prev = identifier; entries[identifier] = Entry(locator, score, prevEntry, nextEntry); } /** * @notice Internal function to unset a Locator * @param identifier address On-chain address identifying the owner of a locator */ function _unsetLocator( address identifier ) internal { // Ensure the entry exists. require(_hasEntry(identifier), "ENTRY_DOES_NOT_EXIST"); // Link the previous and next entries together. address prevUser = entries[identifier].prev; address nextUser = entries[identifier].next; entries[prevUser].next = nextUser; entries[nextUser].prev = prevUser; // Delete entry from the index. delete entries[identifier]; } /** * @notice Check if the Index has an Entry * @param identifier address On-chain address identifying the owner of a locator * @return bool True if the identifier corresponds to an Entry in the list */ function _hasEntry( address identifier ) internal view returns (bool) { return entries[identifier].locator != bytes32(0); } /** * @notice Returns the largest scoring Entry Lower than a Score * @param score uint256 Score in question * @return address Identifier of the largest score lower than score */ function _getEntryLowerThan( uint256 score ) internal view returns (address) { address identifier = entries[HEAD].next; // Head indicates last because the list is circular. if (score == 0) { return HEAD; } // Iterate until a lower score is found. while (score <= entries[identifier].score) { identifier = entries[identifier].next; } return identifier; } } // File: @airswap/indexer/contracts/Indexer.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Indexer: A Collection of Index contracts by Token Pair */ contract Indexer is IIndexer, Ownable { // Token to be used for staking (ERC-20) IERC20 public stakingToken; // Mapping of signer token to sender token to protocol type to index mapping (address => mapping (address => mapping (bytes2 => Index))) public indexes; // The whitelist contract for checking whether a peer is whitelisted per peer type mapping (bytes2 => address) public locatorWhitelists; // Mapping of token address to boolean mapping (address => bool) public tokenBlacklist; /** * @notice Contract Constructor * @param indexerStakingToken address */ constructor( address indexerStakingToken ) public { stakingToken = IERC20(indexerStakingToken); } /** * @notice Modifier to check an index exists */ modifier indexExists(address signerToken, address senderToken, bytes2 protocol) { require(indexes[signerToken][senderToken][protocol] != Index(0), "INDEX_DOES_NOT_EXIST"); _; } /** * @notice Set the address of an ILocatorWhitelist to use * @dev Allows removal of locatorWhitelist by passing 0x0 * @param protocol bytes2 Protocol type for locators * @param newLocatorWhitelist address Locator whitelist */ function setLocatorWhitelist( bytes2 protocol, address newLocatorWhitelist ) external onlyOwner { locatorWhitelists[protocol] = newLocatorWhitelist; } /** * @notice Create an Index (List of Locators for a Token Pair) * @dev Deploys a new Index contract and stores the address. If the Index already * @dev exists, returns its address, and does not emit a CreateIndex event * @param signerToken address Signer token for the Index * @param senderToken address Sender token for the Index * @param protocol bytes2 Protocol type for locators in Index */ function createIndex( address signerToken, address senderToken, bytes2 protocol ) external returns (address) { // If the Index does not exist, create it. if (indexes[signerToken][senderToken][protocol] == Index(0)) { // Create a new Index contract for the token pair. indexes[signerToken][senderToken][protocol] = new Index(); emit CreateIndex(signerToken, senderToken, protocol, address(indexes[signerToken][senderToken][protocol])); } // Return the address of the Index contract. return address(indexes[signerToken][senderToken][protocol]); } /** * @notice Add a Token to the Blacklist * @param token address Token to blacklist */ function addTokenToBlacklist( address token ) external onlyOwner { if (!tokenBlacklist[token]) { tokenBlacklist[token] = true; emit AddTokenToBlacklist(token); } } /** * @notice Remove a Token from the Blacklist * @param token address Token to remove from the blacklist */ function removeTokenFromBlacklist( address token ) external onlyOwner { if (tokenBlacklist[token]) { tokenBlacklist[token] = false; emit RemoveTokenFromBlacklist(token); } } /** * @notice Set an Intent to Trade * @dev Requires approval to transfer staking token for sender * * @param signerToken address Signer token of the Index being staked * @param senderToken address Sender token of the Index being staked * @param protocol bytes2 Protocol type for locator in Intent * @param stakingAmount uint256 Amount being staked * @param locator bytes32 Locator of the staker */ function setIntent( address signerToken, address senderToken, bytes2 protocol, uint256 stakingAmount, bytes32 locator ) external indexExists(signerToken, senderToken, protocol) { // If whitelist set, ensure the locator is valid. if (locatorWhitelists[protocol] != address(0)) { require(ILocatorWhitelist(locatorWhitelists[protocol]).has(locator), "LOCATOR_NOT_WHITELISTED"); } // Ensure neither of the tokens are blacklisted. require(!tokenBlacklist[signerToken] && !tokenBlacklist[senderToken], "PAIR_IS_BLACKLISTED"); bool notPreviouslySet = (indexes[signerToken][senderToken][protocol].getLocator(msg.sender) == bytes32(0)); if (notPreviouslySet) { // Only transfer for staking if stakingAmount is set. if (stakingAmount > 0) { // Transfer the stakingAmount for staking. require(stakingToken.transferFrom(msg.sender, address(this), stakingAmount), "STAKING_FAILED"); } // Set the locator on the index. indexes[signerToken][senderToken][protocol].setLocator(msg.sender, stakingAmount, locator); emit Stake(msg.sender, signerToken, senderToken, protocol, stakingAmount); } else { uint256 oldStake = indexes[signerToken][senderToken][protocol].getScore(msg.sender); _updateIntent(msg.sender, signerToken, senderToken, protocol, stakingAmount, locator, oldStake); } } /** * @notice Unset an Intent to Trade * @dev Users are allowed to unstake from blacklisted indexes * * @param signerToken address Signer token of the Index being unstaked * @param senderToken address Sender token of the Index being staked * @param protocol bytes2 Protocol type for locators in Intent */ function unsetIntent( address signerToken, address senderToken, bytes2 protocol ) external { _unsetIntent(msg.sender, signerToken, senderToken, protocol); } /** * @notice Get the locators of those trading a token pair * @dev Users are allowed to unstake from blacklisted indexes * * @param signerToken address Signer token of the trading pair * @param senderToken address Sender token of the trading pair * @param protocol bytes2 Protocol type for locators in Intent * @param cursor address Address to start from * @param limit uint256 Total number of locators to return * @return bytes32[] List of locators * @return uint256[] List of scores corresponding to locators * @return address The next cursor to provide for pagination */ function getLocators( address signerToken, address senderToken, bytes2 protocol, address cursor, uint256 limit ) external view returns ( bytes32[] memory locators, uint256[] memory scores, address nextCursor ) { // Ensure neither token is blacklisted. if (tokenBlacklist[signerToken] || tokenBlacklist[senderToken]) { return (new bytes32[](0), new uint256[](0), address(0)); } // Ensure the index exists. if (indexes[signerToken][senderToken][protocol] == Index(0)) { return (new bytes32[](0), new uint256[](0), address(0)); } return indexes[signerToken][senderToken][protocol].getLocators(cursor, limit); } /** * @notice Gets the Stake Amount for a User * @param user address User who staked * @param signerToken address Signer token the user staked on * @param senderToken address Sender token the user staked on * @param protocol bytes2 Protocol type for locators in Intent * @return uint256 Amount the user staked */ function getStakedAmount( address user, address signerToken, address senderToken, bytes2 protocol ) public view returns (uint256 stakedAmount) { if (indexes[signerToken][senderToken][protocol] == Index(0)) { return 0; } // Return the score, equivalent to the stake amount. return indexes[signerToken][senderToken][protocol].getScore(user); } function _updateIntent( address user, address signerToken, address senderToken, bytes2 protocol, uint256 newAmount, bytes32 newLocator, uint256 oldAmount ) internal { // If the new stake is bigger, collect the difference. if (oldAmount < newAmount) { // Note: SafeMath not required due to the inequality check above require(stakingToken.transferFrom(user, address(this), newAmount - oldAmount), "STAKING_FAILED"); } // If the old stake is bigger, return the excess. if (newAmount < oldAmount) { // Note: SafeMath not required due to the inequality check above require(stakingToken.transfer(user, oldAmount - newAmount)); } // Update their intent. indexes[signerToken][senderToken][protocol].updateLocator(user, newAmount, newLocator); emit Stake(user, signerToken, senderToken, protocol, newAmount); } /** * @notice Unset intents and return staked tokens * @param user address Address of the user who staked * @param signerToken address Signer token of the trading pair * @param senderToken address Sender token of the trading pair * @param protocol bytes2 Protocol type for locators in Intent */ function _unsetIntent( address user, address signerToken, address senderToken, bytes2 protocol ) internal indexExists(signerToken, senderToken, protocol) { // Get the score for the user. uint256 score = indexes[signerToken][senderToken][protocol].getScore(user); // Unset the locator on the index. indexes[signerToken][senderToken][protocol].unsetLocator(user); if (score > 0) { // Return the staked tokens. Reverts on failure. require(stakingToken.transfer(user, score)); } emit Unstake(user, signerToken, senderToken, protocol, score); } } // File: @airswap/swap/contracts/Swap.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Swap: The Atomic Swap used on the AirSwap Network */ contract Swap is ISwap { // Domain and version for use in signatures (EIP-712) bytes constant internal DOMAIN_NAME = "SWAP"; bytes constant internal DOMAIN_VERSION = "2"; // Unique domain identifier for use in signatures (EIP-712) bytes32 private _domainSeparator; // Possible nonce statuses byte constant internal AVAILABLE = 0x00; byte constant internal UNAVAILABLE = 0x01; // Mapping of sender address to a delegated sender address and bool mapping (address => mapping (address => bool)) public senderAuthorizations; // Mapping of signer address to a delegated signer and bool mapping (address => mapping (address => bool)) public signerAuthorizations; // Mapping of signers to nonces with value AVAILABLE (0x00) or UNAVAILABLE (0x01) mapping (address => mapping (uint256 => byte)) public signerNonceStatus; // Mapping of signer addresses to an optionally set minimum valid nonce mapping (address => uint256) public signerMinimumNonce; // A registry storing a transfer handler for different token kinds TransferHandlerRegistry public registry; /** * @notice Contract Constructor * @dev Sets domain for signature validation (EIP-712) * @param swapRegistry TransferHandlerRegistry */ constructor(TransferHandlerRegistry swapRegistry) public { _domainSeparator = Types.hashDomain( DOMAIN_NAME, DOMAIN_VERSION, address(this) ); registry = swapRegistry; } /** * @notice Atomic Token Swap * @param order Types.Order Order to settle */ function swap( Types.Order calldata order ) external { // Ensure the order is not expired. require(order.expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the nonce is AVAILABLE (0x00). require(signerNonceStatus[order.signer.wallet][order.nonce] == AVAILABLE, "ORDER_TAKEN_OR_CANCELLED"); // Ensure the order nonce is above the minimum. require(order.nonce >= signerMinimumNonce[order.signer.wallet], "NONCE_TOO_LOW"); // Mark the nonce UNAVAILABLE (0x01). signerNonceStatus[order.signer.wallet][order.nonce] = UNAVAILABLE; // Validate the sender side of the trade. address finalSenderWallet; if (order.sender.wallet == address(0)) { /** * Sender is not specified. The msg.sender of the transaction becomes * the sender of the order. */ finalSenderWallet = msg.sender; } else { /** * Sender is specified. If the msg.sender is not the specified sender, * this determines whether the msg.sender is an authorized sender. */ require(isSenderAuthorized(order.sender.wallet, msg.sender), "SENDER_UNAUTHORIZED"); // The msg.sender is authorized. finalSenderWallet = order.sender.wallet; } // Validate the signer side of the trade. if (order.signature.v == 0) { /** * Signature is not provided. The signer may have authorized the * msg.sender to swap on its behalf, which does not require a signature. */ require(isSignerAuthorized(order.signer.wallet, msg.sender), "SIGNER_UNAUTHORIZED"); } else { /** * The signature is provided. Determine whether the signer is * authorized and if so validate the signature itself. */ require(isSignerAuthorized(order.signer.wallet, order.signature.signatory), "SIGNER_UNAUTHORIZED"); // Ensure the signature is valid. require(isValid(order, _domainSeparator), "SIGNATURE_INVALID"); } // Transfer token from sender to signer. transferToken( finalSenderWallet, order.signer.wallet, order.sender.amount, order.sender.id, order.sender.token, order.sender.kind ); // Transfer token from signer to sender. transferToken( order.signer.wallet, finalSenderWallet, order.signer.amount, order.signer.id, order.signer.token, order.signer.kind ); // Transfer token from signer to affiliate if specified. if (order.affiliate.token != address(0)) { transferToken( order.signer.wallet, order.affiliate.wallet, order.affiliate.amount, order.affiliate.id, order.affiliate.token, order.affiliate.kind ); } emit Swap( order.nonce, block.timestamp, order.signer.wallet, order.signer.amount, order.signer.id, order.signer.token, finalSenderWallet, order.sender.amount, order.sender.id, order.sender.token, order.affiliate.wallet, order.affiliate.amount, order.affiliate.id, order.affiliate.token ); } /** * @notice Cancel one or more open orders by nonce * @dev Cancelled nonces are marked UNAVAILABLE (0x01) * @dev Emits a Cancel event * @dev Out of gas may occur in arrays of length > 400 * @param nonces uint256[] List of nonces to cancel */ function cancel( uint256[] calldata nonces ) external { for (uint256 i = 0; i < nonces.length; i++) { if (signerNonceStatus[msg.sender][nonces[i]] == AVAILABLE) { signerNonceStatus[msg.sender][nonces[i]] = UNAVAILABLE; emit Cancel(nonces[i], msg.sender); } } } /** * @notice Cancels all orders below a nonce value * @dev Emits a CancelUpTo event * @param minimumNonce uint256 Minimum valid nonce */ function cancelUpTo( uint256 minimumNonce ) external { signerMinimumNonce[msg.sender] = minimumNonce; emit CancelUpTo(minimumNonce, msg.sender); } /** * @notice Authorize a delegated sender * @dev Emits an AuthorizeSender event * @param authorizedSender address Address to authorize */ function authorizeSender( address authorizedSender ) external { require(msg.sender != authorizedSender, "SELF_AUTH_INVALID"); if (!senderAuthorizations[msg.sender][authorizedSender]) { senderAuthorizations[msg.sender][authorizedSender] = true; emit AuthorizeSender(msg.sender, authorizedSender); } } /** * @notice Authorize a delegated signer * @dev Emits an AuthorizeSigner event * @param authorizedSigner address Address to authorize */ function authorizeSigner( address authorizedSigner ) external { require(msg.sender != authorizedSigner, "SELF_AUTH_INVALID"); if (!signerAuthorizations[msg.sender][authorizedSigner]) { signerAuthorizations[msg.sender][authorizedSigner] = true; emit AuthorizeSigner(msg.sender, authorizedSigner); } } /** * @notice Revoke an authorized sender * @dev Emits a RevokeSender event * @param authorizedSender address Address to revoke */ function revokeSender( address authorizedSender ) external { if (senderAuthorizations[msg.sender][authorizedSender]) { delete senderAuthorizations[msg.sender][authorizedSender]; emit RevokeSender(msg.sender, authorizedSender); } } /** * @notice Revoke an authorized signer * @dev Emits a RevokeSigner event * @param authorizedSigner address Address to revoke */ function revokeSigner( address authorizedSigner ) external { if (signerAuthorizations[msg.sender][authorizedSigner]) { delete signerAuthorizations[msg.sender][authorizedSigner]; emit RevokeSigner(msg.sender, authorizedSigner); } } /** * @notice Determine whether a sender delegate is authorized * @param authorizer address Address doing the authorization * @param delegate address Address being authorized * @return bool True if a delegate is authorized to send */ function isSenderAuthorized( address authorizer, address delegate ) internal view returns (bool) { return ((authorizer == delegate) || senderAuthorizations[authorizer][delegate]); } /** * @notice Determine whether a signer delegate is authorized * @param authorizer address Address doing the authorization * @param delegate address Address being authorized * @return bool True if a delegate is authorized to sign */ function isSignerAuthorized( address authorizer, address delegate ) internal view returns (bool) { return ((authorizer == delegate) || signerAuthorizations[authorizer][delegate]); } /** * @notice Validate signature using an EIP-712 typed data hash * @param order Types.Order Order to validate * @param domainSeparator bytes32 Domain identifier used in signatures (EIP-712) * @return bool True if order has a valid signature */ function isValid( Types.Order memory order, bytes32 domainSeparator ) internal pure returns (bool) { if (order.signature.version == byte(0x01)) { return order.signature.signatory == ecrecover( Types.hashOrder( order, domainSeparator ), order.signature.v, order.signature.r, order.signature.s ); } if (order.signature.version == byte(0x45)) { return order.signature.signatory == ecrecover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", Types.hashOrder(order, domainSeparator) ) ), order.signature.v, order.signature.r, order.signature.s ); } return false; } /** * @notice Perform token transfer for tokens in registry * @dev Transfer type specified by the bytes4 kind param * @dev ERC721: uses transferFrom for transfer * @dev ERC20: Takes into account non-standard ERC-20 tokens. * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256 Amount for ERC-20 * @param id token ID for ERC-721 * @param token address Contract address of token * @param kind bytes4 EIP-165 interface ID of the token */ function transferToken( address from, address to, uint256 amount, uint256 id, address token, bytes4 kind ) internal { // Ensure the transfer is not to self. require(from != to, "SELF_TRANSFER_INVALID"); ITransferHandler transferHandler = registry.transferHandlers(kind); require(address(transferHandler) != address(0), "TOKEN_KIND_UNKNOWN"); // delegatecall required to pass msg.sender as Swap contract to handle the // token transfer in the calling contract (bool success, bytes memory data) = address(transferHandler). delegatecall(abi.encodeWithSelector( transferHandler.transferTokens.selector, from, to, amount, id, token )); require(success && abi.decode(data, (bool)), "TRANSFER_FAILED"); } } // File: @airswap/tokens/contracts/interfaces/IWETH.sol interface IWETH { function deposit() external payable; function withdraw(uint256) external; function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @airswap/wrapper/contracts/Wrapper.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title Wrapper: Send and receive ether for WETH trades */ contract Wrapper { // The Swap contract to settle trades ISwap public swapContract; // The WETH contract to wrap ether IWETH public wethContract; /** * @notice Contract Constructor * @param wrapperSwapContract address * @param wrapperWethContract address */ constructor( address wrapperSwapContract, address wrapperWethContract ) public { swapContract = ISwap(wrapperSwapContract); wethContract = IWETH(wrapperWethContract); } /** * @notice Required when withdrawing from WETH * @dev During unwraps, WETH.withdraw transfers ether to msg.sender (this contract) */ function() external payable { // Ensure the message sender is the WETH contract. if(msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } /** * @notice Send an Order to be forwarded to Swap * @dev Sender must authorize this contract on the swapContract * @dev Sender must approve this contract on the wethContract * @param order Types.Order The Order */ function swap( Types.Order calldata order ) external payable { // Ensure msg.sender is sender wallet. require(order.sender.wallet == msg.sender, "MSG_SENDER_MUST_BE_ORDER_SENDER"); // Ensure that the signature is present. // The signature will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Wraps ETH to WETH when the sender provides ETH and the order is WETH _wrapEther(order.sender); // Perform the swap. swapContract.swap(order); // Unwraps WETH to ETH when the sender receives WETH _unwrapEther(order.sender.wallet, order.signer.token, order.signer.amount); } /** * @notice Send an Order to be forwarded to a Delegate * @dev Sender must authorize the Delegate contract on the swapContract * @dev Sender must approve this contract on the wethContract * @dev Delegate's tradeWallet must be order.sender - checked in Delegate * @param order Types.Order The Order * @param delegate IDelegate The Delegate to provide the order to */ function provideDelegateOrder( Types.Order calldata order, IDelegate delegate ) external payable { // Ensure that the signature is present. // The signature will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Wraps ETH to WETH when the signer provides ETH and the order is WETH _wrapEther(order.signer); // Provide the order to the Delegate. delegate.provideOrder(order); // Unwraps WETH to ETH when the signer receives WETH _unwrapEther(order.signer.wallet, order.sender.token, order.sender.amount); } /** * @notice Wraps ETH to WETH when a trade requires it * @param party Types.Party The side of the trade that may need wrapping */ function _wrapEther(Types.Party memory party) internal { // Check whether ether needs wrapping if (party.token == address(wethContract)) { // Ensure message value is param. require(party.amount == msg.value, "VALUE_MUST_BE_SENT"); // Wrap (deposit) the ether. wethContract.deposit.value(msg.value)(); // Transfer the WETH from the wrapper to party. // Return value not checked - WETH throws on error and does not return false wethContract.transfer(party.wallet, party.amount); } else { // Ensure no unexpected ether is sent. require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } } /** * @notice Unwraps WETH to ETH when a trade requires it * @dev The unwrapping only succeeds if recipientWallet has approved transferFrom * @param recipientWallet address The trade recipient, who may have received WETH * @param receivingToken address The token address the recipient received * @param amount uint256 The amount of token the recipient received */ function _unwrapEther(address recipientWallet, address receivingToken, uint256 amount) internal { // Check whether ether needs unwrapping if (receivingToken == address(wethContract)) { // Transfer weth from the recipient to the wrapper. wethContract.transferFrom(recipientWallet, address(this), amount); // Unwrap (withdraw) the ether. wethContract.withdraw(amount); // Transfer ether to the recipient. // solium-disable-next-line security/no-call-value (bool success, ) = recipientWallet.call.value(amount)(""); require(success, "ETH_RETURN_FAILED"); } } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol /** * @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: @airswap/tokens/contracts/interfaces/IERC1155.sol /** * * Copied from OpenZeppelin ERC1155 feature branch from (20642cca30fa18fb167df6db1889b558742d189a) * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feature-erc1155/contracts/token/ERC1155/ERC1155.sol */ /** @title ERC-1155 Multi Token Standard basic interface @dev See https://eips.ethereum.org/EIPS/eip-1155 */ contract IERC1155 is IERC165 { event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); event ApprovalForAll(address indexed account, address indexed operator, bool approved); event URI(string value, uint256 indexed id); function balanceOf(address account, uint256 id) public view returns (uint256); function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view returns (uint256[] memory); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll(address account, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external; function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data) external; } // File: @airswap/transfers/contracts/handlers/ERC1155TransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ contract ERC1155TransferHandler is ITransferHandler { /** * @notice Function to wrap safeTransferFrom for ERC1155 * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256 Amount for ERC-1155 * @param id uint256 token ID for ERC-1155 * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token ) external returns (bool) { IERC1155(token).safeTransferFrom( from, to, id, amount, "" // bytes are empty ); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol /** * @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-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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: @airswap/transfers/contracts/handlers/ERC20TransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ contract ERC20TransferHandler is ITransferHandler { using SafeERC20 for IERC20; /** * @notice Function to wrap safeTransferFrom for ERC20 * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256 Amount for ERC-20 * @param id uint256 ID, must be 0 for this contract * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token ) external returns (bool) { require(id == 0, "ID_INVALID"); IERC20(token).safeTransferFrom(from, to, amount); return true; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol /** * @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; } // File: @airswap/transfers/contracts/handlers/ERC721TransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ contract ERC721TransferHandler is ITransferHandler { /** * @notice Function to wrap safeTransferFrom for ERC721 * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256, must be 0 for this contract * @param id uint256 ID for ERC721 * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token) external returns (bool) { require(amount == 0, "AMOUNT_INVALID"); IERC721(token).safeTransferFrom(from, to, id); return true; } } // File: @airswap/transfers/contracts/interfaces/IKittyCoreTokenTransfer.sol /* Copyright 2020 Swap Holdings 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. */ /** * @title IKittyCoreTokenTransfer * @dev transferFrom function from KittyCore */ contract IKittyCoreTokenTransfer { function transferFrom(address from, address to, uint256 tokenId) external; } // File: @airswap/transfers/contracts/handlers/KittyCoreTransferHandler.sol /* Copyright 2020 Swap Holdings 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. */ contract KittyCoreTransferHandler is ITransferHandler { /** * @notice Function to wrap transferFrom for CKitty * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256, must be 0 for this contract * @param id uint256 ID for ERC721 * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token ) external returns (bool) { require(amount == 0, "AMOUNT_INVALID"); IKittyCoreTokenTransfer(token).transferFrom(from, to, id); return true; } } // File: contracts/Imports.sol //Import all the contracts desired to be deployed contract Imports {}
Determine whether a sender delegate is authorized authorizer address Address doing the authorization delegate address Address being authorized return bool True if a delegate is authorized to send/
function isSenderAuthorized( address authorizer, address delegate ) internal view returns (bool) { return ((authorizer == delegate) || senderAuthorizations[authorizer][delegate]); }
12,682,695
./full_match/1/0x4f4883ecAF658018024446E65bf51f68996F0296/sources/contracts/MarryStrgtVault.sol
Harvests the yield Can only be called by the executor swapper Address of the Swapper amountOutMin Minimum amount of underlying tokens received data Data to be passed for the swapper
function harvest( address swapper, uint256 amountOutMin, bytes calldata data ) public { if (executors[msg.sender] != true) revert MarryStrgtVault__NotExecutor(); if (lastHarvestBlock == block.number) revert MarryStrgtVault__HarvestAtSameBlock(); uint256 baseAssetBalanceBefore = asset.balanceOf(address(this)); strgtStaking.deposit(pid, 0); uint256 rewardTokenBalance = rewardToken.balanceOf(address(this)); rewardToken.safeTransfer(swapper, rewardTokenBalance); ISwapper(swapper).onSwapReceived(data); uint256 underlyingAssetBalance = underlyingAsset.balanceOf( address(this) ); if (underlyingAssetBalance < amountOutMin) revert MarryStrgtVault__InsufficientOut(); strgtRouter.addLiquidity( poolId, underlyingAssetBalance, address(this) ); uint256 baseAssetBalance = asset.balanceOf(address(this)) - baseAssetBalanceBefore; uint256 totalFee = baseAssetBalance.mulDivDown(fee, 1e18); asset.safeTransfer(feeTo, totalFee); strgtStaking.deposit(pid, baseAssetBalance - totalFee); totalLockedProfit = baseAssetBalance - totalFee; totalBaseAssets += baseAssetBalance - totalFee; lastHarvestBlock = block.number; emit LogFeeClaimed(feeTo, totalFee); emit LogHarvested(baseAssetBalance); }
17,066,389
pragma solidity ^0.5.0; contract overledgerSCDemo { bool testBool; int testInt; uint16 testUint; bytes32 testBytes; address testAddress; string testString; bool[] testArray; /// Create a new smart contract and initialise the test variables constructor(bool thisTestBool, int256 thisTestInt, uint16 thisTestUint, bytes32 thisTestBytes,address thisTestAddress,string memory thisTestString,bool[] memory thisTestArray) public { testBool = thisTestBool; testInt = thisTestInt; testUint = thisTestUint; testBytes = thisTestBytes; testAddress = thisTestAddress; testString = thisTestString; testArray = thisTestArray; } //the following functions change the state of the distributed ledger function setOVLTestBool(bool newBool) external { testBool = newBool; } function setOVLTestInt(int newInt) external { testInt = newInt; } function setOVLTestUint(uint16 newUint) external { testUint = newUint; } function setOVLTestBytes(bytes6 newBytes) external { testBytes = newBytes; } function setOVLTestAddress(address newAddress) external { testAddress = newAddress; } function setOVLTestString(string calldata newString) external { testString = newString; } function setOVLTestArray(bool[] calldata newArray) external { testArray = newArray; } //the following functions read the state of the distributed ledger function getOVLTestBool() external view returns(bool){ return testBool; } function getOVLTestInt() external view returns(int){ return testInt; } function getOVLTestUint() external view returns(uint16){ return testUint; } function getOVLTestBytes() external view returns(bytes32){ return testBytes; } function getOVLTestAddress() external view returns(address){ return testAddress; } function getTestString() external view returns(string memory){ return testString; } function getTestArray(uint index) external view returns(bool){ return testArray[index]; } }
the following functions change the state of the distributed ledger
function setOVLTestBool(bool newBool) external { testBool = newBool; }
7,303,121
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { 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.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; /* * @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; } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./RoleAware.sol"; import "./Fund.sol"; import "./CrossMarginTrading.sol"; import "../libraries/IncentiveReporter.sol"; /** @title Here we support staking for MFI incentives as well as staking to perform the maintenance role. */ contract Admin is RoleAware { /// Margenswap (MFI) token address address public immutable MFI; mapping(address => uint256) public stakes; uint256 public totalStakes; uint256 public constant mfiStakeTranche = 1; uint256 public maintenanceStakePerBlock = 15 ether; mapping(address => address) public nextMaintenanceStaker; mapping(address => mapping(address => bool)) public maintenanceDelegateTo; address public currentMaintenanceStaker; address public prevMaintenanceStaker; uint256 public currentMaintenanceStakerStartBlock; address public immutable lockedMFI; constructor( address _MFI, address _lockedMFI, address lockedMFIDelegate, address _roles ) RoleAware(_roles) { MFI = _MFI; lockedMFI = _lockedMFI; // for initialization purposes and to ensure availability of service // the team's locked MFI participate in maintenance staking only // (not in the incentive staking part) // this implies some trust of the team to execute, which we deem reasonable // since the locked stake is temporary and diminishing as well as the fact // that the team is heavily invested in the protocol and incentivized // by fees like any other maintainer // furthermore others could step in to liquidate via the attacker route // and take away the team fees if they were delinquent nextMaintenanceStaker[_lockedMFI] = _lockedMFI; currentMaintenanceStaker = _lockedMFI; prevMaintenanceStaker = _lockedMFI; maintenanceDelegateTo[_lockedMFI][lockedMFIDelegate]; currentMaintenanceStakerStartBlock = block.number; } /// Maintence stake setter function setMaintenanceStakePerBlock(uint256 amount) external onlyOwnerExec { maintenanceStakePerBlock = amount; } function _stake(address holder, uint256 amount) internal { Fund(fund()).depositFor(holder, MFI, amount); stakes[holder] += amount; totalStakes += amount; IncentiveReporter.addToClaimAmount(MFI, holder, amount); } /// Deposit a stake for sender function depositStake(uint256 amount) external { _stake(msg.sender, amount); } function _withdrawStake( address holder, uint256 amount, address recipient ) internal { // overflow failure desirable stakes[holder] -= amount; totalStakes -= amount; Fund(fund()).withdraw(MFI, recipient, amount); IncentiveReporter.subtractFromClaimAmount(MFI, holder, amount); } /// Withdraw stake for sender function withdrawStake(uint256 amount) external { require( !isAuthorizedStaker(msg.sender), "You can't withdraw while you're authorized staker" ); _withdrawStake(msg.sender, amount, msg.sender); } /// Deposit maintenance stake function depositMaintenanceStake(uint256 amount) external { require( amount + stakes[msg.sender] >= maintenanceStakePerBlock, "Insufficient stake to call even one block" ); _stake(msg.sender, amount); if (nextMaintenanceStaker[msg.sender] == address(0)) { nextMaintenanceStaker[msg.sender] = getUpdatedCurrentStaker(); nextMaintenanceStaker[prevMaintenanceStaker] = msg.sender; } } function getMaintenanceStakerStake(address staker) public view returns (uint256) { if (staker == lockedMFI) { return IERC20(MFI).balanceOf(lockedMFI) / 2; } else { return stakes[staker]; } } function getUpdatedCurrentStaker() public returns (address) { uint256 currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if ( (block.number - currentMaintenanceStakerStartBlock) * maintenanceStakePerBlock >= currentStake ) { currentMaintenanceStakerStartBlock = block.number; prevMaintenanceStaker = currentMaintenanceStaker; currentMaintenanceStaker = nextMaintenanceStaker[ currentMaintenanceStaker ]; currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if (maintenanceStakePerBlock > currentStake) { // delete current from daisy chain address nextOne = nextMaintenanceStaker[currentMaintenanceStaker]; nextMaintenanceStaker[prevMaintenanceStaker] = nextOne; nextMaintenanceStaker[currentMaintenanceStaker] = address(0); currentMaintenanceStaker = nextOne; currentStake = getMaintenanceStakerStake( currentMaintenanceStaker ); } } return currentMaintenanceStaker; } function viewCurrentMaintenanceStaker() public view returns (address staker, uint256 startBlock) { staker = currentMaintenanceStaker; uint256 currentStake = getMaintenanceStakerStake(staker); startBlock = currentMaintenanceStakerStartBlock; if ( (block.number - startBlock) * maintenanceStakePerBlock >= currentStake ) { staker = nextMaintenanceStaker[staker]; currentStake = getMaintenanceStakerStake(staker); startBlock = block.number; if (maintenanceStakePerBlock > currentStake) { staker = nextMaintenanceStaker[staker]; } } } /// Add a delegate for staker function addDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = true; } /// Remove a delegate for staker function removeDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = false; } function isAuthorizedStaker(address caller) public returns (bool isAuthorized) { address currentStaker = getUpdatedCurrentStaker(); isAuthorized = currentStaker == caller || maintenanceDelegateTo[currentStaker][caller]; } /// Penalize a staker function penalizeMaintenanceStake( address maintainer, uint256 penalty, address recipient ) external returns (uint256 stakeTaken) { require( isStakePenalizer(msg.sender), "msg.sender not authorized to penalize stakers" ); if (penalty > stakes[maintainer]) { stakeTaken = stakes[maintainer]; } else { stakeTaken = penalty; } _withdrawStake(maintainer, stakeTaken, recipient); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; /// @title Base lending behavior abstract contract BaseLending { uint256 constant FP48 = 2**48; uint256 constant ACCUMULATOR_INIT = 10**18; uint256 constant hoursPerYear = 365 days / (1 hours); uint256 constant CHANGE_POINT = 79; uint256 public normalRatePerPercent = (FP48 * 15) / hoursPerYear / CHANGE_POINT / 100; uint256 public highRatePerPercent = (FP48 * (194 - 15)) / hoursPerYear / (100 - CHANGE_POINT) / 100; struct YieldAccumulator { uint256 accumulatorFP; uint256 lastUpdated; uint256 hourlyYieldFP; } struct LendingMetadata { uint256 totalLending; uint256 totalBorrowed; uint256 lendingCap; } mapping(address => LendingMetadata) public lendingMeta; /// @dev accumulate interest per issuer (like compound indices) mapping(address => YieldAccumulator) public borrowYieldAccumulators; /// @dev simple formula for calculating interest relative to accumulator function applyInterest( uint256 balance, uint256 accumulatorFP, uint256 yieldQuotientFP ) internal pure returns (uint256) { // 1 * FP / FP = 1 return (balance * accumulatorFP) / yieldQuotientFP; } function currentLendingRateFP(uint256 totalLending, uint256 totalBorrowing) internal view returns (uint256 rate) { rate = FP48; uint256 utilizationPercent = (100 * totalBorrowing) / totalLending; if (utilizationPercent < CHANGE_POINT) { rate += utilizationPercent * normalRatePerPercent; } else { rate += CHANGE_POINT * normalRatePerPercent + (utilizationPercent - CHANGE_POINT) * highRatePerPercent; } } /// @dev minimum function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return b; } else { return a; } } /// @dev maximum function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a; } else { return b; } } /// Available tokens to this issuance function issuanceBalance(address issuance) internal view virtual returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Fund.sol"; import "../libraries/UniswapStyleLib.sol"; abstract contract BaseRouter { modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "Trade has expired"); _; } // **** SWAP **** /// @dev requires the initial amount to have already been sent to the first pair /// and for pairs to be vetted (which getAmountsIn / getAmountsOut do) function _swap( uint256[] memory amounts, address[] memory pairs, address[] memory tokens, address _to ) internal { for (uint256 i; i < pairs.length; i++) { (address input, address output) = (tokens[i], tokens[i + 1]); (address token0, ) = UniswapStyleLib.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < pairs.length - 1 ? pairs[i + 1] : _to; IUniswapV2Pair pair = IUniswapV2Pair(pairs[i]); pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Fund.sol"; import "./Lending.sol"; import "./RoleAware.sol"; import "./PriceAware.sol"; // Goal: all external functions only accessible to margintrader role // except for view functions of course struct CrossMarginAccount { uint256 lastDepositBlock; address[] borrowTokens; // borrowed token address => amount mapping(address => uint256) borrowed; // borrowed token => yield quotient mapping(address => uint256) borrowedYieldQuotientsFP; address[] holdingTokens; // token held in portfolio => amount mapping(address => uint256) holdings; // boolean value of whether an account holds a token mapping(address => bool) holdsToken; } abstract contract CrossMarginAccounts is RoleAware, PriceAware { /// @dev gets used in calculating how much accounts can borrow uint256 public leveragePercent = 300; /// @dev percentage of assets held per assets borrowed at which to liquidate uint256 public liquidationThresholdPercent = 115; /// @dev record of all cross margin accounts mapping(address => CrossMarginAccount) internal marginAccounts; /// @dev total token caps mapping(address => uint256) public tokenCaps; /// @dev tracks total of short positions per token mapping(address => uint256) public totalShort; /// @dev tracks total of long positions per token mapping(address => uint256) public totalLong; uint256 public coolingOffPeriod = 10; /// @dev add an asset to be held by account function addHolding( CrossMarginAccount storage account, address token, uint256 depositAmount ) internal { if (!hasHoldingToken(account, token)) { account.holdingTokens.push(token); account.holdsToken[token] = true; } account.holdings[token] += depositAmount; } /// @dev adjust account to reflect borrowing of token amount function borrow( CrossMarginAccount storage account, address borrowToken, uint256 borrowAmount ) internal { if (!hasBorrowedToken(account, borrowToken)) { account.borrowTokens.push(borrowToken); account.borrowedYieldQuotientsFP[borrowToken] = Lending(lending()) .getUpdatedBorrowYieldAccuFP(borrowToken); account.borrowed[borrowToken] = borrowAmount; } else { (uint256 oldBorrowed, uint256 accumulatorFP) = Lending(lending()).applyBorrowInterest( account.borrowed[borrowToken], borrowToken, account.borrowedYieldQuotientsFP[borrowToken] ); account.borrowedYieldQuotientsFP[borrowToken] = accumulatorFP; account.borrowed[borrowToken] = oldBorrowed + borrowAmount; } require(positiveBalance(account), "Insufficient balance"); } /// @dev checks whether account is in the black, deposit + earnings relative to borrowed function positiveBalance(CrossMarginAccount storage account) internal returns (bool) { uint256 loan = loanInPeg(account); uint256 holdings = holdingsInPeg(account); // The following condition should hold: // holdings / loan >= leveragePercent / (leveragePercent - 100) // => return holdings * (leveragePercent - 100) >= loan * leveragePercent; } /// @dev internal function adjusting holding and borrow balances when debt extinguished function extinguishDebt( CrossMarginAccount storage account, address debtToken, uint256 extinguishAmount ) internal { // will throw if insufficient funds (uint256 borrowAmount, uint256 newYieldQuot) = Lending(lending()).applyBorrowInterest( account.borrowed[debtToken], debtToken, account.borrowedYieldQuotientsFP[debtToken] ); uint256 newBorrowAmount = borrowAmount - extinguishAmount; account.borrowed[debtToken] = newBorrowAmount; if (newBorrowAmount > 0) { account.borrowedYieldQuotientsFP[debtToken] = newYieldQuot; } else { delete account.borrowedYieldQuotientsFP[debtToken]; bool decrement = false; uint256 len = account.borrowTokens.length; for (uint256 i; len > i; i++) { address currToken = account.borrowTokens[i]; if (currToken == debtToken) { decrement = true; } else if (decrement) { account.borrowTokens[i - 1] = currToken; } } account.borrowTokens.pop(); } } /// @dev checks whether an account holds a token function hasHoldingToken(CrossMarginAccount storage account, address token) internal view returns (bool) { return account.holdsToken[token]; } /// @dev checks whether an account has borrowed a token function hasBorrowedToken(CrossMarginAccount storage account, address token) internal view returns (bool) { return account.borrowedYieldQuotientsFP[token] > 0; } /// @dev calculate total loan in reference currency, including compound interest function loanInPeg(CrossMarginAccount storage account) internal returns (uint256) { return sumTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); } /// @dev total of assets of account, expressed in reference currency function holdingsInPeg(CrossMarginAccount storage account) internal returns (uint256) { return sumTokensInPeg(account.holdingTokens, account.holdings); } /// @dev check whether an account can/should be liquidated function belowMaintenanceThreshold(CrossMarginAccount storage account) internal returns (bool) { uint256 loan = loanInPeg(account); uint256 holdings = holdingsInPeg(account); // The following should hold: // holdings / loan >= 1.1 // => holdings >= loan * 1.1 return 100 * holdings < liquidationThresholdPercent * loan; } /// @dev go through list of tokens and their amounts, summing up function sumTokensInPeg( address[] storage tokens, mapping(address => uint256) storage amounts ) internal returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += PriceAware.getCurrentPriceInPeg(token, amounts[token]); } } /// @dev go through list of tokens and their amounts, summing up function viewTokensInPeg( address[] storage tokens, mapping(address => uint256) storage amounts ) internal view returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += PriceAware.viewCurrentPriceInPeg(token, amounts[token]); } } /// @dev go through list of tokens and ammounts, summing up with interest function sumTokensInPegWithYield( address[] storage tokens, mapping(address => uint256) storage amounts, mapping(address => uint256) storage yieldQuotientsFP ) internal returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += yieldTokenInPeg( token, amounts[token], yieldQuotientsFP ); } } /// @dev go through list of tokens and ammounts, summing up with interest function viewTokensInPegWithYield( address[] storage tokens, mapping(address => uint256) storage amounts, mapping(address => uint256) storage yieldQuotientsFP ) internal view returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += viewYieldTokenInPeg( token, amounts[token], yieldQuotientsFP ); } } /// @dev calculate yield for token amount and convert to reference currency function yieldTokenInPeg( address token, uint256 amount, mapping(address => uint256) storage yieldQuotientsFP ) internal returns (uint256) { uint256 yieldFP = Lending(lending()).viewAccumulatedBorrowingYieldFP(token); // 1 * FP / FP = 1 uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token]; return PriceAware.getCurrentPriceInPeg(token, amountInToken); } /// @dev calculate yield for token amount and convert to reference currency function viewYieldTokenInPeg( address token, uint256 amount, mapping(address => uint256) storage yieldQuotientsFP ) internal view returns (uint256) { uint256 yieldFP = Lending(lending()).viewAccumulatedBorrowingYieldFP(token); // 1 * FP / FP = 1 uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token]; return PriceAware.viewCurrentPriceInPeg(token, amountInToken); } /// @dev move tokens from one holding to another function adjustAmounts( CrossMarginAccount storage account, address fromToken, address toToken, uint256 soldAmount, uint256 boughtAmount ) internal { account.holdings[fromToken] = account.holdings[fromToken] - soldAmount; addHolding(account, toToken, boughtAmount); } /// sets borrow and holding to zero function deleteAccount(CrossMarginAccount storage account) internal { uint256 len = account.borrowTokens.length; for (uint256 borrowIdx; len > borrowIdx; borrowIdx++) { address borrowToken = account.borrowTokens[borrowIdx]; totalShort[borrowToken] -= account.borrowed[borrowToken]; account.borrowed[borrowToken] = 0; account.borrowedYieldQuotientsFP[borrowToken] = 0; } len = account.holdingTokens.length; for (uint256 holdingIdx; len > holdingIdx; holdingIdx++) { address holdingToken = account.holdingTokens[holdingIdx]; totalLong[holdingToken] -= account.holdings[holdingToken]; account.holdings[holdingToken] = 0; account.holdsToken[holdingToken] = false; } delete account.borrowTokens; delete account.holdingTokens; } /// @dev minimum function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return b; } else { return a; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./CrossMarginAccounts.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @title Handles liquidation of accounts below maintenance threshold @notice Liquidation can be called by the authorized staker, as determined in the Admin contract. If the authorized staker is delinquent, other participants can jump in and attack, taking their fees and potentially even their stake, depending how delinquent the responsible authorized staker is. */ abstract contract CrossMarginLiquidation is CrossMarginAccounts { event LiquidationShortfall(uint256 amount); event AccountLiquidated(address account); struct Liquidation { uint256 buy; uint256 sell; uint256 blockNum; } /// record kept around until a stake attacker can claim their reward struct AccountLiqRecord { uint256 blockNum; address loser; uint256 amount; address stakeAttacker; } mapping(address => Liquidation) liquidationAmounts; address[] internal liquidationTokens; address[] internal tradersToLiquidate; mapping(address => uint256) public maintenanceFailures; mapping(address => AccountLiqRecord) public stakeAttackRecords; uint256 public avgLiquidationPerCall = 10; uint256 public liqStakeAttackWindow = 5; uint256 public MAINTAINER_CUT_PERCENT = 5; uint256 public failureThreshold = 10; /// Set failure threshold function setFailureThreshold(uint256 threshFactor) external onlyOwnerExec { failureThreshold = threshFactor; } /// Set liquidity stake attack window function setLiqStakeAttackWindow(uint256 window) external onlyOwnerExec { liqStakeAttackWindow = window; } /// Set maintainer's percent cut function setMaintainerCutPercent(uint256 cut) external onlyOwnerExec { MAINTAINER_CUT_PERCENT = cut; } /// @dev calcLiquidationAmounts does a number of tasks in this contract /// and some of them are not straightforward. /// First of all it aggregates liquidation amounts, /// as well as which traders are ripe for liquidation, in storage (not in memory) /// owing to the fact that arrays can't be pushed to and hash maps don't /// exist in memory. /// Then it also returns any stake attack funds if the stake was unsuccessful /// (i.e. current caller is authorized). Also see context below. function calcLiquidationAmounts( address[] memory liquidationCandidates, bool isAuthorized ) internal returns (uint256 attackReturns) { liquidationTokens = new address[](0); tradersToLiquidate = new address[](0); for ( uint256 traderIndex = 0; liquidationCandidates.length > traderIndex; traderIndex++ ) { address traderAddress = liquidationCandidates[traderIndex]; CrossMarginAccount storage account = marginAccounts[traderAddress]; if (belowMaintenanceThreshold(account)) { tradersToLiquidate.push(traderAddress); uint256 len = account.holdingTokens.length; for (uint256 sellIdx = 0; len > sellIdx; sellIdx++) { address token = account.holdingTokens[sellIdx]; Liquidation storage liquidation = liquidationAmounts[token]; if (liquidation.blockNum != block.number) { liquidation.sell = account.holdings[token]; liquidation.buy = 0; liquidation.blockNum = block.number; liquidationTokens.push(token); } else { liquidation.sell += account.holdings[token]; } } len = account.borrowTokens.length; for (uint256 buyIdx = 0; len > buyIdx; buyIdx++) { address token = account.borrowTokens[buyIdx]; Liquidation storage liquidation = liquidationAmounts[token]; (uint256 loanAmount, ) = Lending(lending()).applyBorrowInterest( account.borrowed[token], token, account.borrowedYieldQuotientsFP[token] ); Lending(lending()).payOff(token, loanAmount); if (liquidation.blockNum != block.number) { liquidation.sell = 0; liquidation.buy = loanAmount; liquidation.blockNum = block.number; liquidationTokens.push(token); } else { liquidation.buy += loanAmount; } } } AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[traderAddress]; if (isAuthorized) { attackReturns += _disburseLiqAttack(liqAttackRecord); } } } function _disburseLiqAttack(AccountLiqRecord storage liqAttackRecord) internal returns (uint256 returnAmount) { if (liqAttackRecord.amount > 0) { // validate attack records, if any uint256 blockDiff = min( block.number - liqAttackRecord.blockNum, liqStakeAttackWindow ); uint256 attackerCut = (liqAttackRecord.amount * blockDiff) / liqStakeAttackWindow; Fund(fund()).withdraw( PriceAware.peg, liqAttackRecord.stakeAttacker, attackerCut ); Admin a = Admin(admin()); uint256 penalty = (a.maintenanceStakePerBlock() * attackerCut) / avgLiquidationPerCall; a.penalizeMaintenanceStake( liqAttackRecord.loser, penalty, liqAttackRecord.stakeAttacker ); // return remainder, after cut was taken to authorized stakekr returnAmount = liqAttackRecord.amount - attackerCut; } } /// Disburse liquidity stake attacks function disburseLiqStakeAttacks(address[] memory liquidatedAccounts) external { for (uint256 i = 0; liquidatedAccounts.length > i; i++) { address liqAccount = liquidatedAccounts[i]; AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[liqAccount]; if ( block.number > liqAttackRecord.blockNum + liqStakeAttackWindow ) { _disburseLiqAttack(liqAttackRecord); delete stakeAttackRecords[liqAccount]; } } } function liquidateFromPeg() internal returns (uint256 pegAmount) { uint256 len = liquidationTokens.length; for (uint256 tokenIdx = 0; len > tokenIdx; tokenIdx++) { address buyToken = liquidationTokens[tokenIdx]; Liquidation storage liq = liquidationAmounts[buyToken]; if (liq.buy > liq.sell) { pegAmount += PriceAware.liquidateFromPeg( buyToken, liq.buy - liq.sell ); delete liquidationAmounts[buyToken]; } } } function liquidateToPeg() internal returns (uint256 pegAmount) { uint256 len = liquidationTokens.length; for (uint256 tokenIndex = 0; len > tokenIndex; tokenIndex++) { address token = liquidationTokens[tokenIndex]; Liquidation storage liq = liquidationAmounts[token]; if (liq.sell > liq.buy) { uint256 sellAmount = liq.sell - liq.buy; pegAmount += PriceAware.liquidateToPeg(token, sellAmount); delete liquidationAmounts[token]; } } } function maintainerIsFailing() internal view returns (bool) { (address currentMaintainer, ) = Admin(admin()).viewCurrentMaintenanceStaker(); return maintenanceFailures[currentMaintainer] > failureThreshold * avgLiquidationPerCall; } /// called by maintenance stakers to liquidate accounts below liquidation threshold function liquidate(address[] memory liquidationCandidates) external noIntermediary returns (uint256 maintainerCut) { bool isAuthorized = Admin(admin()).isAuthorizedStaker(msg.sender); bool canTakeNow = isAuthorized || maintainerIsFailing(); // calcLiquidationAmounts does a lot of the work here // * aggregates both sell and buy side targets to be liquidated // * returns attacker cuts to them // * aggregates any returned fees from unauthorized (attacking) attempts maintainerCut = calcLiquidationAmounts( liquidationCandidates, isAuthorized ); uint256 sale2pegAmount = liquidateToPeg(); uint256 peg2targetCost = liquidateFromPeg(); delete liquidationTokens; // this may be a bit imprecise, since individual shortfalls may be obscured // by overall returns and the maintainer cut is taken out of the net total, // but it gives us the general picture uint256 costWithCut = (peg2targetCost * (100 + MAINTAINER_CUT_PERCENT)) / 100; if (costWithCut > sale2pegAmount) { emit LiquidationShortfall(costWithCut - sale2pegAmount); canTakeNow = canTakeNow && IERC20(peg).balanceOf(fund()) > costWithCut; } address loser = address(0); if (!canTakeNow) { // whoever is the current responsible maintenance staker // and liable to lose their stake loser = Admin(admin()).getUpdatedCurrentStaker(); } // iterate over traders and send back their money // as well as giving attackers their due, in case caller isn't authorized for ( uint256 traderIdx = 0; tradersToLiquidate.length > traderIdx; traderIdx++ ) { address traderAddress = tradersToLiquidate[traderIdx]; CrossMarginAccount storage account = marginAccounts[traderAddress]; uint256 holdingsValue = holdingsInPeg(account); uint256 borrowValue = loanInPeg(account); // 5% of value borrowed uint256 maintainerCut4Account = (borrowValue * MAINTAINER_CUT_PERCENT) / 100; maintainerCut += maintainerCut4Account; if (!canTakeNow) { // This could theoretically lead to a previous attackers // record being overwritten, but only if the trader restarts // their account and goes back into the red within the short time window // which would be a costly attack requiring collusion without upside AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[traderAddress]; liqAttackRecord.amount = maintainerCut4Account; liqAttackRecord.stakeAttacker = msg.sender; liqAttackRecord.blockNum = block.number; liqAttackRecord.loser = loser; } // send back trader money // include 1% for protocol uint256 forfeited = maintainerCut4Account + (borrowValue * 101) / 100; if (holdingsValue > forfeited) { // send remaining funds back to trader Fund(fund()).withdraw( PriceAware.peg, traderAddress, holdingsValue - forfeited ); } emit AccountLiquidated(traderAddress); deleteAccount(account); } avgLiquidationPerCall = (avgLiquidationPerCall * 99 + maintainerCut) / 100; if (canTakeNow) { Fund(fund()).withdraw(PriceAware.peg, msg.sender, maintainerCut); } address currentMaintainer = Admin(admin()).getUpdatedCurrentStaker(); if (isAuthorized) { if (maintenanceFailures[currentMaintainer] > maintainerCut) { maintenanceFailures[currentMaintainer] -= maintainerCut; } else { maintenanceFailures[currentMaintainer] = 0; } } else { maintenanceFailures[currentMaintainer] += maintainerCut; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Fund.sol"; import "./Lending.sol"; import "./RoleAware.sol"; import "./CrossMarginLiquidation.sol"; // Goal: all external functions only accessible to margintrader role // except for view functions of course contract CrossMarginTrading is CrossMarginLiquidation, IMarginTrading { constructor(address _peg, address _roles) RoleAware(_roles) PriceAware(_peg) {} /// @dev admin function to set the token cap function setTokenCap(address token, uint256 cap) external onlyOwnerExecActivator { tokenCaps[token] = cap; } /// @dev setter for cooling off period for withdrawing funds after deposit function setCoolingOffPeriod(uint256 blocks) external onlyOwnerExec { coolingOffPeriod = blocks; } /// @dev admin function to set leverage function setLeveragePercent(uint256 _leveragePercent) external onlyOwnerExec { leveragePercent = _leveragePercent; } /// @dev admin function to set liquidation threshold function setLiquidationThresholdPercent(uint256 threshold) external onlyOwnerExec { liquidationThresholdPercent = threshold; } /// @dev gets called by router to affirm a deposit to an account function registerDeposit( address trader, address token, uint256 depositAmount ) external override returns (uint256 extinguishableDebt) { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; account.lastDepositBlock = block.number; if (account.borrowed[token] > 0) { extinguishableDebt = min(depositAmount, account.borrowed[token]); extinguishDebt(account, token, extinguishableDebt); totalShort[token] -= extinguishableDebt; } // no overflow because depositAmount >= extinguishableDebt uint256 addedHolding = depositAmount - extinguishableDebt; _registerDeposit(account, token, addedHolding); } function _registerDeposit( CrossMarginAccount storage account, address token, uint256 addedHolding ) internal { addHolding(account, token, addedHolding); totalLong[token] += addedHolding; require( tokenCaps[token] >= totalLong[token], "Exceeds global token cap" ); } /// @dev gets called by router to affirm borrowing event function registerBorrow( address trader, address borrowToken, uint256 borrowAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; addHolding(account, borrowToken, borrowAmount); _registerBorrow(account, borrowToken, borrowAmount); } function _registerBorrow( CrossMarginAccount storage account, address borrowToken, uint256 borrowAmount ) internal { totalShort[borrowToken] += borrowAmount; totalLong[borrowToken] += borrowAmount; require( tokenCaps[borrowToken] >= totalShort[borrowToken] && tokenCaps[borrowToken] >= totalLong[borrowToken], "Exceeds global token cap" ); borrow(account, borrowToken, borrowAmount); } /// @dev gets called by router to affirm withdrawal of tokens from account function registerWithdrawal( address trader, address withdrawToken, uint256 withdrawAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; _registerWithdrawal(account, withdrawToken, withdrawAmount); } function _registerWithdrawal( CrossMarginAccount storage account, address withdrawToken, uint256 withdrawAmount ) internal { require( block.number > account.lastDepositBlock + coolingOffPeriod, "No withdrawal soon after deposit" ); totalLong[withdrawToken] -= withdrawAmount; // throws on underflow account.holdings[withdrawToken] = account.holdings[withdrawToken] - withdrawAmount; require(positiveBalance(account), "Insufficient balance"); } /// @dev overcollateralized borrowing on a cross margin account, called by router function registerOvercollateralizedBorrow( address trader, address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; _registerDeposit(account, depositToken, depositAmount); _registerBorrow(account, borrowToken, withdrawAmount); _registerWithdrawal(account, borrowToken, withdrawAmount); account.lastDepositBlock = block.number; } /// @dev gets called by router to register a trade and borrow and extinguish as necessary function registerTradeAndBorrow( address trader, address tokenFrom, address tokenTo, uint256 inAmount, uint256 outAmount ) external override returns (uint256 extinguishableDebt, uint256 borrowAmount) { require(isMarginTrader(msg.sender), "Calling contr. not an authorized"); CrossMarginAccount storage account = marginAccounts[trader]; if (account.borrowed[tokenTo] > 0) { extinguishableDebt = min(outAmount, account.borrowed[tokenTo]); extinguishDebt(account, tokenTo, extinguishableDebt); totalShort[tokenTo] -= extinguishableDebt; } uint256 sellAmount = inAmount; uint256 fromHoldings = account.holdings[tokenFrom]; if (inAmount > fromHoldings) { sellAmount = fromHoldings; /// won't overflow borrowAmount = inAmount - sellAmount; } if (inAmount > borrowAmount) { totalLong[tokenFrom] -= inAmount - borrowAmount; } if (outAmount > extinguishableDebt) { totalLong[tokenTo] += outAmount - extinguishableDebt; } require( tokenCaps[tokenTo] >= totalLong[tokenTo], "Exceeds global token cap" ); adjustAmounts( account, tokenFrom, tokenTo, sellAmount, outAmount - extinguishableDebt ); if (borrowAmount > 0) { totalShort[tokenFrom] += borrowAmount; require( tokenCaps[tokenFrom] >= totalShort[tokenFrom], "Exceeds global token cap" ); borrow(account, tokenFrom, borrowAmount); } } /// @dev can get called by router to register the dissolution of an account function registerLiquidation(address trader) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; require(loanInPeg(account) == 0, "Can't liquidate: borrowing"); deleteAccount(account); } /// @dev currently holding in this token function viewBalanceInToken(address trader, address token) external view returns (uint256) { CrossMarginAccount storage account = marginAccounts[trader]; return account.holdings[token]; } /// @dev view function to display account held assets state function getHoldingAmounts(address trader) external view override returns ( address[] memory holdingTokens, uint256[] memory holdingAmounts ) { CrossMarginAccount storage account = marginAccounts[trader]; holdingTokens = account.holdingTokens; holdingAmounts = new uint256[](account.holdingTokens.length); for (uint256 idx = 0; holdingTokens.length > idx; idx++) { address tokenAddress = holdingTokens[idx]; holdingAmounts[idx] = account.holdings[tokenAddress]; } } /// @dev view function to display account borrowing state function getBorrowAmounts(address trader) external view override returns (address[] memory borrowTokens, uint256[] memory borrowAmounts) { CrossMarginAccount storage account = marginAccounts[trader]; borrowTokens = account.borrowTokens; borrowAmounts = new uint256[](account.borrowTokens.length); for (uint256 idx = 0; borrowTokens.length > idx; idx++) { address tokenAddress = borrowTokens[idx]; borrowAmounts[idx] = Lending(lending()).viewWithBorrowInterest( account.borrowed[tokenAddress], tokenAddress, account.borrowedYieldQuotientsFP[tokenAddress] ); } } /// @dev view function to get loan amount in peg function viewLoanInPeg(address trader) external view returns (uint256 amount) { CrossMarginAccount storage account = marginAccounts[trader]; return viewTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); } /// @dev total of assets of account, expressed in reference currency function viewHoldingsInPeg(address trader) external view returns (uint256) { CrossMarginAccount storage account = marginAccounts[trader]; return viewTokensInPeg(account.holdingTokens, account.holdings); } /// @dev can this trader be liquidated? function canBeLiquidated(address trader) external view returns (bool) { CrossMarginAccount storage account = marginAccounts[trader]; uint256 loan = viewTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); uint256 holdings = viewTokensInPeg(account.holdingTokens, account.holdings); return liquidationThresholdPercent * loan >= 100 * holdings; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IWETH.sol"; import "./RoleAware.sol"; /// @title Manage funding contract Fund is RoleAware { using SafeERC20 for IERC20; /// wrapped ether address public immutable WETH; constructor(address _WETH, address _roles) RoleAware(_roles) { WETH = _WETH; } /// Deposit an active token function deposit(address depositToken, uint256 depositAmount) external { IERC20(depositToken).safeTransferFrom( msg.sender, address(this), depositAmount ); } /// Deposit token on behalf of `sender` function depositFor( address sender, address depositToken, uint256 depositAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized deposit"); IERC20(depositToken).safeTransferFrom( sender, address(this), depositAmount ); } /// Deposit to wrapped ether function depositToWETH() external payable { IWETH(WETH).deposit{value: msg.value}(); } // withdrawers role function withdraw( address withdrawalToken, address recipient, uint256 withdrawalAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IERC20(withdrawalToken).safeTransfer(recipient, withdrawalAmount); } // withdrawers role function withdrawETH(address recipient, uint256 withdrawalAmount) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IWETH(WETH).withdraw(withdrawalAmount); Address.sendValue(payable(recipient), withdrawalAmount); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./BaseLending.sol"; struct HourlyBond { uint256 amount; uint256 yieldQuotientFP; uint256 moduloHour; } /// @title Here we offer subscriptions to auto-renewing hourly bonds /// Funds are locked in for an 50 minutes per hour, while interest rates float abstract contract HourlyBondSubscriptionLending is BaseLending { mapping(address => YieldAccumulator) hourlyBondYieldAccumulators; uint256 constant RATE_UPDATE_WINDOW = 10 minutes; uint256 public withdrawalWindow = 20 minutes; uint256 constant MAX_HOUR_UPDATE = 4; // issuer => holder => bond record mapping(address => mapping(address => HourlyBond)) public hourlyBondAccounts; uint256 public borrowingFactorPercent = 200; uint256 constant borrowMinAPR = 6; uint256 constant borrowMinHourlyYield = FP48 + (borrowMinAPR * FP48) / 100 / hoursPerYear; function _makeHourlyBond( address issuer, address holder, uint256 amount ) internal { HourlyBond storage bond = hourlyBondAccounts[issuer][holder]; updateHourlyBondAmount(issuer, bond); YieldAccumulator storage yieldAccumulator = hourlyBondYieldAccumulators[issuer]; bond.yieldQuotientFP = yieldAccumulator.accumulatorFP; if (bond.amount == 0) { bond.moduloHour = block.timestamp % (1 hours); } bond.amount += amount; lendingMeta[issuer].totalLending += amount; } function updateHourlyBondAmount(address issuer, HourlyBond storage bond) internal { uint256 yieldQuotientFP = bond.yieldQuotientFP; if (yieldQuotientFP > 0) { YieldAccumulator storage yA = getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); uint256 oldAmount = bond.amount; bond.amount = applyInterest( bond.amount, yA.accumulatorFP, yieldQuotientFP ); uint256 deltaAmount = bond.amount - oldAmount; lendingMeta[issuer].totalLending += deltaAmount; } } // Retrieves bond balance for issuer and holder function viewHourlyBondAmount(address issuer, address holder) public view returns (uint256) { HourlyBond storage bond = hourlyBondAccounts[issuer][holder]; uint256 yieldQuotientFP = bond.yieldQuotientFP; uint256 cumulativeYield = viewCumulativeYieldFP( hourlyBondYieldAccumulators[issuer], block.timestamp ); if (yieldQuotientFP > 0) { return applyInterest(bond.amount, cumulativeYield, yieldQuotientFP); } else { return bond.amount; } } function _withdrawHourlyBond( address issuer, HourlyBond storage bond, uint256 amount ) internal { // how far the current hour has advanced (relative to acccount hourly clock) uint256 currentOffset = (block.timestamp - bond.moduloHour) % (1 hours); require( withdrawalWindow >= currentOffset, "Tried withdrawing outside subscription cancellation time window" ); bond.amount -= amount; lendingMeta[issuer].totalLending -= amount; } function calcCumulativeYieldFP( YieldAccumulator storage yieldAccumulator, uint256 timeDelta ) internal view returns (uint256 accumulatorFP) { uint256 secondsDelta = timeDelta % (1 hours); // linearly interpolate interest for seconds // FP * FP * 1 / (FP * 1) = FP accumulatorFP = yieldAccumulator.accumulatorFP + (yieldAccumulator.accumulatorFP * (yieldAccumulator.hourlyYieldFP - FP48) * secondsDelta) / (FP48 * 1 hours); uint256 hoursDelta = timeDelta / (1 hours); if (hoursDelta > 0) { uint256 accumulatorBeforeFP = accumulatorFP; for (uint256 i = 0; hoursDelta > i && MAX_HOUR_UPDATE > i; i++) { // FP48 * FP48 / FP48 = FP48 accumulatorFP = (accumulatorFP * yieldAccumulator.hourlyYieldFP) / FP48; } // a lot of time has passed if (hoursDelta > MAX_HOUR_UPDATE) { // apply interest in non-compounding way accumulatorFP += ((accumulatorFP - accumulatorBeforeFP) * (hoursDelta - MAX_HOUR_UPDATE)) / MAX_HOUR_UPDATE; } } } /// @dev updates yield accumulators for both borrowing and lending /// issuer address represents a token function updateHourlyYield(address issuer) public returns (uint256 hourlyYield) { return getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ) .hourlyYieldFP; } /// @dev updates yield accumulators for both borrowing and lending function getUpdatedHourlyYield( address issuer, YieldAccumulator storage accumulator, uint256 window ) internal returns (YieldAccumulator storage) { uint256 lastUpdated = accumulator.lastUpdated; uint256 timeDelta = (block.timestamp - lastUpdated); if (timeDelta > window) { YieldAccumulator storage borrowAccumulator = borrowYieldAccumulators[issuer]; accumulator.accumulatorFP = calcCumulativeYieldFP( accumulator, timeDelta ); LendingMetadata storage meta = lendingMeta[issuer]; accumulator.hourlyYieldFP = currentLendingRateFP( meta.totalLending, meta.totalBorrowed ); accumulator.lastUpdated = block.timestamp; updateBorrowYieldAccu(borrowAccumulator); borrowAccumulator.hourlyYieldFP = max( borrowMinHourlyYield, FP48 + (borrowingFactorPercent * (accumulator.hourlyYieldFP - FP48)) / 100 ); } return accumulator; } function updateBorrowYieldAccu(YieldAccumulator storage borrowAccumulator) internal { uint256 timeDelta = block.timestamp - borrowAccumulator.lastUpdated; if (timeDelta > RATE_UPDATE_WINDOW) { borrowAccumulator.accumulatorFP = calcCumulativeYieldFP( borrowAccumulator, timeDelta ); borrowAccumulator.lastUpdated = block.timestamp; } } function getUpdatedBorrowYieldAccuFP(address issuer) external returns (uint256) { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; updateBorrowYieldAccu(yA); return yA.accumulatorFP; } function viewCumulativeYieldFP( YieldAccumulator storage yA, uint256 timestamp ) internal view returns (uint256) { uint256 timeDelta = (timestamp - yA.lastUpdated); if (timeDelta > RATE_UPDATE_WINDOW) { return calcCumulativeYieldFP(yA, timeDelta); } else { return yA.accumulatorFP; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Fund.sol"; import "./HourlyBondSubscriptionLending.sol"; import "../libraries/IncentiveReporter.sol"; // TODO activate bonds for lending /// @title Manage lending for a variety of bond issuers contract Lending is RoleAware, HourlyBondSubscriptionLending { /// mapping issuers to tokens /// (in crossmargin, the issuers are tokens themselves) mapping(address => address) public issuerTokens; /// In case of shortfall, adjust debt mapping(address => uint256) public haircuts; /// map of available issuers mapping(address => bool) public activeIssuers; uint256 constant BORROW_RATE_UPDATE_WINDOW = 60 minutes; constructor(address _roles) RoleAware(_roles) {} /// Make a issuer available for protocol function activateIssuer(address issuer) external { activateIssuer(issuer, issuer); } /// Make issuer != token available for protocol (isol. margin) function activateIssuer(address issuer, address token) public onlyOwnerExecActivator { activeIssuers[issuer] = true; issuerTokens[issuer] = token; } /// Remove a issuer from trading availability function deactivateIssuer(address issuer) external onlyOwnerExecActivator { activeIssuers[issuer] = false; } /// Set lending cap function setLendingCap(address issuer, uint256 cap) external onlyOwnerExecActivator { lendingMeta[issuer].lendingCap = cap; } /// Set withdrawal window function setWithdrawalWindow(uint256 window) external onlyOwnerExec { withdrawalWindow = window; } function setNormalRatePerPercent(uint256 rate) external onlyOwnerExec { normalRatePerPercent = rate; } function setHighRatePerPercent(uint256 rate) external onlyOwnerExec { highRatePerPercent = rate; } /// Set hourly yield APR for issuer function setHourlyYieldAPR(address issuer, uint256 aprPercent) external onlyOwnerExecActivator { YieldAccumulator storage yieldAccumulator = hourlyBondYieldAccumulators[issuer]; if (yieldAccumulator.accumulatorFP == 0) { uint256 yieldFP = FP48 + (FP48 * aprPercent) / 100 / (24 * 365); hourlyBondYieldAccumulators[issuer] = YieldAccumulator({ accumulatorFP: FP48, lastUpdated: block.timestamp, hourlyYieldFP: yieldFP }); } else { YieldAccumulator storage yA = getUpdatedHourlyYield( issuer, yieldAccumulator, RATE_UPDATE_WINDOW ); yA.hourlyYieldFP = (FP48 * (100 + aprPercent)) / 100 / (24 * 365); } } /// @dev how much interest has accrued to a borrowed balance over time function applyBorrowInterest( uint256 balance, address issuer, uint256 yieldQuotientFP ) external returns (uint256 balanceWithInterest, uint256 accumulatorFP) { require(isBorrower(msg.sender), "Not approved call"); YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; updateBorrowYieldAccu(yA); accumulatorFP = yA.accumulatorFP; balanceWithInterest = applyInterest( balance, accumulatorFP, yieldQuotientFP ); uint256 deltaAmount = balanceWithInterest - balance; LendingMetadata storage meta = lendingMeta[issuer]; meta.totalBorrowed += deltaAmount; } /// @dev view function to get balance with borrowing interest applied function viewWithBorrowInterest( uint256 balance, address issuer, uint256 yieldQuotientFP ) external view returns (uint256) { uint256 accumulatorFP = viewCumulativeYieldFP( borrowYieldAccumulators[issuer], block.timestamp ); return applyInterest(balance, accumulatorFP, yieldQuotientFP); } /// @dev gets called by router to register if a trader borrows issuers function registerBorrow(address issuer, uint256 amount) external { require(isBorrower(msg.sender), "Not approved borrower"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalBorrowed += amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], BORROW_RATE_UPDATE_WINDOW ); require( meta.totalLending >= meta.totalBorrowed, "Insufficient lending" ); } /// @dev gets called when external sources provide lending function registerLend(address issuer, uint256 amount) external { require(isLender(msg.sender), "Not an approved lender"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalLending += amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); } /// @dev gets called when external sources pay withdraw their bobnd function registerWithdrawal(address issuer, uint256 amount) external { require(isLender(msg.sender), "Not an approved lender"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalLending -= amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); } /// @dev gets called by router if loan is extinguished function payOff(address issuer, uint256 amount) external { require(isBorrower(msg.sender), "Not approved borrower"); lendingMeta[issuer].totalBorrowed -= amount; } /// @dev get the borrow yield for a specific issuer/token function viewAccumulatedBorrowingYieldFP(address issuer) external view returns (uint256) { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; return viewCumulativeYieldFP(yA, block.timestamp); } function viewAPRPer10k(YieldAccumulator storage yA) internal view returns (uint256) { uint256 hourlyYieldFP = yA.hourlyYieldFP; uint256 aprFP = ((hourlyYieldFP * 10_000 - FP48 * 10_000) * 365 days) / (1 hours); return aprFP / FP48; } /// @dev get current borrowing interest per 10k for a token / issuer function viewBorrowAPRPer10k(address issuer) external view returns (uint256) { return viewAPRPer10k(borrowYieldAccumulators[issuer]); } /// @dev get current lending APR per 10k for a token / issuer function viewHourlyBondAPRPer10k(address issuer) external view returns (uint256) { return viewAPRPer10k(hourlyBondYieldAccumulators[issuer]); } /// @dev In a liquidity crunch make a fallback bond until liquidity is good again function makeFallbackBond( address issuer, address holder, uint256 amount ) external { require(isLender(msg.sender), "Not an approved lender"); _makeHourlyBond(issuer, holder, amount); } /// @dev withdraw an hour bond function withdrawHourlyBond(address issuer, uint256 amount) external { HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender]; // apply all interest updateHourlyBondAmount(issuer, bond); super._withdrawHourlyBond(issuer, bond, amount); if (bond.amount == 0) { delete hourlyBondAccounts[issuer][msg.sender]; } disburse(issuer, msg.sender, amount); IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount); } /// Shut down hourly bond account for `issuer` function closeHourlyBondAccount(address issuer) external { HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender]; // apply all interest updateHourlyBondAmount(issuer, bond); uint256 amount = bond.amount; super._withdrawHourlyBond(issuer, bond, amount); disburse(issuer, msg.sender, amount); delete hourlyBondAccounts[issuer][msg.sender]; IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount); } /// @dev buy hourly bond subscription function buyHourlyBondSubscription(address issuer, uint256 amount) external { require(activeIssuers[issuer], "Not approved issuer"); collectToken(issuer, msg.sender, amount); super._makeHourlyBond(issuer, msg.sender, amount); IncentiveReporter.addToClaimAmount(issuer, msg.sender, amount); } function initBorrowYieldAccumulator(address issuer) external onlyOwnerExecActivator { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; require(yA.accumulatorFP == 0, "don't re-initialize"); yA.accumulatorFP = FP48; yA.lastUpdated = block.timestamp; yA.hourlyYieldFP = FP48 + (FP48 * borrowMinAPR) / 100 / (365 * 24); } function setBorrowingFactorPercent(uint256 borrowingFactor) external onlyOwnerExec { borrowingFactorPercent = borrowingFactor; } function issuanceBalance(address issuer) internal view override returns (uint256) { address token = issuerTokens[issuer]; if (token == issuer) { // cross margin return IERC20(token).balanceOf(fund()); } else { return lendingMeta[issuer].totalLending - haircuts[issuer]; } } function disburse( address issuer, address recipient, uint256 amount ) internal { uint256 haircutAmount = haircuts[issuer]; if (haircutAmount > 0 && amount > 0) { uint256 totalLending = lendingMeta[issuer].totalLending; uint256 adjustment = (amount * min(totalLending, haircutAmount)) / totalLending; amount = amount - adjustment; haircuts[issuer] -= adjustment; } address token = issuerTokens[issuer]; Fund(fund()).withdraw(token, recipient, amount); } function collectToken( address issuer, address source, uint256 amount ) internal { Fund(fund()).depositFor(source, issuer, amount); } function haircut(uint256 amount) external { haircuts[msg.sender] += amount; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; import "../interfaces/IMarginTrading.sol"; import "./Lending.sol"; import "./Admin.sol"; import "./BaseRouter.sol"; import "../libraries/IncentiveReporter.sol"; /// @title Top level transaction controller contract MarginRouter is RoleAware, BaseRouter { event AccountUpdated(address indexed trader); uint256 public constant mswapFeesPer10k = 10; address public immutable WETH; constructor(address _WETH, address _roles) RoleAware(_roles) { WETH = _WETH; } /////////////////////////// // Cross margin endpoints /////////////////////////// /// @notice traders call this to deposit funds on cross margin function crossDeposit(address depositToken, uint256 depositAmount) external { Fund(fund()).depositFor(msg.sender, depositToken, depositAmount); uint256 extinguishAmount = IMarginTrading(crossMarginTrading()).registerDeposit( msg.sender, depositToken, depositAmount ); if (extinguishAmount > 0) { Lending(lending()).payOff(depositToken, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( depositToken, msg.sender, extinguishAmount ); } emit AccountUpdated(msg.sender); } /// @notice deposit wrapped ehtereum into cross margin account function crossDepositETH() external payable { Fund(fund()).depositToWETH{value: msg.value}(); uint256 extinguishAmount = IMarginTrading(crossMarginTrading()).registerDeposit( msg.sender, WETH, msg.value ); if (extinguishAmount > 0) { Lending(lending()).payOff(WETH, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( WETH, msg.sender, extinguishAmount ); } emit AccountUpdated(msg.sender); } /// @notice withdraw deposits/earnings from cross margin account function crossWithdraw(address withdrawToken, uint256 withdrawAmount) external { IMarginTrading(crossMarginTrading()).registerWithdrawal( msg.sender, withdrawToken, withdrawAmount ); Fund(fund()).withdraw(withdrawToken, msg.sender, withdrawAmount); emit AccountUpdated(msg.sender); } /// @notice withdraw ethereum from cross margin account function crossWithdrawETH(uint256 withdrawAmount) external { IMarginTrading(crossMarginTrading()).registerWithdrawal( msg.sender, WETH, withdrawAmount ); Fund(fund()).withdrawETH(msg.sender, withdrawAmount); emit AccountUpdated(msg.sender); } /// @notice borrow into cross margin trading account function crossBorrow(address borrowToken, uint256 borrowAmount) external { Lending(lending()).registerBorrow(borrowToken, borrowAmount); IMarginTrading(crossMarginTrading()).registerBorrow( msg.sender, borrowToken, borrowAmount ); IncentiveReporter.addToClaimAmount( borrowToken, msg.sender, borrowAmount ); emit AccountUpdated(msg.sender); } /// @notice convenience function to perform overcollateralized borrowing /// against a cross margin account. /// @dev caution: the account still has to have a positive balaance at the end /// of the withdraw. So an underwater account may not be able to withdraw function crossOvercollateralizedBorrow( address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external { Fund(fund()).depositFor(msg.sender, depositToken, depositAmount); Lending(lending()).registerBorrow(borrowToken, withdrawAmount); IMarginTrading(crossMarginTrading()).registerOvercollateralizedBorrow( msg.sender, depositToken, depositAmount, borrowToken, withdrawAmount ); Fund(fund()).withdraw(borrowToken, msg.sender, withdrawAmount); IncentiveReporter.addToClaimAmount( borrowToken, msg.sender, withdrawAmount ); emit AccountUpdated(msg.sender); } /// @notice close an account that is no longer borrowing and return gains function crossCloseAccount() external { (address[] memory holdingTokens, uint256[] memory holdingAmounts) = IMarginTrading(crossMarginTrading()).getHoldingAmounts(msg.sender); // requires all debts paid off IMarginTrading(crossMarginTrading()).registerLiquidation(msg.sender); for (uint256 i; holdingTokens.length > i; i++) { Fund(fund()).withdraw( holdingTokens[i], msg.sender, holdingAmounts[i] ); } emit AccountUpdated(msg.sender); } /// @notice entry point for swapping tokens held in cross margin account function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { // calc fees uint256 fees = takeFeesFromInput(amountIn); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn - fees, amms, tokens ); // checks that trader is within allowed lending bounds registerTrade( msg.sender, tokens[0], tokens[tokens.length - 1], amountIn, amounts[amounts.length - 1] ); _fundSwapExactT4T(amounts, amountOutMin, pairs, tokens); } /// @notice entry point for swapping tokens held in cross margin account function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut + takeFeesFromOutput(amountOut), amms, tokens ); // checks that trader is within allowed lending bounds registerTrade( msg.sender, tokens[0], tokens[tokens.length - 1], amounts[0], amountOut ); _fundSwapT4ExactT(amounts, amountInMax, pairs, tokens); } /// @dev helper function does all the work of telling other contracts /// about a cross margin trade function registerTrade( address trader, address inToken, address outToken, uint256 inAmount, uint256 outAmount ) internal { (uint256 extinguishAmount, uint256 borrowAmount) = IMarginTrading(crossMarginTrading()).registerTradeAndBorrow( trader, inToken, outToken, inAmount, outAmount ); if (extinguishAmount > 0) { Lending(lending()).payOff(outToken, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( outToken, trader, extinguishAmount ); } if (borrowAmount > 0) { Lending(lending()).registerBorrow(inToken, borrowAmount); IncentiveReporter.addToClaimAmount(inToken, trader, borrowAmount); } emit AccountUpdated(trader); } ///////////// // Helpers ///////////// /// @dev internal helper swapping exact token for token on AMM function _fundSwapExactT4T( uint256[] memory amounts, uint256 amountOutMin, address[] memory pairs, address[] calldata tokens ) internal { require( amounts[amounts.length - 1] >= amountOutMin, "MarginRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]); _swap(amounts, pairs, tokens, fund()); } /// @notice make swaps on AMM using protocol funds, only for authorized contracts function authorizedSwapExactT4T( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens ) external returns (uint256[] memory amounts) { require( isAuthorizedFundTrader(msg.sender), "Calling contract is not authorized to trade with protocl funds" ); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn, amms, tokens ); _fundSwapExactT4T(amounts, amountOutMin, pairs, tokens); } // @dev internal helper swapping exact token for token on on AMM function _fundSwapT4ExactT( uint256[] memory amounts, uint256 amountInMax, address[] memory pairs, address[] calldata tokens ) internal { require( amounts[0] <= amountInMax, "MarginRouter: EXCESSIVE_INPUT_AMOUNT" ); Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]); _swap(amounts, pairs, tokens, fund()); } //// @notice swap protocol funds on AMM, only for authorized function authorizedSwapT4ExactT( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens ) external returns (uint256[] memory amounts) { require( isAuthorizedFundTrader(msg.sender), "Calling contract is not authorized to trade with protocl funds" ); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut, amms, tokens ); _fundSwapT4ExactT(amounts, amountInMax, pairs, tokens); } function takeFeesFromOutput(uint256 amount) internal pure returns (uint256 fees) { fees = (mswapFeesPer10k * amount) / 10_000; } function takeFeesFromInput(uint256 amount) internal pure returns (uint256 fees) { fees = (mswapFeesPer10k * amount) / (10_000 + mswapFeesPer10k); } function getAmountsOut( uint256 inAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsOut(inAmount, amms, tokens); } function getAmountsIn( uint256 outAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsIn(outAmount, amms, tokens); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; import "./MarginRouter.sol"; import "../libraries/UniswapStyleLib.sol"; /// Stores how many of token you could get for 1k of peg struct TokenPrice { uint256 lastUpdated; uint256 priceFP; address[] liquidationTokens; bytes32 amms; address[] inverseLiquidationTokens; bytes32 inverseAmms; } struct VolatilitySetting { uint256 priceUpdateWindow; uint256 updateRatePermil; uint256 voluntaryUpdateWindow; } struct PairPrice { uint256 cumulative; uint256 lastUpdated; uint256 priceFP; } /// @title The protocol features several mechanisms to prevent vulnerability to /// price manipulation: /// 1) global exposure caps on all tokens which need to be raised gradually /// during the process of introducing a new token, making attacks unprofitable /// due to lack of scale /// 2) Exponential moving average with cautious price update. Prices for estimating /// how much a trader can borrow need not be extremely current and precise, mainly /// they must be resilient against extreme manipulation /// 3) Liquidators may not call from a contract address, to prevent extreme forms of /// of front-running and other price manipulation. abstract contract PriceAware is RoleAware { uint256 constant FP112 = 2**112; address public immutable peg; mapping(address => TokenPrice) public tokenPrices; mapping(address => mapping(address => PairPrice)) public pairPrices; /// update window in blocks // TODO uint256 public priceUpdateWindow = 20 minutes; uint256 public voluntaryUpdateWindow = 5 minutes; uint256 public UPDATE_RATE_PERMIL = 400; VolatilitySetting[] public volatilitySettings; constructor(address _peg) { peg = _peg; } /// Set window for price updates function setPriceUpdateWindow(uint16 window, uint256 voluntaryWindow) external onlyOwnerExec { priceUpdateWindow = window; voluntaryUpdateWindow = voluntaryWindow; } /// Add a new volatility setting function addVolatilitySetting( uint256 _priceUpdateWindow, uint256 _updateRatePermil, uint256 _voluntaryUpdateWindow ) external onlyOwnerExec { volatilitySettings.push( VolatilitySetting({ priceUpdateWindow: _priceUpdateWindow, updateRatePermil: _updateRatePermil, voluntaryUpdateWindow: _voluntaryUpdateWindow }) ); } /// Choose a volatitlity setting function chooseVolatilitySetting(uint256 index) external onlyOwnerExecDisabler { VolatilitySetting storage vs = volatilitySettings[index]; if (vs.updateRatePermil > 0) { UPDATE_RATE_PERMIL = vs.updateRatePermil; priceUpdateWindow = vs.priceUpdateWindow; voluntaryUpdateWindow = vs.voluntaryUpdateWindow; } } /// Set rate for updates function setUpdateRate(uint256 rate) external onlyOwnerExec { UPDATE_RATE_PERMIL = rate; } function getCurrentPriceInPeg(address token, uint256 inAmount) internal returns (uint256) { return getCurrentPriceInPeg(token, inAmount, false); } function getCurrentPriceInPeg( address token, uint256 inAmount, bool voluntary ) public returns (uint256 priceInPeg) { if (token == peg) { return inAmount; } else { TokenPrice storage tokenPrice = tokenPrices[token]; uint256 timeDelta = block.timestamp - tokenPrice.lastUpdated; if ( timeDelta > priceUpdateWindow || tokenPrice.priceFP == 0 || (voluntary && timeDelta > voluntaryUpdateWindow) ) { // update the currently cached price uint256 priceUpdateFP; priceUpdateFP = getPriceByPairs( tokenPrice.liquidationTokens, tokenPrice.amms ); _setPriceVal(tokenPrice, priceUpdateFP, UPDATE_RATE_PERMIL); } priceInPeg = (inAmount * tokenPrice.priceFP) / FP112; } } /// Get view of current price of token in peg function viewCurrentPriceInPeg(address token, uint256 inAmount) public view returns (uint256 priceInPeg) { if (token == peg) { return inAmount; } else { TokenPrice storage tokenPrice = tokenPrices[token]; uint256 priceFP = tokenPrice.priceFP; priceInPeg = (inAmount * priceFP) / FP112; } } function _setPriceVal( TokenPrice storage tokenPrice, uint256 updateFP, uint256 weightPerMil ) internal { tokenPrice.priceFP = (tokenPrice.priceFP * (1000 - weightPerMil) + updateFP * weightPerMil) / 1000; tokenPrice.lastUpdated = block.timestamp; } /// add path from token to current liquidation peg function setLiquidationPath(bytes32 amms, address[] memory tokens) external onlyOwnerExecActivator { address token = tokens[0]; if (token != peg) { TokenPrice storage tokenPrice = tokenPrices[token]; tokenPrice.amms = amms; tokenPrice.liquidationTokens = tokens; tokenPrice.inverseLiquidationTokens = new address[](tokens.length); bytes32 inverseAmms; for (uint256 i = 0; tokens.length - 1 > i; i++) { initPairPrice(tokens[i], tokens[i + 1], amms[i]); bytes32 shifted = bytes32(amms[i]) >> ((tokens.length - 2 - i) * 8); inverseAmms = inverseAmms | shifted; } tokenPrice.inverseAmms = inverseAmms; for (uint256 i = 0; tokens.length > i; i++) { tokenPrice.inverseLiquidationTokens[i] = tokens[ tokens.length - i - 1 ]; } tokenPrice.priceFP = getPriceByPairs(tokens, amms); tokenPrice.lastUpdated = block.timestamp; } } function liquidateToPeg(address token, uint256 amount) internal returns (uint256) { if (token == peg) { return amount; } else { TokenPrice storage tP = tokenPrices[token]; uint256[] memory amounts = MarginRouter(marginRouter()).authorizedSwapExactT4T( amount, 0, tP.amms, tP.liquidationTokens ); uint256 outAmount = amounts[amounts.length - 1]; return outAmount; } } function liquidateFromPeg(address token, uint256 targetAmount) internal returns (uint256) { if (token == peg) { return targetAmount; } else { TokenPrice storage tP = tokenPrices[token]; uint256[] memory amounts = MarginRouter(marginRouter()).authorizedSwapT4ExactT( targetAmount, type(uint256).max, tP.amms, tP.inverseLiquidationTokens ); return amounts[0]; } } function getPriceByPairs(address[] memory tokens, bytes32 amms) internal returns (uint256 priceFP) { priceFP = FP112; for (uint256 i; i < tokens.length - 1; i++) { address inToken = tokens[i]; address outToken = tokens[i + 1]; address pair = amms[i] == 0 ? UniswapStyleLib.pairForUni(inToken, outToken) : UniswapStyleLib.pairForSushi(inToken, outToken); PairPrice storage pairPrice = pairPrices[pair][inToken]; (, , uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves(); uint256 timeDelta = pairLastUpdated - pairPrice.lastUpdated; if (timeDelta > voluntaryUpdateWindow) { // we are in business (address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken); uint256 cumulative = inToken == token0 ? IUniswapV2Pair(pair).price0CumulativeLast() : IUniswapV2Pair(pair).price1CumulativeLast(); uint256 pairPriceFP = (cumulative - pairPrice.cumulative) / timeDelta; priceFP = (priceFP * pairPriceFP) / FP112; pairPrice.priceFP = pairPriceFP; pairPrice.cumulative = cumulative; pairPrice.lastUpdated = pairLastUpdated; } else { priceFP = (priceFP * pairPrice.priceFP) / FP112; } } } function initPairPrice( address inToken, address outToken, bytes1 amm ) internal { address pair = amm == 0 ? UniswapStyleLib.pairForUni(inToken, outToken) : UniswapStyleLib.pairForSushi(inToken, outToken); PairPrice storage pairPrice = pairPrices[pair][inToken]; if (pairPrice.lastUpdated == 0) { (uint112 reserve0, uint112 reserve1, uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves(); (address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken); if (inToken == token0) { pairPrice.priceFP = (FP112 * reserve1) / reserve0; pairPrice.cumulative = IUniswapV2Pair(pair) .price0CumulativeLast(); } else { pairPrice.priceFP = (FP112 * reserve0) / reserve1; pairPrice.cumulative = IUniswapV2Pair(pair) .price1CumulativeLast(); } pairPrice.lastUpdated = block.timestamp; pairPrice.lastUpdated = pairLastUpdated; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Roles.sol"; /// @title Role management behavior /// Main characters are for service discovery /// Whereas roles are for access control contract RoleAware { Roles public immutable roles; mapping(uint256 => address) public mainCharacterCache; mapping(address => mapping(uint256 => bool)) public roleCache; constructor(address _roles) { require(_roles != address(0), "Please provide valid roles address"); roles = Roles(_roles); } modifier noIntermediary() { require( msg.sender == tx.origin, "Currently no intermediaries allowed for this function call" ); _; } // @dev Throws if called by any account other than the owner or executor modifier onlyOwnerExec() { require( owner() == msg.sender || executor() == msg.sender, "Roles: caller is not the owner" ); _; } modifier onlyOwnerExecDisabler() { require( owner() == msg.sender || executor() == msg.sender || disabler() == msg.sender, "Caller is not the owner, executor or authorized disabler" ); _; } modifier onlyOwnerExecActivator() { require( owner() == msg.sender || executor() == msg.sender || isTokenActivator(msg.sender), "Caller is not the owner, executor or authorized activator" ); _; } function updateRoleCache(uint256 role, address contr) public virtual { roleCache[contr][role] = roles.getRole(role, contr); } function updateMainCharacterCache(uint256 role) public virtual { mainCharacterCache[role] = roles.mainCharacters(role); } function owner() internal view returns (address) { return roles.owner(); } function executor() internal returns (address) { return roles.executor(); } function disabler() internal view returns (address) { return mainCharacterCache[DISABLER]; } function fund() internal view returns (address) { return mainCharacterCache[FUND]; } function lending() internal view returns (address) { return mainCharacterCache[LENDING]; } function marginRouter() internal view returns (address) { return mainCharacterCache[MARGIN_ROUTER]; } function crossMarginTrading() internal view returns (address) { return mainCharacterCache[CROSS_MARGIN_TRADING]; } function feeController() internal view returns (address) { return mainCharacterCache[FEE_CONTROLLER]; } function price() internal view returns (address) { return mainCharacterCache[PRICE_CONTROLLER]; } function admin() internal view returns (address) { return mainCharacterCache[ADMIN]; } function incentiveDistributor() internal view returns (address) { return mainCharacterCache[INCENTIVE_DISTRIBUTION]; } function tokenAdmin() internal view returns (address) { return mainCharacterCache[TOKEN_ADMIN]; } function isBorrower(address contr) internal view returns (bool) { return roleCache[contr][BORROWER]; } function isFundTransferer(address contr) internal view returns (bool) { return roleCache[contr][FUND_TRANSFERER]; } function isMarginTrader(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_TRADER]; } function isFeeSource(address contr) internal view returns (bool) { return roleCache[contr][FEE_SOURCE]; } function isMarginCaller(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_CALLER]; } function isLiquidator(address contr) internal view returns (bool) { return roleCache[contr][LIQUIDATOR]; } function isAuthorizedFundTrader(address contr) internal view returns (bool) { return roleCache[contr][AUTHORIZED_FUND_TRADER]; } function isIncentiveReporter(address contr) internal view returns (bool) { return roleCache[contr][INCENTIVE_REPORTER]; } function isTokenActivator(address contr) internal view returns (bool) { return roleCache[contr][TOKEN_ACTIVATOR]; } function isStakePenalizer(address contr) internal view returns (bool) { return roleCache[contr][STAKE_PENALIZER]; } function isLender(address contr) internal view returns (bool) { return roleCache[contr][LENDER]; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IDependencyController.sol"; // we chose not to go with an enum // to make this list easy to extend uint256 constant FUND_TRANSFERER = 1; uint256 constant MARGIN_CALLER = 2; uint256 constant BORROWER = 3; uint256 constant MARGIN_TRADER = 4; uint256 constant FEE_SOURCE = 5; uint256 constant LIQUIDATOR = 6; uint256 constant AUTHORIZED_FUND_TRADER = 7; uint256 constant INCENTIVE_REPORTER = 8; uint256 constant TOKEN_ACTIVATOR = 9; uint256 constant STAKE_PENALIZER = 10; uint256 constant LENDER = 11; uint256 constant FUND = 101; uint256 constant LENDING = 102; uint256 constant MARGIN_ROUTER = 103; uint256 constant CROSS_MARGIN_TRADING = 104; uint256 constant FEE_CONTROLLER = 105; uint256 constant PRICE_CONTROLLER = 106; uint256 constant ADMIN = 107; uint256 constant INCENTIVE_DISTRIBUTION = 108; uint256 constant TOKEN_ADMIN = 109; uint256 constant DISABLER = 1001; uint256 constant DEPENDENCY_CONTROLLER = 1002; /// @title Manage permissions of contracts and ownership of everything /// owned by a multisig wallet (0xEED9D1c6B4cdEcB3af070D85bfd394E7aF179CBd) during /// beta and will then be transfered to governance /// https://github.com/marginswap/governance contract Roles is Ownable { mapping(address => mapping(uint256 => bool)) public roles; mapping(uint256 => address) public mainCharacters; constructor() Ownable() { // token activation from the get-go roles[msg.sender][TOKEN_ACTIVATOR] = true; } /// @dev Throws if called by any account other than the owner. modifier onlyOwnerExecDepController() { require( owner() == msg.sender || executor() == msg.sender || mainCharacters[DEPENDENCY_CONTROLLER] == msg.sender, "Roles: caller is not the owner" ); _; } function giveRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = true; } function removeRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = false; } function setMainCharacter(uint256 role, address actor) external onlyOwnerExecDepController { mainCharacters[role] = actor; } function getRole(uint256 role, address contr) external view returns (bool) { return roles[contr][role]; } /// @dev current executor function executor() public returns (address exec) { address depController = mainCharacters[DEPENDENCY_CONTROLLER]; if (depController != address(0)) { exec = IDependencyController(depController).currentExecutor(); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IDependencyController { function currentExecutor() external returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IMarginTrading { function registerDeposit( address trader, address token, uint256 amount ) external returns (uint256 extinguishAmount); function registerWithdrawal( address trader, address token, uint256 amount ) external; function registerBorrow( address trader, address token, uint256 amount ) external; function registerTradeAndBorrow( address trader, address inToken, address outToken, uint256 inAmount, uint256 outAmount ) external returns (uint256 extinguishAmount, uint256 borrowAmount); function registerOvercollateralizedBorrow( address trader, address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external; function registerLiquidation(address trader) external; function getHoldingAmounts(address trader) external view returns ( address[] memory holdingTokens, uint256[] memory holdingAmounts ); function getBorrowAmounts(address trader) external view returns (address[] memory borrowTokens, uint256[] memory borrowAmounts); } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } library IncentiveReporter { event AddToClaim(address topic, address indexed claimant, uint256 amount); event SubtractFromClaim( address topic, address indexed claimant, uint256 amount ); /// Start / increase amount of claim function addToClaimAmount( address topic, address recipient, uint256 claimAmount ) internal { emit AddToClaim(topic, recipient, claimAmount); } /// Decrease amount of claim function subtractFromClaimAmount( address topic, address recipient, uint256 subtractAmount ) internal { emit SubtractFromClaim(topic, recipient, subtractAmount); } } pragma solidity >=0.5.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; library UniswapStyleLib { address constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address constant SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // 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, "Identical address!"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "Zero address!"); } // fetches and sorts the reserves for a pair function getReserves( address pair, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1_000 + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn * amountOut * 1_000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( uint256 amountIn, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[0] = amountIn; pairs = new address[](tokens.length - 1); for (uint256 i; i < tokens.length - 1; i++) { address inToken = tokens[i]; address outToken = tokens[i + 1]; address pair = amms[i] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( uint256 amountOut, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[amounts.length - 1] = amountOut; pairs = new address[](tokens.length - 1); for (uint256 i = tokens.length - 1; i > 0; i--) { address inToken = tokens[i - 1]; address outToken = tokens[i]; address pair = amms[i - 1] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i - 1] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } // calculates the CREATE2 address for a pair without making any external calls function pairForUni(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", UNISWAP_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } function pairForSushi(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", SUSHI_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ) ); } }
Make a issuer available for protocol
function activateIssuer(address issuer) external { activateIssuer(issuer, issuer); }
563,853
./full_match/1/0x6ADD0Ac9f7dee66d02cC46A77B1666Ff5Ebf284E/sources/src/BeraPunk/Den.sol
admin function to mint a specified amount of THJ. the value is set on initialization.
function adminMint(uint8 bundleId_, uint256 amount_) external onlyRole(Constants.GAME_ADMIN) { if (adminMintAmount == 0) revert MekingTooManyHoneyJars(bundleId_); if (amount_ > adminMintAmount) { amount_ = adminMintAmount; } adminMintAmount -= amount_; _canMintHoneyJar(bundleId_, amount_); _mintHoneyJarForBear(msg.sender, bundleId_, amount_); }
4,911,088
pragma solidity ^0.4.24; /** * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed from, address indexed to); /** * Constructor */ constructor() public { owner = msg.sender; } /** * @dev Only the owner of contract */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev transfer the ownership to other * - Only the owner can operate */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev Accept the ownership from last owner */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract TRNData is Owned { TripioRoomNightData dataSource; /** * Only the valid vendor and the vendor is valid */ modifier onlyVendor { uint256 vendorId = dataSource.vendorIds(msg.sender); require(vendorId > 0); (,,,bool valid) = dataSource.getVendor(vendorId); require(valid); _; } /** * The vendor is valid */ modifier vendorValid(address _vendor) { uint256 vendorId = dataSource.vendorIds(_vendor); require(vendorId > 0); (,,,bool valid) = dataSource.getVendor(vendorId); require(valid); _; } /** * The vendorId is valid */ modifier vendorIdValid(uint256 _vendorId) { (,,,bool valid) = dataSource.getVendor(_vendorId); require(valid); _; } /** * Rate plan exist. */ modifier ratePlanExist(uint256 _vendorId, uint256 _rpid) { (,,,bool valid) = dataSource.getVendor(_vendorId); require(valid); require(dataSource.ratePlanIsExist(_vendorId, _rpid)); _; } /** * Token is valid */ modifier validToken(uint256 _tokenId) { require(_tokenId > 0); require(dataSource.roomNightIndexToOwner(_tokenId) != address(0)); _; } /** * Tokens are valid */ modifier validTokenInBatch(uint256[] _tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { require(_tokenIds[i] > 0); require(dataSource.roomNightIndexToOwner(_tokenIds[i]) != address(0)); } _; } /** * Whether the `_tokenId` can be transfered */ modifier canTransfer(uint256 _tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); bool isOwner = (msg.sender == owner); bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenId)); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isApproval || isOperator); _; } /** * Whether the `_tokenIds` can be transfered */ modifier canTransferInBatch(uint256[] _tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]); bool isOwner = (msg.sender == owner); bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenIds[i])); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isApproval || isOperator); } _; } /** * Whether the `_tokenId` can be operated by `msg.sender` */ modifier canOperate(uint256 _tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); bool isOwner = (msg.sender == owner); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isOperator); _; } /** * Whether the `_date` is valid(no hours, no seconds) */ modifier validDate(uint256 _date) { require(_date > 0); require(dateIsLegal(_date)); _; } /** * Whether the `_dates` are valid(no hours, no seconds) */ modifier validDates(uint256[] _dates) { for(uint256 i = 0;i < _dates.length; i++) { require(_dates[i] > 0); require(dateIsLegal(_dates[i])); } _; } function dateIsLegal(uint256 _date) pure private returns(bool) { uint256 year = _date / 10000; uint256 mon = _date / 100 - year * 100; uint256 day = _date - mon * 100 - year * 10000; if(year < 1970 || mon <= 0 || mon > 12 || day <= 0 || day > 31) return false; if(4 == mon || 6 == mon || 9 == mon || 11 == mon){ if (day == 31) { return false; } } if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { if(2 == mon && day > 29) { return false; } }else { if(2 == mon && day > 28){ return false; } } return true; } /** * Constructor */ constructor() public { } } contract TRNPrices is TRNData { /** * Constructor */ constructor() public { } /** * This emits when rate plan price changed */ event RatePlanPriceChanged(uint256 indexed _rpid); /** * This emits when rate plan inventory changed */ event RatePlanInventoryChanged(uint256 indexed _rpid); /** * This emits when rate plan base price changed */ event RatePlanBasePriceChanged(uint256 indexed _rpid); function _updatePrices(uint256 _rpid, uint256 _date, uint16 _inventory, uint256[] _tokens, uint256[] _prices) private { uint256 vendorId = dataSource.vendorIds(msg.sender); dataSource.updateInventories(vendorId, _rpid, _date, _inventory); for (uint256 tindex = 0; tindex < _tokens.length; tindex++) { dataSource.updatePrice(vendorId, _rpid, _date, _tokens[tindex], _prices[tindex]); } } function _updateInventories(uint256 _rpid, uint256 _date, uint16 _inventory) private { uint256 vendorId = dataSource.vendorIds(msg.sender); dataSource.updateInventories(vendorId, _rpid, _date, _inventory); } /** * @dev Update base price assigned to a vendor by `_rpid`, `msg.sender`, `_dates` * Throw when `msg.sender` is not a vendor * Throw when `_rpid` not exist * Throw when `_tokens`'s length is not equal to `_prices`'s length or `_tokens`'s length is equal to zero * @param _rpid The rate plan identifier * @param _inventory The amount that can be sold * @param _tokens The pricing currency token * @param _prices The currency token selling price */ function updateBasePrice(uint256 _rpid, uint256[] _tokens, uint256[] _prices, uint16 _inventory) external ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { require(_tokens.length == _prices.length); require(_prices.length > 0); uint256 vendorId = dataSource.vendorIds(msg.sender); dataSource.updateBaseInventory(vendorId, _rpid, _inventory); for (uint256 tindex = 0; tindex < _tokens.length; tindex++) { dataSource.updateBasePrice(vendorId, _rpid, _tokens[tindex], _prices[tindex]); } // Event emit RatePlanBasePriceChanged(_rpid); return true; } /** * @dev Update prices assigned to a vendor by `_rpid`, `msg.sender`, `_dates` * Throw when `msg.sender` is not a vendor * Throw when `_rpid` not exist * Throw when `_dates`'s length lte 0 * Throw when `_tokens`'s length is not equal to `_prices`'s length or `_tokens`'s length is equal to zero * @param _rpid The rate plan identifier * @param _dates The prices to be modified of `_dates` * @param _inventory The amount that can be sold * @param _tokens The pricing currency token * @param _prices The currency token selling price */ function updatePrices(uint256 _rpid, uint256[] _dates, uint16 _inventory, uint256[] _tokens, uint256[] _prices) external ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { require(_dates.length > 0); require(_tokens.length == _prices.length); require(_prices.length > 0); for (uint256 index = 0; index < _dates.length; index++) { _updatePrices(_rpid, _dates[index], _inventory, _tokens, _prices); } // Event emit RatePlanPriceChanged(_rpid); return true; } /** * @dev Update inventory assigned to a vendor by `_rpid`, `msg.sender`, `_dates` * Throw when `msg.sender` is not a vendor * Throw when `_rpid` not exist * Throw when `_dates`'s length lte 0 * @param _rpid The rate plan identifier * @param _dates The prices to be modified of `_dates` * @param _inventory The amount that can be sold */ function updateInventories(uint256 _rpid, uint256[] _dates, uint16 _inventory) external ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { for (uint256 index = 0; index < _dates.length; index++) { _updateInventories(_rpid, _dates[index], _inventory); } // Event emit RatePlanInventoryChanged(_rpid); return true; } /** * @dev Returns the inventories of `_vendor`'s RP(`_rpid`) on `_dates` * Throw when `_rpid` not exist * Throw when `_dates`'s count lte 0 * @param _vendorId The vendor Id * @param _rpid The rate plan identifier * @param _dates The inventories to be returned of `_dates` * @return The inventories */ function inventoriesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates) external view ratePlanExist(_vendorId, _rpid) returns(uint16[]) { require(_dates.length > 0); uint16[] memory result = new uint16[](_dates.length); for (uint256 index = 0; index < _dates.length; index++) { uint256 date = _dates[index]; (uint16 inventory,) = dataSource.getInventory(_vendorId, _rpid, date); result[index] = inventory; } return result; } /** * @dev Returns the prices of `_vendor`'s RP(`_rpid`) on `_dates` * Throw when `_rpid` not exist * Throw when `_dates`'s count lte 0 * @param _vendorId The vendor Id * @param _rpid The rate plan identifier * @param _dates The inventories to be returned of `_dates` * @param _token The digital currency token * @return The prices */ function pricesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token) external view ratePlanExist(_vendorId, _rpid) returns(uint256[]) { require(_dates.length > 0); uint256[] memory result = new uint256[](_dates.length); for (uint256 index = 0; index < _dates.length; index++) { (,, uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _dates[index], _token); result[index] = _price; } return result; } /** * @dev Returns the prices and inventories of `_vendor`'s RP(`_rpid`) on `_dates` * Throw when `_rpid` not exist * Throw when `_dates`'s count lte 0 * @param _vendorId The vendor Id * @param _rpid The rate plan identifier * @param _dates The inventories to be returned of `_dates` * @param _token The digital currency token * @return The prices and inventories */ function pricesAndInventoriesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token) external view returns(uint256[], uint16[]) { uint256[] memory prices = new uint256[](_dates.length); uint16[] memory inventories = new uint16[](_dates.length); for (uint256 index = 0; index < _dates.length; index++) { (uint16 _inventory,, uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _dates[index], _token); prices[index] = _price; inventories[index] = _inventory; } return (prices, inventories); } /** * @dev Returns the RP's price and inventory of `_date`. * Throw when `_rpid` not exist * @param _vendorId The vendor Id * @param _rpid The rate plan identifier * @param _date The price and inventory to be returneed of `_date` * @param _token The digital currency token * @return The price and inventory */ function priceOfDate(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token) external view ratePlanExist(_vendorId, _rpid) returns(uint16 _inventory, uint256 _price) { (_inventory, , _price) = dataSource.getPrice(_vendorId, _rpid, _date, _token); } } /** * This utility library was forked from https://github.com/o0ragman0o/LibCLL */ library LinkedListLib { uint256 constant NULL = 0; uint256 constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct LinkedList { mapping (uint256 => mapping (bool => uint256)) list; uint256 length; uint256 index; } /** * @dev returns true if the list exists * @param self stored linked list from contract */ function listExists(LinkedList storage self) internal view returns (bool) { return self.length > 0; } /** * @dev returns true if the node exists * @param self stored linked list from contract * @param _node a node to search for */ function nodeExists(LinkedList storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract */ function sizeOf(LinkedList storage self) internal view returns (uint256 numElements) { return self.length; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get */ function getNode(LinkedList storage self, uint256 _node) public view returns (bool, uint256, uint256) { if (!nodeExists(self,_node)) { return (false, 0, 0); } else { return (true, self.list[_node][PREV], self.list[_node][NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in */ function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) public view returns (bool, uint256) { if (!nodeExists(self,_node)) { return (false,0); } else { return (true,self.list[_node][_direction]); } } /** * @dev Can be used before `insert` to build an ordered list * @param self stored linked list from contract * @param _node an existing node to search from, e.g. HEAD. * @param _value value to seek * @param _direction direction to seek in * @return next first node beyond '_node' in direction `_direction` */ function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction) public view returns (uint256) { if (sizeOf(self) == 0) { return 0; } require((_node == 0) || nodeExists(self,_node)); bool exists; uint256 next; (exists,next) = getAdjacent(self, _node, _direction); while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction]; return next; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node first node for linking * @param _link node to link to in the _direction */ function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in */ function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if(!nodeExists(self,_new) && nodeExists(self,_node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); self.length++; return true; } else { return false; } } /** * @dev removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list */ function remove(LinkedList storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; self.length--; return _node; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _index The node Id * @param _direction push to the head (NEXT) or tail (PREV) */ function add(LinkedList storage self, uint256 _index, bool _direction) internal returns (uint256) { insert(self, HEAD, _index, _direction); return self.index; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _direction push to the head (NEXT) or tail (PREV) */ function push(LinkedList storage self, bool _direction) internal returns (uint256) { self.index++; insert(self, HEAD, self.index, _direction); return self.index; } /** * @dev pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (NEXT) or the tail (PREV) */ function pop(LinkedList storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj; (exists,adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } contract TripioToken { string public name; string public symbol; uint8 public decimals; function transfer(address _to, uint256 _value) public returns (bool); function balanceOf(address who) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); } contract TripioRoomNightData is Owned { using LinkedListLib for LinkedListLib.LinkedList; // Interface signature of erc165. // bytes4(keccak256("supportsInterface(bytes4)")) bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7; // Interface signature of erc721 metadata. // bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)")); bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd; // Interface signature of erc721. // bytes4(keccak256("balanceOf(address)")) ^ // bytes4(keccak256("ownerOf(uint256)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^ // bytes4(keccak256("transferFrom(address,address,uint256)")) ^ // bytes4(keccak256("approve(address,uint256)")) ^ // bytes4(keccak256("setApprovalForAll(address,bool)")) ^ // bytes4(keccak256("getApproved(uint256)")) ^ // bytes4(keccak256("isApprovedForAll(address,address)")); bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5; // Base URI of token asset string public tokenBaseURI; // Authorized contracts struct AuthorizedContract { string name; address acontract; } mapping (address=>uint256) public authorizedContractIds; mapping (uint256 => AuthorizedContract) public authorizedContracts; LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0); // Rate plan prices struct Price { uint16 inventory; // Rate plan inventory bool init; // Whether the price is initied mapping (uint256 => uint256) tokens; } // Vendor hotel RPs struct RatePlan { string name; // Name of rate plan. uint256 timestamp; // Create timestamp. bytes32 ipfs; // The address of rate plan detail on IPFS. Price basePrice; // The base price of rate plan mapping (uint256 => Price) prices; // date -> Price } // Vendors struct Vendor { string name; // Name of vendor. address vendor; // Address of vendor. uint256 timestamp; // Create timestamp. bool valid; // Whether the vendor is valid(default is true) LinkedListLib.LinkedList ratePlanList; mapping (uint256=>RatePlan) ratePlans; } mapping (address => uint256) public vendorIds; mapping (uint256 => Vendor) vendors; LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0); // Supported digital currencies mapping (uint256 => address) public tokenIndexToAddress; LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0); // RoomNight tokens struct RoomNight { uint256 vendorId; uint256 rpid; uint256 token; // The digital currency token uint256 price; // The digital currency price uint256 timestamp; // Create timestamp. uint256 date; // The checkin date bytes32 ipfs; // The address of rate plan detail on IPFS. } RoomNight[] public roomnights; // rnid -> owner mapping (uint256 => address) public roomNightIndexToOwner; // Owner Account mapping (address => LinkedListLib.LinkedList) public roomNightOwners; // Vendor Account mapping (address => LinkedListLib.LinkedList) public roomNightVendors; // The authorized address for each TRN mapping (uint256 => address) public roomNightApprovals; // The authorized operators for each address mapping (address => mapping (address => bool)) public operatorApprovals; // The applications of room night redund mapping (address => mapping (uint256 => bool)) public refundApplications; // The signature of `onERC721Received(address,uint256,bytes)` // bytes4(keccak256("onERC721Received(address,uint256,bytes)")); bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba; /** * This emits when contract authorized */ event ContractAuthorized(address _contract); /** * This emits when contract deauthorized */ event ContractDeauthorized(address _contract); /** * The contract is valid */ modifier authorizedContractValid(address _contract) { require(authorizedContractIds[_contract] > 0); _; } /** * The contract is valid */ modifier authorizedContractIdValid(uint256 _cid) { require(authorizedContractList.nodeExists(_cid)); _; } /** * Only the owner or authorized contract is valid */ modifier onlyOwnerOrAuthorizedContract { require(msg.sender == owner || authorizedContractIds[msg.sender] > 0); _; } /** * Constructor */ constructor() public { // Add one invalid RoomNight, avoid subscript 0 roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0)); } /** * @dev Returns the node list and next node as a tuple * @param self stored linked list from contract * @param _node the begin id of the node to get * @param _limit the total nodes of one page * @param _direction direction to step in */ function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction) private view returns (uint256[], uint256) { bool exists; uint256 i = 0; uint256 ei = 0; uint256 index = 0; uint256 count = _limit; if(count > self.length) { count = self.length; } (exists, i) = self.getAdjacent(_node, _direction); if(!exists || count == 0) { return (new uint256[](0), 0); }else { uint256[] memory temp = new uint256[](count); if(_node != 0) { index++; temp[0] = _node; } while (i != 0 && index < count) { temp[index] = i; (exists,i) = self.getAdjacent(i, _direction); index++; } ei = i; if(index < count) { uint256[] memory result = new uint256[](index); for(i = 0; i < index; i++) { result[i] = temp[i]; } return (result, ei); }else { return (temp, ei); } } } /** * @dev Authorize `_contract` to execute this contract's funs * @param _contract The contract address * @param _name The contract name */ function authorizeContract(address _contract, string _name) public onlyOwner returns(bool) { uint256 codeSize; assembly { codeSize := extcodesize(_contract) } require(codeSize != 0); // Not exists require(authorizedContractIds[_contract] == 0); // Add uint256 id = authorizedContractList.push(false); authorizedContractIds[_contract] = id; authorizedContracts[id] = AuthorizedContract(_name, _contract); // Event emit ContractAuthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by address * @param _contract The contract address */ function deauthorizeContract(address _contract) public onlyOwner authorizedContractValid(_contract) returns(bool) { uint256 id = authorizedContractIds[_contract]; authorizedContractList.remove(id); authorizedContractIds[_contract] = 0; delete authorizedContracts[id]; // Event emit ContractDeauthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by contract id * @param _cid The contract id */ function deauthorizeContractById(uint256 _cid) public onlyOwner authorizedContractIdValid(_cid) returns(bool) { address acontract = authorizedContracts[_cid].acontract; authorizedContractList.remove(_cid); authorizedContractIds[acontract] = 0; delete authorizedContracts[_cid]; // Event emit ContractDeauthorized(acontract); return true; } /** * @dev Get authorize contract ids by page * @param _from The begin authorize contract id * @param _limit How many authorize contract ids one page * @return The authorize contract ids and the next authorize contract id as tuple, the next page not exists when next eq 0 */ function getAuthorizeContractIds(uint256 _from, uint256 _limit) external view returns(uint256[], uint256){ return getNodes(authorizedContractList, _from, _limit, true); } /** * @dev Get authorize contract by id * @param _cid Then authorize contract id * @return The authorize contract info(_name, _acontract) */ function getAuthorizeContract(uint256 _cid) external view returns(string _name, address _acontract) { AuthorizedContract memory acontract = authorizedContracts[_cid]; _name = acontract.name; _acontract = acontract.acontract; } /*************************************** GET ***************************************/ /** * @dev Get the rate plan by `_vendorId` and `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function getRatePlan(uint256 _vendorId, uint256 _rpid) public view returns (string _name, uint256 _timestamp, bytes32 _ipfs) { _name = vendors[_vendorId].ratePlans[_rpid].name; _timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp; _ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs; } /** * @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId) public view returns(uint16 _inventory, bool _init, uint256 _price) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; _price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId]; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; _price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; _init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } } /** * @dev Get the rate plan prices by `_vendorId`, `_rpid`, `_dates` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _dates The dates desc ([20180723,20180724,20180725]) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId) public view returns(uint16[] _inventories, uint256[] _prices) { uint16[] memory inventories = new uint16[](_dates.length); uint256[] memory prices = new uint256[](_dates.length); uint256 date; for(uint256 i = 0; i < _dates.length; i++) { date = _dates[i]; uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory; bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init; uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId]; if(!init) { // Get the base price inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } inventories[i] = inventory; prices[i] = price; } return (inventories, prices); } /** * @dev Get the inventory by by `_vendorId`, `_rpid` and `_date` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @return The inventory info(inventory, init) */ function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date) public view returns(uint16 _inventory, bool _init) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; } } /** * @dev Whether the rate plan is exist * @param _vendorId The vendor id * @param _rpid The rate plan id * @return If the rate plan of the vendor is exist returns true otherwise return false */ function ratePlanIsExist(uint256 _vendorId, uint256 _rpid) public view returns (bool) { return vendors[_vendorId].ratePlanList.nodeExists(_rpid); } /** * @dev Get orders of owner by page * @param _owner The owner address * @param _from The begin id of the node to get * @param _limit The total nodes of one page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightOwners[_owner], _from, _limit, _direction); } /** * @dev Get orders of vendor by page * @param _owner The vendor address * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightVendors[_owner], _from, _limit, _direction); } /** * @dev Get the token count of somebody * @param _owner The owner of token * @return The token count of `_owner` */ function balanceOf(address _owner) public view returns(uint256) { return roomNightOwners[_owner].length; } /** * @dev Get rate plan ids of `_vendorId` * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The rate plan ids and the next id */ function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction); } /** * @dev Get token ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The token ids and the next id */ function getTokens(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(tokenList, _from, _limit, _direction); } /** * @dev Get token Info * @param _tokenId The token id * @return The token info(symbol, name, decimals) */ function getToken(uint256 _tokenId) public view returns(string _symbol, string _name, uint8 _decimals, address _token) { _token = tokenIndexToAddress[_tokenId]; TripioToken tripio = TripioToken(_token); _symbol = tripio.symbol(); _name = tripio.name(); _decimals = tripio.decimals(); } /** * @dev Get vendor ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The vendor ids and the next id */ function getVendors(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendorList, _from, _limit, _direction); } /** * @dev Get the vendor infomation by vendorId * @param _vendorId The vendor id * @return The vendor infomation(name, vendor, timestamp, valid) */ function getVendor(uint256 _vendorId) public view returns(string _name, address _vendor,uint256 _timestamp, bool _valid) { _name = vendors[_vendorId].name; _vendor = vendors[_vendorId].vendor; _timestamp = vendors[_vendorId].timestamp; _valid = vendors[_vendorId].valid; } /*************************************** SET ***************************************/ /** * @dev Update base uri of token metadata * @param _tokenBaseURI The base uri */ function updateTokenBaseURI(string _tokenBaseURI) public onlyOwnerOrAuthorizedContract { tokenBaseURI = _tokenBaseURI; } /** * @dev Push order to user's order list * @param _owner The buyer address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightOwners[_owner].listExists()) { roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0); } roomNightOwners[_owner].add(_rnid, _direction); } /** * @dev Remove order from owner's order list * @param _owner The owner address * @param _rnid The room night order id */ function removeOrderOfOwner(address _owner, uint _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightOwners[_owner].nodeExists(_rnid)); roomNightOwners[_owner].remove(_rnid); } /** * @dev Push order to the vendor's order list * @param _vendor The vendor address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightVendors[_vendor].listExists()) { roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0); } roomNightVendors[_vendor].add(_rnid, _direction); } /** * @dev Remove order from vendor's order list * @param _vendor The vendor address * @param _rnid The room night order id */ function removeOrderOfVendor(address _vendor, uint256 _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightVendors[_vendor].nodeExists(_rnid)); roomNightVendors[_vendor].remove(_rnid); } /** * @dev Transfer token to somebody * @param _tokenId The token id * @param _to The target owner of the token */ function transferTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightIndexToOwner[_tokenId] = _to; roomNightApprovals[_tokenId] = address(0); } /** * @dev Approve `_to` to operate the `_tokenId` * @param _tokenId The token id * @param _to Somebody to be approved */ function approveTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightApprovals[_tokenId] = _to; } /** * @dev Approve `_operator` to operate all the Token of `_to` * @param _operator The operator to be approved * @param _to The owner of tokens to be operate * @param _approved Approved or not */ function approveOperatorTo(address _operator, address _to, bool _approved) public onlyOwnerOrAuthorizedContract { operatorApprovals[_to][_operator] = _approved; } /** * @dev Update base price of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _tokenId The digital token id * @param _price The price to be updated */ function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.init = true; vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price; } /** * @dev Update base inventory of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _inventory The inventory to be updated */ function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory; } /** * @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated */ function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Update inventory by `_vendorId`, `_rpid`, `_date`, `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The inventory to be updated */ function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); } } /** * @dev Reduce inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be reduced */ function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 a = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){ a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory; } } /** * @dev Add inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be add */ function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 c = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c; } } /** * @dev Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated * @param _inventory The inventory to be updated */ function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Push rate plan to `_vendorId`'s rate plan list * @param _vendorId The vendor id * @param _name The name of rate plan * @param _ipfs The rate plan IPFS address * @param _direction direction to step in */ function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false)); uint256 id = vendors[_vendorId].ratePlanList.push(_direction); vendors[_vendorId].ratePlans[id] = rp; return id; } /** * @dev Remove rate plan of `_vendorId` by `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function removeRatePlan(uint256 _vendorId, uint256 _rpid) public onlyOwnerOrAuthorizedContract { delete vendors[_vendorId].ratePlans[_rpid]; vendors[_vendorId].ratePlanList.remove(_rpid); } /** * @dev Update `_rpid` of `_vendorId` by `_name` and `_ipfs` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _name The rate plan name * @param _ipfs The rate plan IPFS address */ function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs; vendors[_vendorId].ratePlans[_rpid].name = _name; } /** * @dev Push token contract to the token list * @param _direction direction to step in */ function pushToken(address _contract, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = tokenList.push(_direction); tokenIndexToAddress[id] = _contract; return id; } /** * @dev Remove token by `_tokenId` * @param _tokenId The digital token id */ function removeToken(uint256 _tokenId) public onlyOwnerOrAuthorizedContract { delete tokenIndexToAddress[_tokenId]; tokenList.remove(_tokenId); } /** * @dev Generate room night token * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _token The token id * @param _price The token price * @param _ipfs The rate plan IPFS address */ function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract returns(uint256) { roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs)); // Give the token to `_customer` uint256 rnid = uint256(roomnights.length - 1); return rnid; } /** * @dev Update refund applications * @param _buyer The room night token holder * @param _rnid The room night token id * @param _isRefund Is redund or not */ function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund) public onlyOwnerOrAuthorizedContract { refundApplications[_buyer][_rnid] = _isRefund; } /** * @dev Push vendor info to the vendor list * @param _name The name of vendor * @param _vendor The vendor address * @param _direction direction to step in */ function pushVendor(string _name, address _vendor, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = vendorList.push(_direction); vendorIds[_vendor] = id; vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0)); return id; } /** * @dev Remove vendor from vendor list * @param _vendorId The vendor id */ function removeVendor(uint256 _vendorId) public onlyOwnerOrAuthorizedContract { vendorList.remove(_vendorId); address vendor = vendors[_vendorId].vendor; vendorIds[vendor] = 0; delete vendors[_vendorId]; } /** * @dev Make vendor valid or invalid * @param _vendorId The vendor id * @param _valid The vendor is valid or not */ function updateVendorValid(uint256 _vendorId, bool _valid) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].valid = _valid; } /** * @dev Modify vendor's name * @param _vendorId The vendor id * @param _name Then vendor name */ function updateVendorName(uint256 _vendorId, string _name) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].name = _name; } } contract TRNRatePlans is TRNData { /** * Constructor */ constructor() public { } /** * This emits when rate plan created */ event RatePlanCreated(address indexed _vendor, string _name, bytes32 indexed _ipfs); /** * This emits when rate plan removed */ event RatePlanRemoved(address indexed _vendor, uint256 indexed _rpid); /** * This emits when rate plan modified */ event RatePlanModified(address indexed _vendor, uint256 indexed _rpid, string name, bytes32 _ipfs); /** * @dev Create rate plan * Only vendor can operate * Throw when `_name`'s length lte 0 or mte 100. * @param _name The name of rate plan * @param _ipfs The address of the rate plan detail info on IPFS. */ function createRatePlan(string _name, bytes32 _ipfs) external // onlyVendor returns(uint256) { // if vendor not exist create it if(dataSource.vendorIds(msg.sender) == 0) { dataSource.pushVendor("", msg.sender, false); } bytes memory nameBytes = bytes(_name); require(nameBytes.length > 0 && nameBytes.length < 200); uint256 vendorId = dataSource.vendorIds(msg.sender); uint256 id = dataSource.pushRatePlan(vendorId, _name, _ipfs, false); // Event emit RatePlanCreated(msg.sender, _name, _ipfs); return id; } /** * @dev Remove rate plan * Only vendor can operate * Throw when `_rpid` not exist * @param _rpid The rate plan identifier */ function removeRatePlan(uint256 _rpid) external onlyVendor ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { uint256 vendorId = dataSource.vendorIds(msg.sender); // Delete rate plan dataSource.removeRatePlan(vendorId, _rpid); // Event emit RatePlanRemoved(msg.sender, _rpid); return true; } /** * @dev Modify rate plan * Throw when `_rpid` not exist * @param _rpid The rate plan identifier * @param _ipfs The address of the rate plan detail info on IPFS */ function modifyRatePlan(uint256 _rpid, string _name, bytes32 _ipfs) external onlyVendor ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { uint256 vendorId = dataSource.vendorIds(msg.sender); dataSource.updateRatePlan(vendorId, _rpid, _name, _ipfs); // Event emit RatePlanModified(msg.sender, _rpid, _name, _ipfs); return true; } /** * @dev Returns a list of all rate plan IDs assigned to a vendor. * @param _vendorId The Id of vendor * @param _from The begin ratePlan Id * @param _limit How many ratePlan Ids one page * @return A list of all rate plan IDs assigned to a vendor */ function ratePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit) external view vendorIdValid(_vendorId) returns(uint256[], uint256) { return dataSource.getRatePlansOfVendor(_vendorId, _from, _limit, true); } /** * @dev Returns ratePlan info of vendor * @param _vendorId The address of vendor * @param _rpid The ratePlan id * @return The ratePlan info(_name, _timestamp, _ipfs) */ function ratePlanOfVendor(uint256 _vendorId, uint256 _rpid) external view vendorIdValid(_vendorId) returns(string _name, uint256 _timestamp, bytes32 _ipfs) { (_name, _timestamp, _ipfs) = dataSource.getRatePlan(_vendorId, _rpid); } } contract TripioRoomNightVendor is TRNPrices, TRNRatePlans { /** * Constructor */ constructor(address _dataSource) public { // Init the data source dataSource = TripioRoomNightData(_dataSource); } /** * @dev Destory the contract */ function destroy() external onlyOwner { selfdestruct(owner); } }
Returns the inventories of `_vendor`'s RP(`_rpid`) on `_dates` Throw when `_rpid` not exist Throw when `_dates`'s count lte 0 _vendorId The vendor Id _rpid The rate plan identifier _dates The inventories to be returned of `_dates` return The inventories/
function inventoriesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates) external view ratePlanExist(_vendorId, _rpid) returns(uint16[]) { require(_dates.length > 0); uint16[] memory result = new uint16[](_dates.length); for (uint256 index = 0; index < _dates.length; index++) { uint256 date = _dates[index]; (uint16 inventory,) = dataSource.getInventory(_vendorId, _rpid, date); result[index] = inventory; } return result; }
10,201,756
pragma solidity 0.4.23; /** @title DegreeRequests*/ contract DegreeRequests { mapping(address => DegreeRequest) private studentContractToRequest; mapping(uint => address) private intToSudent; mapping(address => uint) private studentToInt; uint private last = 0; // first free slot address private adminFacade; address private studentFacade; struct DegreeRequest { bytes thesisTitle; int8 requestState; // in pending = 0 acceppted = 1 o rejected = -1 bytes submmissionDate; address professorContract; } /** @dev Check if the the sender is the admin facade.*/ modifier onlyAdmin() { require(msg.sender == adminFacade); _; } /** @dev Check if the the sender is the student facade.*/ modifier onlyStudent() { require(msg.sender == studentFacade); _; } /** @dev Check if the student doesn't have a pending degree request. * @param studentContract address of the student contract. */ modifier onlyNewRequest(address studentContract) { require(studentToInt[studentContract] == 0); _; } /** dev Constructor of admin facade initialize the adminFacade field with msg.sender. */ constructor() public { adminFacade = msg.sender; } /** @dev Change the two accounts with write permissions on the contract storage. * @param newAdmin address of the new admin. * @param newStudent address of the new student. */ function changeOwners(address newAdmin, address newStudent) public onlyAdmin() { if (newAdmin != address(0) && newStudent != address(0)) { adminFacade = newAdmin; studentFacade = newStudent; } } /** @dev Add a degree request to the mapping. * @param studentContract address of the student contract creating the degree request. * @param thesisTitle title of the student thesis. * @param submmissionDate date of the subbmission of the degree request. * @param professorContract address of the contract of the professor. */ function addRequest(address studentContract, bytes thesisTitle, bytes submmissionDate, address professorContract) public onlyStudent() onlyNewRequest(studentContract) { studentContractToRequest[studentContract] = DegreeRequest(thesisTitle, 0, submmissionDate, professorContract); studentToInt[studentContract] = last; intToSudent[last] = studentContract; last += 1; } /** @dev return the number of pending requests. * @return uint number of pending requests. */ function pendingDegreeRequestNumber() public view returns(uint) { return last; } /** @dev Change the state of the degree request. * @param newState int8 rapresenting the new state of the request. * @param request index of the degree request. */ function manageRequest(int8 newState, uint request) public onlyAdmin() { require(newState == -1 || newState == 1); require(request < last); address stdCont = intToSudent[request]; studentContractToRequest[stdCont].requestState = newState; studentToInt[stdCont] = 0; intToSudent[request] = intToSudent[last]; last -= 1; } /** @dev return the degree request given an index. * @param index uint of the degree request. * @return bytes title of the thesis. * @return int8 state of the degree request. * @return bytes date of submission of the request. * @return address address of the professor contract. */ function getDegreeRequestIndex(uint index) public view returns( bytes, int8, bytes, address) { require(index < last); address stdCont = intToSudent[index]; DegreeRequest memory request = studentContractToRequest[stdCont]; return ( request.thesisTitle, request.requestState, request.submmissionDate, request.professorContract); } /** @dev return the degree request given a student address. * @param studentContract address of the student of the degree request. * @return bytes title of the thesis. * @return int8 state of the degree request. * @return bytes date of submission of the request. * @return address address of the professor contract. */ function getDegreeRequest(address studentContract) public view returns( bytes, int8, bytes, address) { require(studentContractToRequest[studentContract].professorContract != 0x0); DegreeRequest memory request = studentContractToRequest[studentContract]; return ( request.thesisTitle, request.requestState, request.submmissionDate, request.professorContract); } }
Add a degree request to the mapping. studentContract address of the student contract creating the degree request. thesisTitle title of the student thesis. submmissionDate date of the subbmission of the degree request. professorContract address of the contract of the professor./
function addRequest(address studentContract, bytes thesisTitle, bytes submmissionDate, address professorContract) public onlyStudent() onlyNewRequest(studentContract) { studentContractToRequest[studentContract] = DegreeRequest(thesisTitle, 0, submmissionDate, professorContract); studentToInt[studentContract] = last; intToSudent[last] = studentContract; last += 1; }
5,467,223
./full_match/1/0x15480f5B5ED98A94e1d36b52Dd20e9a35453A38e/sources/contracts/mixins/Auth.sol
==== System-wide views ==== returns: bool(main is frozen) == now < unfreezeAt
function frozen() public view returns (bool) { return block.timestamp < unfreezeAt; }
4,999,838
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { 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 AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; 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.7.5; /** * @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: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; /** * @title SP1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contracts with storage. */ abstract contract SP1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Modifiers ============ /** * @dev Modifier to ensure the STARK key is allowed. */ modifier onlyAllowedKey( uint256 starkKey ) { require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Storage: STARK key is not on the allowlist'); _; } /** * @dev Modifier to ensure the recipient is allowed. */ modifier onlyAllowedRecipient( address recipient ) { require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Storage: Recipient is not on the allowlist'); _; } // ============ Storage ============ mapping(uint256 => bool) internal _ALLOWED_STARK_KEYS_; mapping(address => bool) internal _ALLOWED_RECIPIENTS_; /// @dev Note that withdrawals are always permitted if the amount is in excess of the borrowed /// amount. Also, this approval only applies to the primary ERC20 token, `TOKEN`. uint256 internal _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_; /// @dev Note that this is different from _IS_BORROWING_RESTRICTED_ in LiquidityStakingV1. bool internal _IS_BORROWING_RESTRICTED_; /// @dev Mapping from args hash to timestamp. mapping(bytes32 => uint256) internal _QUEUED_FORCED_TRADE_TIMESTAMPS_; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @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. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { SP1Storage } from './SP1Storage.sol'; /** * @title SP1Getters * @author dYdX * * @dev Simple external getter functions. */ abstract contract SP1Getters is SP1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice Check whether a STARK key is on the allowlist for exchange operations. * * @param starkKey The STARK key to check. * * @return Boolean `true` if the STARK key is allowed, otherwise `false`. */ function isStarkKeyAllowed( uint256 starkKey ) external view returns (bool) { return _ALLOWED_STARK_KEYS_[starkKey]; } /** * @notice Check whether a recipient is on the allowlist to receive withdrawals. * * @param recipient The recipient to check. * * @return Boolean `true` if the recipient is allowed, otherwise `false`. */ function isRecipientAllowed( address recipient ) external view returns (bool) { return _ALLOWED_RECIPIENTS_[recipient]; } /** * @notice Get the amount approved by the guardian for external withdrawals. * Note that withdrawals are always permitted if the amount is in excess of the borrowed amount. * * @return The amount approved for external withdrawals. */ function getApprovedAmountForExternalWithdrawal() external view returns (uint256) { return _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_; } /** * @notice Check whether this borrower contract is restricted from new borrowing, as well as * restricted from depositing borrowed funds to the exchange. * * @return Boolean `true` if the borrower is restricted, otherwise `false`. */ function isBorrowingRestricted() external view returns (bool) { return _IS_BORROWING_RESTRICTED_; } /** * @notice Get the timestamp at which a forced trade request was queued. * * @param argsHash The hash of the forced trade request args. * * @return Timestamp at which the forced trade was queued, or zero, if it was not queued or was * vetoed by the VETO_GUARDIAN_ROLE. */ function getQueuedForcedTradeTimestamp( bytes32 argsHash ) external view returns (uint256) { return _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash]; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { IERC20 } from '../../interfaces/IERC20.sol'; import { ILiquidityStakingV1 } from '../../interfaces/ILiquidityStakingV1.sol'; import { IMerkleDistributorV1 } from '../../interfaces/IMerkleDistributorV1.sol'; import { IStarkPerpetual } from '../../interfaces/IStarkPerpetual.sol'; import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol'; import { SP1Withdrawals } from './impl/SP1Withdrawals.sol'; import { SP1Getters } from './impl/SP1Getters.sol'; import { SP1Guardian } from './impl/SP1Guardian.sol'; import { SP1Owner } from './impl/SP1Owner.sol'; /** * @title StarkProxyV1 * @author dYdX * * @notice Proxy contract allowing a LiquidityStaking borrower to use borrowed funds (as well as * their own funds, if desired) on the dYdX L2 exchange. Restrictions are put in place to * prevent borrowed funds being used outside the exchange. Furthermore, a guardian address is * specified which has the ability to restrict borrows and make repayments. * * Owner actions may be delegated to various roles as defined in SP1Roles. Other actions are * available to guardian roles, to be nominated by dYdX governance. */ contract StarkProxyV1 is SP1Guardian, SP1Owner, SP1Withdrawals, SP1Getters { using SafeERC20 for IERC20; // ============ Constructor ============ constructor( ILiquidityStakingV1 liquidityStaking, IStarkPerpetual starkPerpetual, IERC20 token, IMerkleDistributorV1 merkleDistributor ) SP1Guardian(liquidityStaking, starkPerpetual, token) SP1Withdrawals(merkleDistributor) {} // ============ External Functions ============ function initialize(address guardian) external initializer { __SP1Roles_init(guardian); TOKEN.safeApprove(address(LIQUIDITY_STAKING), uint256(-1)); TOKEN.safeApprove(address(STARK_PERPETUAL), uint256(-1)); } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 1; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ILiquidityStakingV1 * @author dYdX * * @notice Partial interface for LiquidityStakingV1. */ interface ILiquidityStakingV1 { function getToken() external view virtual returns (address); function getBorrowedBalance(address borrower) external view virtual returns (uint256); function getBorrowerDebtBalance(address borrower) external view virtual returns (uint256); function isBorrowingRestrictedForBorrower(address borrower) external view virtual returns (bool); function getTimeRemainingInEpoch() external view virtual returns (uint256); function inBlackoutWindow() external view virtual returns (bool); // LS1Borrowing function borrow(uint256 amount) external virtual; function repayBorrow(address borrower, uint256 amount) external virtual; function getAllocatedBalanceCurrentEpoch(address borrower) external view virtual returns (uint256); function getAllocatedBalanceNextEpoch(address borrower) external view virtual returns (uint256); function getBorrowableAmount(address borrower) external view virtual returns (uint256); // LS1DebtAccounting function repayDebt(address borrower, uint256 amount) external virtual; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title IMerkleDistributorV1 * @author dYdX * * @notice Partial interface for the MerkleDistributorV1 contract. */ interface IMerkleDistributorV1 { function getIpnsName() external virtual view returns (string memory); function getRewardsParameters() external virtual view returns (uint256, uint256, uint256); function getActiveRoot() external virtual view returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid); function getNextRootEpoch() external virtual view returns (uint256); function claimRewards( uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title IStarkPerpetual * @author dYdX * * @notice Partial interface for the StarkPerpetual contract, for accessing the dYdX L2 exchange. * @dev See https://github.com/starkware-libs/starkex-contracts */ interface IStarkPerpetual { function registerUser( address ethKey, uint256 starkKey, bytes calldata signature ) external; function deposit( uint256 starkKey, uint256 assetType, uint256 vaultId, uint256 quantizedAmount ) external; function withdraw(uint256 starkKey, uint256 assetType) external; function forcedWithdrawalRequest( uint256 starkKey, uint256 vaultId, uint256 quantizedAmount, bool premiumCost ) external; function forcedTradeRequest( uint256 starkKeyA, uint256 starkKeyB, uint256 vaultIdA, uint256 vaultIdB, uint256 collateralAssetId, uint256 syntheticAssetId, uint256 amountCollateral, uint256 amountSynthetic, bool aIsBuyingSynthetic, uint256 submissionExpirationTime, uint256 nonce, bytes calldata signature, bool premiumCost ) external; function mainAcceptGovernance() external; function proxyAcceptGovernance() external; function mainRemoveGovernor(address governorForRemoval) external; function proxyRemoveGovernor(address governorForRemoval) external; function registerAssetConfigurationChange(uint256 assetId, bytes32 configHash) external; function applyAssetConfigurationChange(uint256 assetId, bytes32 configHash) external; function registerGlobalConfigurationChange(bytes32 configHash) external; function applyGlobalConfigurationChange(bytes32 configHash) external; function getEthKey(uint256 starkKey) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { 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 callOptionalReturn(IERC20 token, bytes memory data) private { 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'); } } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IMerkleDistributorV1 } from '../../../interfaces/IMerkleDistributorV1.sol'; import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol'; import { SP1Exchange } from './SP1Exchange.sol'; /** * @title SP1Withdrawals * @author dYdX * * @dev Actions which may be called only by WITHDRAWAL_OPERATOR_ROLE. Allows for withdrawing * funds from the contract to external addresses that were approved by OWNER_ROLE. */ abstract contract SP1Withdrawals is SP1Exchange { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ IMerkleDistributorV1 public immutable MERKLE_DISTRIBUTOR; // ============ Events ============ event ExternalWithdrewToken( address recipient, uint256 amount ); event ExternalWithdrewOtherToken( address token, address recipient, uint256 amount ); event ExternalWithdrewEther( address recipient, uint256 amount ); // ============ Constructor ============ constructor( IMerkleDistributorV1 merkleDistributor ) { MERKLE_DISTRIBUTOR = merkleDistributor; } // ============ External Functions ============ /** * @notice Claim rewards from the Merkle distributor. They will be held in this contract until * withdrawn by the WITHDRAWAL_OPERATOR_ROLE. * * @param cumulativeAmount The total all-time rewards this contract has earned. * @param merkleProof The Merkle proof for this contract address and cumulative amount. * * @return The amount of new reward received. */ function claimRewardsFromMerkleDistributor( uint256 cumulativeAmount, bytes32[] calldata merkleProof ) external nonReentrant onlyRole(WITHDRAWAL_OPERATOR_ROLE) returns (uint256) { return MERKLE_DISTRIBUTOR.claimRewards(cumulativeAmount, merkleProof); } /** * @notice Withdraw a token amount in excess of the borrowed balance, or an amount approved by * the GUARDIAN_ROLE. * * The contract may hold an excess balance if, for example, additional funds were added by the * contract owner for use with the same exchange account, or if profits were earned from * activity on the exchange. * * @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE. */ function externalWithdrawToken( address recipient, uint256 amount ) external nonReentrant onlyRole(WITHDRAWAL_OPERATOR_ROLE) onlyAllowedRecipient(recipient) { // If we are approved for the full amount, then skip the borrowed balance check. uint256 approvedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_; if (approvedAmount >= amount) { _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = approvedAmount.sub(amount); } else { uint256 owedBalance = getBorrowedAndDebtBalance(); uint256 tokenBalance = getTokenBalance(); require(tokenBalance > owedBalance, 'SP1Withdrawals: No withdrawable balance'); uint256 availableBalance = tokenBalance.sub(owedBalance); require(amount <= availableBalance, 'SP1Withdrawals: Amount exceeds withdrawable balance'); // Always decrease the approval amount. _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0; } TOKEN.safeTransfer(recipient, amount); emit ExternalWithdrewToken(recipient, amount); } /** * @notice Withdraw any ERC20 token balance other than the token used for borrowing. * * @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE. */ function externalWithdrawOtherToken( address token, address recipient, uint256 amount ) external nonReentrant onlyRole(WITHDRAWAL_OPERATOR_ROLE) onlyAllowedRecipient(recipient) { require( token != address(TOKEN), 'SP1Withdrawals: Cannot use this function to withdraw borrowed token' ); IERC20(token).safeTransfer(recipient, amount); emit ExternalWithdrewOtherToken(token, recipient, amount); } /** * @notice Withdraw any ether. * * Note: The contract is not expected to hold Ether so this is not normally needed. * * @param recipient The recipient to receive Ether. Must be authorized by OWNER_ROLE. */ function externalWithdrawEther( address recipient, uint256 amount ) external nonReentrant onlyRole(WITHDRAWAL_OPERATOR_ROLE) onlyAllowedRecipient(recipient) { payable(recipient).transfer(amount); emit ExternalWithdrewEther(recipient, amount); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol'; import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol'; import { SP1Borrowing } from './SP1Borrowing.sol'; import { SP1Exchange } from './SP1Exchange.sol'; /** * @title SP1Guardian * @author dYdX * * @dev Defines guardian powers, to be owned or delegated by dYdX governance. */ abstract contract SP1Guardian is SP1Borrowing, SP1Exchange { using SafeMath for uint256; // ============ Events ============ event BorrowingRestrictionChanged( bool isBorrowingRestricted ); event GuardianVetoedForcedTradeRequest( bytes32 argsHash ); event GuardianUpdateApprovedAmountForExternalWithdrawal( uint256 amount ); // ============ Constructor ============ constructor( ILiquidityStakingV1 liquidityStaking, IStarkPerpetual starkPerpetual, IERC20 token ) SP1Borrowing(liquidityStaking, token) SP1Exchange(starkPerpetual) {} // ============ External Functions ============ /** * @notice Approve an additional amount for external withdrawal by WITHDRAWAL_OPERATOR_ROLE. * * @param amount The additional amount to approve for external withdrawal. * * @return The new amount approved for external withdrawal. */ function increaseApprovedAmountForExternalWithdrawal( uint256 amount ) external nonReentrant onlyRole(GUARDIAN_ROLE) returns (uint256) { uint256 newApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_.add( amount ); _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = newApprovedAmount; emit GuardianUpdateApprovedAmountForExternalWithdrawal(newApprovedAmount); return newApprovedAmount; } /** * @notice Set the approved amount for external withdrawal to zero. * * @return The amount that was previously approved for external withdrawal. */ function resetApprovedAmountForExternalWithdrawal() external nonReentrant onlyRole(GUARDIAN_ROLE) returns (uint256) { uint256 previousApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_; _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0; emit GuardianUpdateApprovedAmountForExternalWithdrawal(0); return previousApprovedAmount; } /** * @notice Guardian method to restrict borrowing or depositing borrowed funds to the exchange. */ function guardianSetBorrowingRestriction( bool isBorrowingRestricted ) external nonReentrant onlyRole(GUARDIAN_ROLE) { _IS_BORROWING_RESTRICTED_ = isBorrowingRestricted; emit BorrowingRestrictionChanged(isBorrowingRestricted); } /** * @notice Guardian method to repay this contract's borrowed balance, using this contract's funds. * * @param amount Amount to repay. */ function guardianRepayBorrow( uint256 amount ) external nonReentrant onlyRole(GUARDIAN_ROLE) { _repayBorrow(amount, true); } /** * @notice Guardian method to repay a debt balance owed by the borrower. * * @param amount Amount to repay. */ function guardianRepayDebt( uint256 amount ) external nonReentrant onlyRole(GUARDIAN_ROLE) { _repayDebt(amount, true); } /** * @notice Guardian method to trigger a withdrawal. This will transfer funds from StarkPerpetual * to this contract. This requires a (slow) withdrawal from L2 to have been previously processed. * * Note: This function is intentionally not protected by the onlyAllowedKey modifier. * * @return The ERC20 token amount received by this contract. */ function guardianWithdrawFromExchange( uint256 starkKey, uint256 assetType ) external nonReentrant onlyRole(GUARDIAN_ROLE) returns (uint256) { return _withdrawFromExchange(starkKey, assetType, true); } /** * @notice Guardian method to trigger a forced withdrawal request. * Reverts if the borrower has no overdue debt. * * Note: This function is intentionally not protected by the onlyAllowedKey modifier. */ function guardianForcedWithdrawalRequest( uint256 starkKey, uint256 vaultId, uint256 quantizedAmount, bool premiumCost ) external nonReentrant onlyRole(GUARDIAN_ROLE) { require( getDebtBalance() > 0, 'SP1Guardian: Cannot call forced action if borrower has no overdue debt' ); _forcedWithdrawalRequest( starkKey, vaultId, quantizedAmount, premiumCost, true // isGuardianAction ); } /** * @notice Guardian method to trigger a forced trade request. * Reverts if the borrower has no overdue debt. * * Note: This function is intentionally not protected by the onlyAllowedKey modifier. */ function guardianForcedTradeRequest( uint256[12] calldata args, bytes calldata signature ) external nonReentrant onlyRole(GUARDIAN_ROLE) { require( getDebtBalance() > 0, 'SP1Guardian: Cannot call forced action if borrower has no overdue debt' ); _forcedTradeRequest(args, signature, true); } /** * @notice Guardian method to prevent queued forced trade requests from being executed. * * May only be called by VETO_GUARDIAN_ROLE. * * @param argsHashes An array of hashes for each forced trade request to veto. */ function guardianVetoForcedTradeRequests( bytes32[] calldata argsHashes ) external nonReentrant onlyRole(VETO_GUARDIAN_ROLE) { for (uint256 i = 0; i < argsHashes.length; i++) { bytes32 argsHash = argsHashes[i]; _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0; emit GuardianVetoedForcedTradeRequest(argsHash); } } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol'; import { SP1Borrowing } from './SP1Borrowing.sol'; import { SP1Exchange } from './SP1Exchange.sol'; /** * @title SP1Owner * @author dYdX * * @dev Actions which may be called only by OWNER_ROLE. These include actions with a larger amount * of control over the funds held by the contract. */ abstract contract SP1Owner is SP1Borrowing, SP1Exchange { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice Time that must elapse before a queued forced trade request can be submitted. uint256 public constant FORCED_TRADE_WAITING_PERIOD = 7 days; /// @notice Max time that may elapse after the waiting period before a queued forced trade /// request expires. uint256 public constant FORCED_TRADE_GRACE_PERIOD = 7 days; // ============ Events ============ event UpdatedStarkKey( uint256 starkKey, bool isAllowed ); event UpdatedExternalRecipient( address recipient, bool isAllowed ); event QueuedForcedTradeRequest( uint256[12] args, bytes32 argsHash ); // ============ External Functions ============ /** * @notice Allow exchange functions to be called for a particular STARK key. * * Will revert if the STARK key is not registered to this contract's address on the * StarkPerpetual contract. * * @param starkKey The STARK key to allow. */ function allowStarkKey( uint256 starkKey ) external nonReentrant onlyRole(OWNER_ROLE) { // This will revert with 'USER_UNREGISTERED' if the STARK key was not registered. address ethKey = STARK_PERPETUAL.getEthKey(starkKey); // Require the STARK key to be registered to this contract before we allow it to be used. require(ethKey == address(this), 'SP1Owner: STARK key not registered to this contract'); require(!_ALLOWED_STARK_KEYS_[starkKey], 'SP1Owner: STARK key already allowed'); _ALLOWED_STARK_KEYS_[starkKey] = true; emit UpdatedStarkKey(starkKey, true); } /** * @notice Remove a STARK key from the allowed list. * * @param starkKey The STARK key to disallow. */ function disallowStarkKey( uint256 starkKey ) external nonReentrant onlyRole(OWNER_ROLE) { require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Owner: STARK key already disallowed'); _ALLOWED_STARK_KEYS_[starkKey] = false; emit UpdatedStarkKey(starkKey, false); } /** * @notice Allow withdrawals of excess funds to be made to a particular recipient. * * @param recipient The recipient to allow. */ function allowExternalRecipient( address recipient ) external nonReentrant onlyRole(OWNER_ROLE) { require(!_ALLOWED_RECIPIENTS_[recipient], 'SP1Owner: Recipient already allowed'); _ALLOWED_RECIPIENTS_[recipient] = true; emit UpdatedExternalRecipient(recipient, true); } /** * @notice Remove a recipient from the allowed list. * * @param recipient The recipient to disallow. */ function disallowExternalRecipient( address recipient ) external nonReentrant onlyRole(OWNER_ROLE) { require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Owner: Recipient already disallowed'); _ALLOWED_RECIPIENTS_[recipient] = false; emit UpdatedExternalRecipient(recipient, false); } /** * @notice Set ERC20 token allowance for the exchange contract. * * @param token The ERC20 token to set the allowance for. * @param amount The new allowance amount. */ function setExchangeContractAllowance( address token, uint256 amount ) external nonReentrant onlyRole(OWNER_ROLE) { // SafeERC20 safeApprove requires setting to zero first. IERC20(token).safeApprove(address(STARK_PERPETUAL), 0); IERC20(token).safeApprove(address(STARK_PERPETUAL), amount); } /** * @notice Set ERC20 token allowance for the staking contract. * * @param token The ERC20 token to set the allowance for. * @param amount The new allowance amount. */ function setStakingContractAllowance( address token, uint256 amount ) external nonReentrant onlyRole(OWNER_ROLE) { // SafeERC20 safeApprove requires setting to zero first. IERC20(token).safeApprove(address(LIQUIDITY_STAKING), 0); IERC20(token).safeApprove(address(LIQUIDITY_STAKING), amount); } /** * @notice Request a forced withdrawal from the exchange. * * @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE. * @param vaultId The exchange position ID for the account to deposit to. * @param quantizedAmount The withdrawal amount denominated in the exchange base units. * @param premiumCost Whether to pay a higher fee for faster inclusion in certain scenarios. */ function forcedWithdrawalRequest( uint256 starkKey, uint256 vaultId, uint256 quantizedAmount, bool premiumCost ) external nonReentrant onlyRole(OWNER_ROLE) onlyAllowedKey(starkKey) { _forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost, false); } /** * @notice Queue a forced trade request to be submitted after the waiting period. * * @param args Arguments for the forced trade request. */ function queueForcedTradeRequest( uint256[12] calldata args ) external nonReentrant onlyRole(OWNER_ROLE) { bytes32 argsHash = keccak256(abi.encodePacked(args)); _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = block.timestamp; emit QueuedForcedTradeRequest(args, argsHash); } /** * @notice Submit a forced trade request that was previously queued. * * @param args Arguments for the forced trade request. * @param signature The signature of the counterparty to the trade. */ function forcedTradeRequest( uint256[12] calldata args, bytes calldata signature ) external nonReentrant onlyRole(OWNER_ROLE) onlyAllowedKey(args[0]) // starkKeyA { bytes32 argsHash = keccak256(abi.encodePacked(args)); uint256 timestamp = _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash]; require( timestamp != 0, 'SP1Owner: Forced trade not queued or was vetoed' ); uint256 elapsed = block.timestamp.sub(timestamp); require( elapsed >= FORCED_TRADE_WAITING_PERIOD, 'SP1Owner: Waiting period has not elapsed for forced trade' ); require( elapsed <= FORCED_TRADE_WAITING_PERIOD.add(FORCED_TRADE_GRACE_PERIOD), 'SP1Owner: Grace period has elapsed for forced trade' ); _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0; _forcedTradeRequest(args, signature, false); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev 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'); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol'; import { SP1Balances } from './SP1Balances.sol'; /** * @title SP1Exchange * @author dYdX * * @dev Handles calls to the StarkPerpetual contract, for interacting with the dYdX L2 exchange. * * Standard exchange operation is handled by EXCHANGE_OPERATOR_ROLE. The “forced” actions can only * be called by the OWNER_ROLE or GUARDIAN_ROLE. Some other functions are also callable by * the GUARDIAN_ROLE. * * See SP1Roles, SP1Guardian, SP1Owner, and SP1Withdrawals. */ abstract contract SP1Exchange is SP1Balances { using SafeMath for uint256; // ============ Constants ============ IStarkPerpetual public immutable STARK_PERPETUAL; // ============ Events ============ event DepositedToExchange( uint256 starkKey, uint256 starkAssetType, uint256 starkVaultId, uint256 tokenAmount ); event WithdrewFromExchange( uint256 starkKey, uint256 starkAssetType, uint256 tokenAmount, bool isGuardianAction ); /// @dev Limited fields included. Details can be retrieved from Starkware logs if needed. event RequestedForcedWithdrawal( uint256 starkKey, uint256 vaultId, bool isGuardianAction ); /// @dev Limited fields included. Details can be retrieved from Starkware logs if needed. event RequestedForcedTrade( uint256 starkKey, uint256 vaultId, bool isGuardianAction ); // ============ Constructor ============ constructor( IStarkPerpetual starkPerpetual ) { STARK_PERPETUAL = starkPerpetual; } // ============ External Functions ============ /** * @notice Deposit funds to the exchange. * * IMPORTANT: The caller is responsible for providing `quantizedAmount` in the right units. * Currently, the exchange collateral is USDC, denominated in ERC20 token units, but * this could change. * * @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE. * @param assetType The exchange asset ID for the asset to deposit. * @param vaultId The exchange position ID for the account to deposit to. * @param quantizedAmount The deposit amount denominated in the exchange base units. * * @return The ERC20 token amount spent. */ function depositToExchange( uint256 starkKey, uint256 assetType, uint256 vaultId, uint256 quantizedAmount ) external nonReentrant onlyRole(EXCHANGE_OPERATOR_ROLE) onlyAllowedKey(starkKey) returns (uint256) { // Deposit and get the deposited token amount. uint256 startingBalance = getTokenBalance(); STARK_PERPETUAL.deposit(starkKey, assetType, vaultId, quantizedAmount); uint256 endingBalance = getTokenBalance(); uint256 tokenAmount = startingBalance.sub(endingBalance); // Disallow depositing borrowed funds to the exchange if the guardian has restricted borrowing. if (_IS_BORROWING_RESTRICTED_) { require( endingBalance >= getBorrowedAndDebtBalance(), 'SP1Borrowing: Cannot deposit borrowed funds to the exchange while Restricted' ); } emit DepositedToExchange(starkKey, assetType, vaultId, tokenAmount); return tokenAmount; } /** * @notice Trigger a withdrawal of account funds held in the exchange contract. This can be * called after a (slow) withdrawal has already been processed by the L2 exchange. * * @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE. * @param assetType The exchange asset ID for the asset to withdraw. * * @return The ERC20 token amount received by this contract. */ function withdrawFromExchange( uint256 starkKey, uint256 assetType ) external nonReentrant onlyRole(EXCHANGE_OPERATOR_ROLE) onlyAllowedKey(starkKey) returns (uint256) { return _withdrawFromExchange(starkKey, assetType, false); } // ============ Internal Functions ============ function _withdrawFromExchange( uint256 starkKey, uint256 assetType, bool isGuardianAction ) internal returns (uint256) { uint256 startingBalance = getTokenBalance(); STARK_PERPETUAL.withdraw(starkKey, assetType); uint256 endingBalance = getTokenBalance(); uint256 tokenAmount = endingBalance.sub(startingBalance); emit WithdrewFromExchange(starkKey, assetType, tokenAmount, isGuardianAction); return tokenAmount; } function _forcedWithdrawalRequest( uint256 starkKey, uint256 vaultId, uint256 quantizedAmount, bool premiumCost, bool isGuardianAction ) internal { STARK_PERPETUAL.forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost); emit RequestedForcedWithdrawal(starkKey, vaultId, isGuardianAction); } function _forcedTradeRequest( uint256[12] calldata args, bytes calldata signature, bool isGuardianAction ) internal { // Split into two functions to avoid error 'call stack too deep'. if (args[11] != 0) { _forcedTradeRequestPremiumCostTrue(args, signature); } else { _forcedTradeRequestPremiumCostFalse(args, signature); } emit RequestedForcedTrade( args[0], // starkKeyA args[2], // vaultIdA isGuardianAction ); } // ============ Private Functions ============ // Split into two functions to avoid error 'call stack too deep'. function _forcedTradeRequestPremiumCostTrue( uint256[12] calldata args, bytes calldata signature ) private { STARK_PERPETUAL.forcedTradeRequest( args[0], // starkKeyA args[1], // starkKeyB args[2], // vaultIdA args[3], // vaultIdB args[4], // collateralAssetId args[5], // syntheticAssetId args[6], // amountCollateral args[7], // amountSynthetic args[8] != 0, // aIsBuyingSynthetic args[9], // submissionExpirationTime args[10], // nonce signature, true // premiumCost ); } // Split into two functions to avoid error 'call stack too deep'. function _forcedTradeRequestPremiumCostFalse( uint256[12] calldata args, bytes calldata signature ) private { STARK_PERPETUAL.forcedTradeRequest( args[0], // starkKeyA args[1], // starkKeyB args[2], // vaultIdA args[3], // vaultIdB args[4], // collateralAssetId args[5], // syntheticAssetId args[6], // amountCollateral args[7], // amountSynthetic args[8] != 0, // aIsBuyingSynthetic args[9], // submissionExpirationTime args[10], // nonce signature, false // premiumCost ); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol'; import { Math } from '../../../utils/Math.sol'; import { SP1Roles } from './SP1Roles.sol'; /** * @title SP1Balances * @author dYdX * * @dev Contains common constants and functions related to token balances. */ abstract contract SP1Balances is SP1Roles { using SafeMath for uint256; // ============ Constants ============ IERC20 public immutable TOKEN; ILiquidityStakingV1 public immutable LIQUIDITY_STAKING; // ============ Constructor ============ constructor( ILiquidityStakingV1 liquidityStaking, IERC20 token ) { LIQUIDITY_STAKING = liquidityStaking; TOKEN = token; } // ============ Public Functions ============ function getAllocatedBalanceCurrentEpoch() public view returns (uint256) { return LIQUIDITY_STAKING.getAllocatedBalanceCurrentEpoch(address(this)); } function getAllocatedBalanceNextEpoch() public view returns (uint256) { return LIQUIDITY_STAKING.getAllocatedBalanceNextEpoch(address(this)); } function getBorrowableAmount() public view returns (uint256) { if (_IS_BORROWING_RESTRICTED_) { return 0; } return LIQUIDITY_STAKING.getBorrowableAmount(address(this)); } function getBorrowedBalance() public view returns (uint256) { return LIQUIDITY_STAKING.getBorrowedBalance(address(this)); } function getDebtBalance() public view returns (uint256) { return LIQUIDITY_STAKING.getBorrowerDebtBalance(address(this)); } function getBorrowedAndDebtBalance() public view returns (uint256) { return getBorrowedBalance().add(getDebtBalance()); } function getTokenBalance() public view returns (uint256) { return TOKEN.balanceOf(address(this)); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SP1Storage } from './SP1Storage.sol'; /** * @title SP1Roles * @author dYdX * * @dev Defines roles used in the StarkProxyV1 contract. The hierarchy and powers of each role * are described below. Not all roles need to be used. * * Overview: * * During operation of this contract, funds will flow between the following three * contracts: * * LiquidityStaking <> StarkProxy <> StarkPerpetual * * Actions which move fund from left to right are called “open” actions, whereas actions which * move funds from right to left are called “close” actions. * * Also note that the “forced” actions (forced trade and forced withdrawal) require special care * since they directly impact the financial risk of positions held on the exchange. * * Roles: * * GUARDIAN_ROLE * | -> May perform “close” actions as defined above, but “forced” actions can only be taken * | if the borrower has an outstanding debt balance. * | -> May restrict “open” actions as defined above, except w.r.t. funds in excess of the * | borrowed balance. * | -> May approve a token amount to be withdrawn externally by the WITHDRAWAL_OPERATOR_ROLE * | to an allowed address. * | * +-- VETO_GUARDIAN_ROLE * -> May veto forced trade requests initiated by the owner, during the waiting period. * * OWNER_ROLE * | -> May add or remove allowed recipients who may receive excess funds. * | -> May add or remove allowed STARK keys for use on the exchange. * | -> May set ERC20 allowances on the LiquidityStakingV1 and StarkPerpetual contracts. * | -> May call the “forced” actions: forcedWithdrawalRequest and forcedTradeRequest. * | * +-- DELEGATION_ADMIN_ROLE * | * +-- BORROWER_ROLE * | -> May call functions on LiquidityStakingV1: autoPayOrBorrow, borrow, repay, * | and repayDebt. * | * +-- EXCHANGE_OPERATOR_ROLE * | -> May call functions on StarkPerpetual: depositToExchange and * | withdrawFromExchange. * | * +-- WITHDRAWAL_OPERATOR_ROLE * -> May withdraw funds in excess of the borrowed balance to an allowed recipient. */ abstract contract SP1Roles is SP1Storage { bytes32 public constant GUARDIAN_ROLE = keccak256('GUARDIAN_ROLE'); bytes32 public constant VETO_GUARDIAN_ROLE = keccak256('VETO_GUARDIAN_ROLE'); bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant DELEGATION_ADMIN_ROLE = keccak256('DELEGATION_ADMIN_ROLE'); bytes32 public constant BORROWER_ROLE = keccak256('BORROWER_ROLE'); bytes32 public constant EXCHANGE_OPERATOR_ROLE = keccak256('EXCHANGE_OPERATOR_ROLE'); bytes32 public constant WITHDRAWAL_OPERATOR_ROLE = keccak256('WITHDRAWAL_OPERATOR_ROLE'); function __SP1Roles_init( address guardian ) internal { // Assign GUARDIAN_ROLE. _setupRole(GUARDIAN_ROLE, guardian); // Assign OWNER_ROLE and DELEGATION_ADMIN_ROLE to the sender. _setupRole(OWNER_ROLE, msg.sender); _setupRole(DELEGATION_ADMIN_ROLE, msg.sender); // Set admins for all roles. (Don't use the default admin role.) _setRoleAdmin(GUARDIAN_ROLE, GUARDIAN_ROLE); _setRoleAdmin(VETO_GUARDIAN_ROLE, GUARDIAN_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(DELEGATION_ADMIN_ROLE, OWNER_ROLE); _setRoleAdmin(BORROWER_ROLE, DELEGATION_ADMIN_ROLE); _setRoleAdmin(EXCHANGE_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE); _setRoleAdmin(WITHDRAWAL_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol'; import { Math } from '../../../utils/Math.sol'; import { SP1Balances } from './SP1Balances.sol'; /** * @title SP1Borrowing * @author dYdX * * @dev Handles calls to the LiquidityStaking contract to borrow and repay funds. */ abstract contract SP1Borrowing is SP1Balances { using SafeMath for uint256; // ============ Events ============ event Borrowed( uint256 amount, uint256 newBorrowedBalance ); event RepaidBorrow( uint256 amount, uint256 newBorrowedBalance, bool isGuardianAction ); event RepaidDebt( uint256 amount, uint256 newDebtBalance, bool isGuardianAction ); // ============ Constructor ============ constructor( ILiquidityStakingV1 liquidityStaking, IERC20 token ) SP1Balances(liquidityStaking, token) {} // ============ External Functions ============ /** * @notice Automatically repay or borrow to bring borrowed balance to the next allocated balance. * Must be called during the blackout window, to ensure allocated balance will not change before * the start of the next epoch. Reverts if there are insufficient funds to prevent a shortfall. * * Can be called with eth_call to view amounts that will be borrowed or repaid. * * @return The newly borrowed amount. * @return The borrow amount repaid. * @return The debt amount repaid. */ function autoPayOrBorrow() external nonReentrant onlyRole(BORROWER_ROLE) returns ( uint256, uint256, uint256 ) { // Ensure we are in the blackout window. require( LIQUIDITY_STAKING.inBlackoutWindow(), 'SP1Borrowing: Auto-pay may only be used during the blackout window' ); // Get the borrowed balance, next allocated balance, and token balance. uint256 borrowedBalance = getBorrowedBalance(); uint256 nextAllocatedBalance = getAllocatedBalanceNextEpoch(); uint256 tokenBalance = getTokenBalance(); // Return values. uint256 borrowAmount = 0; uint256 repayBorrowAmount = 0; uint256 repayDebtAmount = 0; if (borrowedBalance > nextAllocatedBalance) { // Make the necessary repayment due by the end of the current epoch. repayBorrowAmount = borrowedBalance.sub(nextAllocatedBalance); require( tokenBalance >= repayBorrowAmount, 'SP1Borrowing: Insufficient funds to avoid falling short on repayment' ); _repayBorrow(repayBorrowAmount, false); } else { // Borrow the max borrowable amount. borrowAmount = getBorrowableAmount(); if (borrowAmount != 0) { _borrow(borrowAmount); } } // Finally, use remaining funds to pay any overdue debt. uint256 debtBalance = getDebtBalance(); repayDebtAmount = Math.min(debtBalance, tokenBalance); if (repayDebtAmount != 0) { _repayDebt(repayDebtAmount, false); } return (borrowAmount, repayBorrowAmount, repayDebtAmount); } function borrow( uint256 amount ) external nonReentrant onlyRole(BORROWER_ROLE) { // Disallow if the guardian has restricted borrowing. require( !_IS_BORROWING_RESTRICTED_, 'SP1Borrowing: Cannot borrow while Restricted' ); _borrow(amount); } function repayBorrow( uint256 amount ) external nonReentrant onlyRole(BORROWER_ROLE) { _repayBorrow(amount, false); } function repayDebt( uint256 amount ) external nonReentrant onlyRole(BORROWER_ROLE) { _repayDebt(amount, false); } // ============ Internal Functions ============ function _borrow( uint256 amount ) internal { LIQUIDITY_STAKING.borrow(amount); emit Borrowed(amount, getBorrowedBalance()); } function _repayBorrow( uint256 amount, bool isGovernanceAction ) internal { LIQUIDITY_STAKING.repayBorrow(address(this), amount); emit RepaidBorrow(amount, getBorrowedBalance(), isGovernanceAction); } function _repayDebt( uint256 amount, bool isGovernanceAction ) internal { LIQUIDITY_STAKING.repayDebt(address(this), amount); emit RepaidDebt(amount, getDebtBalance(), isGovernanceAction); } }
ILiquidityStakingV1 dYdX Partial interface for LiquidityStakingV1./ LS1Borrowing LS1DebtAccounting
interface ILiquidityStakingV1 { function getToken() external view virtual returns (address); function getBorrowedBalance(address borrower) external view virtual returns (uint256); function getBorrowerDebtBalance(address borrower) external view virtual returns (uint256); function isBorrowingRestrictedForBorrower(address borrower) external view virtual returns (bool); function getTimeRemainingInEpoch() external view virtual returns (uint256); function inBlackoutWindow() external view virtual returns (bool); function borrow(uint256 amount) external virtual; function repayBorrow(address borrower, uint256 amount) external virtual; function getAllocatedBalanceCurrentEpoch(address borrower) external view virtual returns (uint256); function getAllocatedBalanceNextEpoch(address borrower) external view virtual returns (uint256); function getBorrowableAmount(address borrower) external view virtual returns (uint256); function repayDebt(address borrower, uint256 amount) external virtual; } pragma solidity 0.7.5; }
221,829
./full_match/97/0x67758feAA8824de6DD8850f18343dbe3701Ae372/sources/project_/contracts/Token.sol
See {IBEP20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {BEP20}. 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 whenNotPause returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "BEP20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; }
5,023,282
// SPDX-License-Identifier: GPL-3.0 /* 100 ether to enter; require 1000 participants when hit 1000 participants sort 3 winners randonly 1st place 20% = 20,000 ONEs 2nd place 10% = 10,000 ONEs 3rd place 5% = 5,000 ONEs DAO fund 65% = 65,000 ONEs */ pragma solidity >=0.1.1 <0.8.6; contract SocialChangeGame { // the deployer address public owner; // dao fund address dao; // actual event number uint private _event; // mapping totals in event mapping(uint => uint) _totals; // mapping for winners numbers mapping(uint => uint[3]) winners; // mapping for participants mapping(uint => mapping(uint => address)) participants; // mapping for claimed prizes mapping(address => mapping(uint => bool)) claimed; // mapping for joineds in events mapping(address => mapping(uint => bool)) joined; event Winner(uint _event, address _winner, uint _position); constructor(address _dao) { _event = 1; owner = msg.sender; dao = _dao; } modifier onlyOwner() { require(msg.sender == owner); _; } function sort() public onlyOwner{ require(_totals[_event] == 999, "few participants"); // sort 3 winners for(uint i = 0; i < 3; i++){ // prnd - sorted a number from 0 to 999 winners[_event][i] = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, i))) % 1000; // emit winer emit Winner(_event, participants[_event][winners[_event][i]], i); } // transfer 65% for dao _transfer(dao); // update _event _event = _event + 1; } function claim(uint event_) public { if(claimed[msg.sender][event_] == true){ // revert if already claimed revert("already claimed"); } for(uint i = 0; i < winners[event_].length; i++){ // search for address in sort numbers if(participants[event_][winners[event_][i]] == msg.sender){ // if sorted, call internal _withdraw _withdraw(msg.sender, i); } } // revert if not for claim revert("nothing for claim"); } function _withdraw(address _winner, uint _position) internal { if(_position == 0){ // send prize for #1 sorted payable(_winner).transfer(20000 ether); } if(_position == 1){ // send prize for #2 sorted payable(_winner).transfer(10000 ether); } if(_position == 2){ // send prize for #3 sorted payable(_winner).transfer(5000 ether); } // unviable double claim claimed[msg.sender][_event] = true; } function join() public payable { // 100 ether to enter; require(msg.value == 100 ether, "should be 100"); // only one time per event require(joined[msg.sender][_event] == false, "only one time"); // only 1000 participants require(_totals[_event] < 999, "hit maximum"); // add participant in event participants[_event][_totals[_event]] = msg.sender; // increment the totals _totals[_event] = _totals[_event] + 1; // set to true joined key joined[msg.sender][_event] = true; } function _transfer(address _dao) internal onlyOwner { payable(_dao).transfer(65000 ether); } }
send prize for 1 sorted send prize for 2 sorted send prize for 3 sorted
function _withdraw(address _winner, uint _position) internal { if(_position == 0){ payable(_winner).transfer(20000 ether); } if(_position == 1){ payable(_winner).transfer(10000 ether); } if(_position == 2){ payable(_winner).transfer(5000 ether); } }
12,925,019
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./DaoStaking.sol"; import "./RicVault.sol"; // The FeeDao is where the fees accumulate from the contracts in the catalog. // Token holders can Vote on IERC20 addresses to use for fees. // Token holders can exchange their tokens for reward from up to 3 IERC20 balances. // The exchanged tokens are added to the DaoStaking developer reward pool. struct TokenProposal { address creator; string name; IERC20 proposal; string discussionURL; uint256 approvals; uint256 rejections; uint256 created; bool closed; } struct Token { string name; // The name of the token IERC20 token; } uint256 constant requiredBalance = 10000e18; uint256 constant precision = 1000000000; //The precision of reward calculation, 9 decimals enum Balance { current, total } enum Periods { singleLock, trippleLock, pollPeriod } contract FeeDao { using SafeERC20 for IERC20; DaoStaking private staking; CatalogDao private catalogDao; RicVault private ricVault; IERC20 private ric; TokenProposal[] private proposals; mapping(bytes32 => bool) private voted; mapping(address => TokenProposal[]) private myProposals; mapping(address => bool) private hasPendingProposal; Token[] private tokens; // addressAdded is used like a .contains array method for the tokens . // will return true if the address has been added mapping(address => bool) private addressAdded; mapping(bytes32 => uint256) private balance; mapping(Periods => uint256) private periods; address private owner; bool private lock; event ProposeNewToken( address indexed _address, IERC20 _token, string _discussionURL ); event VoteOnToken(address indexed _address, bool _accepted, uint256 _index); event CloseProposal(address indexed _address, uint256 index); event WithdrawToken( address indexed _address, IERC20 withdraw, uint256 amount, uint256 reward ); event WithdrawThreeTokens( address indexed _address, IERC20 first, IERC20 second, IERC20 third, uint256 amount, uint256 firstReward, uint256 secondReward, uint256 thirdReward ); event Received(address to, uint256 value); event WithdrawEth(address to, uint256 reward, uint256 ricAmount); constructor( IERC20 ric_, DaoStaking _staking_, CatalogDao _catalogDao_, uint256 pollPeriod_ ) { ric = ric_; staking = _staking_; periods[Periods.pollPeriod] = pollPeriod_; periods[Periods.singleLock] = 1314900; //blocks are around 1 month with 2 second finality periods[Periods.trippleLock] = 3944700; // blocks are around 3 months with a 2 second finality owner = msg.sender; catalogDao = _catalogDao_; balance[hashBalance(Balance.current)] = 0; balance[hashBalance(Balance.total)] = 0; } function setRicVault(RicVault _ricVault_) external { require(msg.sender == owner, "937"); ricVault = _ricVault_; } function setPollPeriods( uint256 singleLock, uint256 trippleLock, uint256 pollPeriod ) external { require(msg.sender == owner, "937"); periods[Periods.singleLock] = singleLock; periods[Periods.trippleLock] = trippleLock; periods[Periods.pollPeriod] = pollPeriod; } function proposeNewToken( IERC20 _token, string memory _discussionURL, string memory _name_ ) external returns (uint256) { require(address(_token) != address(0), "948"); require(staking.isStaking(msg.sender), "919"); require(catalogDao.getRank(msg.sender) > 0, "911"); // The proposer must have the required balance require(ric.balanceOf(msg.sender) > requiredBalance, "932"); require(!hasPendingProposal[msg.sender], "944"); TokenProposal memory proposal = TokenProposal({ name: _name_, creator: msg.sender, proposal: _token, discussionURL: _discussionURL, approvals: 0, rejections: 0, created: block.number, closed: false }); hasPendingProposal[msg.sender] = true; proposals.push(proposal); bytes32 _hash_ = hashTokenProposal(proposal, msg.sender); voted[_hash_] = true; myProposals[msg.sender].push(proposal); emit ProposeNewToken(msg.sender, _token, _discussionURL); return proposals.length; } function hashTokenProposal(TokenProposal memory _proposal, address _voter) internal pure returns (bytes32) { return keccak256( abi.encodePacked( _proposal.creator, _proposal.proposal, _proposal.discussionURL, _proposal.created, _voter ) ); } // Accessing array by index here! function votedAlready(uint256 index, address _voter) public view returns (bool) { bytes32 _hash_ = hashTokenProposal(proposals[index], _voter); return voted[_hash_]; } function voteOnToken(uint256 index, bool accepted) external { require(staking.isStaking(msg.sender), "919"); require(catalogDao.getRank(msg.sender) > 0, "911"); // The voter must have the required balance require(ric.balanceOf(msg.sender) > requiredBalance, "932"); bytes32 _hash_ = hashTokenProposal(proposals[index], msg.sender); require(!voted[_hash_], "933"); // check if the voting period is over require( proposals[index].created + periods[Periods.pollPeriod] > block.number, "913" ); if (accepted) { proposals[index].approvals += 1; // The deployer of the contract can moderate proposals if (msg.sender == owner) { proposals[index].approvals += 4; } } else { proposals[index].rejections += 1; if (msg.sender == owner) { proposals[index].rejections += 4; } } voted[_hash_] = true; emit VoteOnToken(msg.sender, accepted, index); } function closeTokenProposal(uint256 index) external { require(catalogDao.getRank(msg.sender) > 0, "911"); // Everybody closes their own proposals require(proposals[index].creator == msg.sender, "914"); // The poll period must be over require( proposals[index].created + periods[Periods.pollPeriod] < block.number, "915" ); require(!proposals[index].closed, "917"); proposals[index].closed = true; hasPendingProposal[msg.sender] = false; // If there are more approvals than rejections if (proposals[index].approvals > proposals[index].rejections) { tokens.push( Token({ name: proposals[index].name, token: proposals[index].proposal }) ); addressAdded[address(proposals[index].proposal)] = true; } // else its closed, done. emit CloseProposal(msg.sender, index); } function tokenHashWithAddress(Token memory _tokens_) internal view returns (bytes32) { return keccak256( abi.encodePacked(_tokens_.name, _tokens_.token, msg.sender) ); } function getTokens() external view returns (Token[] memory) { return tokens; } function getProposals() external view returns (TokenProposal[] memory) { return proposals; } function getMyProposals() external view returns (TokenProposal[] memory) { return myProposals[msg.sender]; } function calculateWithdraw(IERC20 from, uint256 amount) public view returns (uint256 payment) { // How much is the amount compared to the total supply? uint256 withPadding = amount * precision; uint256 dividedByTotal = (withPadding / ric.totalSupply()); uint256 calculatedValue = dividedByTotal * from.balanceOf(address(this)); payment = calculatedValue / precision; } function calculateETHWithdraw(uint256 amount) public view returns (uint256 payment) { // How much is the amount compared to the total supply? uint256 withPadding = amount * precision; uint256 dividedByTotal = (withPadding / ric.totalSupply()); uint256 calculatedValue = dividedByTotal * balance[hashBalance(Balance.current)]; payment = calculatedValue / precision; } function withdrawETH(uint256 amount) external { require(!lock, "925"); lock = true; require(ric.balanceOf(msg.sender) >= amount, "934"); uint256 _reward = calculateETHWithdraw(amount); require(_reward < balance[hashBalance(Balance.current)], "927"); balance[hashBalance(Balance.current)] -= _reward; // Lock the ric in the vault ricVault.lockFor(msg.sender, periods[Periods.singleLock], amount); // reduce the balance and send it Address.sendValue(payable(msg.sender), _reward); lock = false; emit WithdrawEth(msg.sender, _reward, amount); } receive() external payable { emit Received(msg.sender, msg.value); balance[hashBalance(Balance.current)] += msg.value; balance[hashBalance(Balance.total)] += msg.value; } function getCurrentBalance() external view returns (uint256) { return balance[hashBalance(Balance.current)]; } function getTotalBalance() external view returns (uint256) { return balance[hashBalance(Balance.total)]; } function withdrawOne(IERC20 from, uint256 amount) external { require(!lock, "935"); lock = true; require(addressAdded[address(from)], "939"); require(ric.balanceOf(msg.sender) >= amount, "934"); uint256 _reward = calculateWithdraw(from, amount); require(_reward < from.balanceOf(address(this)), "927"); // Register a spend balance[hashBalance(address(from))] += _reward; // Lock the ric in the vault ricVault.lockFor(msg.sender, periods[Periods.trippleLock], amount); // transfer the requiested tokens from.safeTransfer(msg.sender, _reward); lock = false; emit WithdrawToken(msg.sender, from, amount, _reward); } function viewSpentBalanceOf(IERC20 _token_) external view returns (uint256) { return balance[hashBalance(address(_token_))]; } function hashBalance(Balance _balance_) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_balance_)); } // hashBalance with the address parameter is used for IERC20 address spent balance tracking // It was done like this because of the limit on variable declarations in the contract function hashBalance(address _balance_) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_balance_)); } }
The voter must have the required balance check if the voting period is over The deployer of the contract can moderate proposals
function voteOnToken(uint256 index, bool accepted) external { require(staking.isStaking(msg.sender), "919"); require(catalogDao.getRank(msg.sender) > 0, "911"); require(ric.balanceOf(msg.sender) > requiredBalance, "932"); bytes32 _hash_ = hashTokenProposal(proposals[index], msg.sender); require(!voted[_hash_], "933"); require( proposals[index].created + periods[Periods.pollPeriod] > block.number, "913" ); if (accepted) { proposals[index].approvals += 1; if (msg.sender == owner) { proposals[index].approvals += 4; } proposals[index].rejections += 1; if (msg.sender == owner) { proposals[index].rejections += 4; } } voted[_hash_] = true; emit VoteOnToken(msg.sender, accepted, index); }
2,473,264
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {Operator} from "./access/Operator.sol"; /* * Your typical reward pool contract */ contract RewardPool is Operator { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. tokens to distribute per block. uint256 lastRewardBlock; // Last block number that tokens distribution occurs. uint256 accTokensPerStake; // Accumulated tokens per staked token, times 1e18. See below. bool isStarted; // if lastRewardBlock has passed } // TODO(ndx): Replace by actual Tokens contract address on chain? IERC20 public token = IERC20(0x0000000000000000000000000000000000000000); // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when tokens mining starts. uint256 public startBlock; uint256 public endBlock; uint256 public tokensPerBlock; uint256 public runningBlocks; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPaid(address indexed user, uint256 amount); constructor( address _token, uint256 _startBlock, uint256 _runningBlocks, uint256 _totalRewards ) { require(block.number < _startBlock, "late"); if (_token != address(0)) token = IERC20(_token); startBlock = _startBlock; runningBlocks = _runningBlocks; endBlock = startBlock + runningBlocks; tokensPerBlock = _totalRewards.div(runningBlocks); } function checkPoolDuplicate(IERC20 _lpToken) internal view { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _lpToken, "RewardPool: existing pool?"); } } // Add a new lp to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock ) public onlyOperator { checkPoolDuplicate(_lpToken); if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { // chef is sleeping if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; } else { if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } } else { // chef is cooking if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (_lastRewardBlock <= startBlock) || (_lastRewardBlock <= block.number); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : _lastRewardBlock, accTokensPerStake : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's tokens allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOperator { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); } pool.allocPoint = _allocPoint; } // Return accumulate rewards over the given _from to _to block. function getGeneratedReward(uint256 _from, uint256 _to) public view returns (uint256) { require(_from <= _to, "_from must be less than _to."); if(_from > endBlock) return 0; if(_from < startBlock) _from = startBlock; if(_to > endBlock) _to = endBlock; return _to.sub(_from).mul(tokensPerBlock); } // View function to see pending tokens on frontend. function pendingRewards(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTokensPerStake = pool.accTokensPerStake; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _tokensReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); accTokensPerStake = accTokensPerStake.add(_tokensReward.mul(1e18).div(lpSupply)); } return user.amount.mul(accTokensPerStake).div(1e18).sub(user.rewardDebt); } // View function to see user balance on frontend. function balanceOf(uint256 _pid, address _user) external view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _tokensReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accTokensPerStake = pool.accTokensPerStake.add(_tokensReward.mul(1e18).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens. function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accTokensPerStake).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeTokensTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_sender, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accTokensPerStake).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw LP tokens. function withdraw(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accTokensPerStake).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeTokensTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accTokensPerStake).div(1e18); emit Withdraw(_sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _pid, _amount); } // Safe tokens transfer function, just in case if rounding error causes pool to not have enough tokens. function safeTokensTransfer(address _to, uint256 _amount) internal { uint256 _tokensBal = token.balanceOf(address(this)); if (_tokensBal > 0) { if (_amount > _tokensBal) { token.safeTransfer(_to, _tokensBal); } else { token.safeTransfer(_to, _amount); } } } }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _tokensReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accTokensPerStake = pool.accTokensPerStake.add(_tokensReward.mul(1e18).div(lpSupply)); } pool.lastRewardBlock = block.number; }
2,541,912
pragma solidity ^0.4.13; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SaferMath { function mulX(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function divX(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SaferMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract DexAlpha is StandardToken, Ownable { string public constant name = "DexAlpha Tokens"; string public constant symbol = "DXAT"; uint8 public constant decimals = 8; uint256 public constant SUPPLY_CAP = 1000000000 * (10 ** uint256(decimals)); address NULL_ADDRESS = address(0); uint public nonce = 0; event NonceTick(uint nonce); function incNonce() { nonce += 1; if(nonce > 100) { nonce = 0; } NonceTick(nonce); } event PerformingDrop(uint count); function drop(address[] addresses, uint256 amount) public onlyOwner { uint256 amt = amount * 10**8; require(amt > 0); require(amt <= SUPPLY_CAP); PerformingDrop(addresses.length); // Multisend function assert(balances[owner] >= amt * addresses.length); for (uint i = 0; i < addresses.length; i++) { address recipient = addresses[i]; if(recipient != NULL_ADDRESS) { balances[owner] -= amt; balances[recipient] += amt; Transfer(owner, recipient, amt); } } } /** * @dev Constructor that gives msg.sender all of existing tokens.. */ function DexAlpha() { totalSupply = SUPPLY_CAP; balances[msg.sender] = SUPPLY_CAP; } }
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 divX(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; }
1,138,599
// File: interfaces/IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: libraries/SafeMath.sol pragma solidity =0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { 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 div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'ds-math-div-overflow'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } // File: interfaces/ISafeSwapV2Pair.sol pragma solidity >=0.5.0; interface ISafeSwapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: libraries/SafeSwapV2Library.sol pragma solidity >=0.5.0; library SafeSwapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'SafeSwapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'SafeSwapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'a28c05e0a206be44a1cbe897feb29866ebc4dbf019a52c1ba553e5e80b33409d' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = ISafeSwapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'SafeSwapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'SafeSwapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'SafeSwapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SafeSwapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'SafeSwapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SafeSwapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'SafeSwapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'SafeSwapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: interfaces/ISafeSwapV2Router01.sol pragma solidity >=0.6.2; interface ISafeSwapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: interfaces/ISafeSwapV2Router02.sol pragma solidity >=0.6.2; interface ISafeSwapV2Router02 is ISafeSwapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); /* function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; */ } // File: libraries/TransferHelper.sol pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // File: interfaces/ISafeSwapV2Factory.sol pragma solidity >=0.5.0; interface ISafeSwapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function owner() 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; } // File: SafeSwapV2Router02.sol pragma solidity >=0.6.6; contract SafeSwapV2Router02 is ISafeSwapV2Router02 { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'SafeSwapV2Router: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (ISafeSwapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { require(msg.sender == ISafeSwapV2Factory(factory).owner(), "SafeSwapV2Router:_addLiquidity::NOT AUTHORIZED"); ISafeSwapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = SafeSwapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = SafeSwapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'SafeSwapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = SafeSwapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'SafeSwapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = SafeSwapV2Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = ISafeSwapV2Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = SafeSwapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = ISafeSwapV2Pair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = SafeSwapV2Library.pairFor(factory, tokenA, tokenB); ISafeSwapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = ISafeSwapV2Pair(pair).burn(to); (address token0,) = SafeSwapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'SafeSwapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'SafeSwapV2Router: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = SafeSwapV2Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; ISafeSwapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = SafeSwapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; ISafeSwapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = SafeSwapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; ISafeSwapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = SafeSwapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? SafeSwapV2Library.pairFor(factory, output, path[i + 2]) : _to; ISafeSwapV2Pair(SafeSwapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = SafeSwapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'SafeSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, SafeSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = SafeSwapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'SafeSwapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, SafeSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'SafeSwapV2Router: INVALID_PATH'); amounts = SafeSwapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'SafeSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(SafeSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'SafeSwapV2Router: INVALID_PATH'); amounts = SafeSwapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'SafeSwapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, SafeSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'SafeSwapV2Router: INVALID_PATH'); amounts = SafeSwapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'SafeSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, SafeSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'SafeSwapV2Router: INVALID_PATH'); amounts = SafeSwapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'SafeSwapV2Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(SafeSwapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // // **** SWAP (supporting fee-on-transfer tokens) **** // // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = SafeSwapV2Library.sortTokens(input, output); ISafeSwapV2Pair pair = ISafeSwapV2Pair(SafeSwapV2Library.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = SafeSwapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? SafeSwapV2Library.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, SafeSwapV2Library.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'SafeSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual payable ensure(deadline) { require(path[0] == WETH, 'SafeSwapV2Router: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(SafeSwapV2Library.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'SafeSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) { require(path[path.length - 1] == WETH, 'SafeSwapV2Router: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, SafeSwapV2Library.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'SafeSwapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return SafeSwapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return SafeSwapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return SafeSwapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return SafeSwapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return SafeSwapV2Library.getAmountsIn(factory, amountOut, path); } }
given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'SafeSwapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SafeSwapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); }
14,359,347
./partial_match/1/0x45c00508C14601fd1C1e296eB3C0e3eEEdCa45D0/sources/contracts/interfaces/external/ISwapRouter.sol
Router token swapping functionality Functions for swapping tokens via Uniswap V3
interface ISwapRouter { pragma solidity 0.6.10; struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } }
9,182,606
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/Exponential.sol"; import "../interfaces/external/yearn/IVault.sol"; import "./UnderlyingAssetMock.sol"; contract YearnVaultV2Mock is IVault { using SafeMath for uint256; using Exponential for uint256; uint256 public constant NOMINAL_ANNUAL_RATE = 15; uint256 public constant NUM_FRACTION_BITS = 64; uint256 public constant SECONDS_IN_DAY = 86400; uint256 public constant DAYS_IN_YEAR = 365; uint256 public constant SECONDS_IN_YEAR = SECONDS_IN_DAY * DAYS_IN_YEAR; uint256 public constant PERCENT_100 = 100; mapping(address => uint256) private _balances; uint256 public override decimals; uint256 public totalSupply; UnderlyingAssetMock public token; uint256 public lastReport; // block.timestamp of last report bool public testTransferFail = false; constructor(address token_) { decimals = 18; token = UnderlyingAssetMock(token_); } function pricePerShare() external view override returns (uint256) { return _shareValue(10**decimals); } function deposit(uint256 amount, address recipient) external override returns (uint256) { require(amount > 0, "0 amount"); // Issue new shares (needs to be done before taking deposit to be accurate) // Shares are issued to recipient (may be different from msg.sender) uint256 shares = _issueSharesForAmount(recipient, amount); if (lastReport == 0) { lastReport = block.timestamp; } // Tokens are transferred from msg.sender (may be different from _recipient) // https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return // https://github.com/crytic/slither/wiki/Detector-Documentation#unchecked-transfer // slither-disable-next-line unused-return,unchecked-transfer token.transferFrom(msg.sender, address(this), amount); return shares; } function withdraw( uint256 maxShares, address recipient, uint256 ) external override returns (uint256) { uint256 shares = maxShares; // May reduce this number below // Limit to only the shares they own require(shares <= _balances[msg.sender], "exceed shares owned"); // Ensure we are withdrawing something require(shares > 0, "0 shares"); // https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities-1 // https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities-2 // slither-disable-next-line reentrancy-no-eth,reentrancy-benign harvest(); uint256 value = _shareValue(shares); // Burn shares (full value of what is being withdrawn) totalSupply -= shares; _balances[msg.sender] -= shares; // Withdraw remaining balance to _recipient (may be different to msg.sender) (minus fee) // https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return // https://github.com/crytic/slither/wiki/Detector-Documentation#unchecked-transfer // slither-disable-next-line unused-return,unchecked-transfer token.transfer(recipient, value); return value; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address receiver, uint256 amount) external override returns (bool) { require(receiver != address(0), "0 receiver"); require(receiver != address(this), "self receiver"); _balances[msg.sender] -= amount; _balances[receiver] += amount; return !testTransferFail; } /** * @dev Returns the accrue per second compound interest, reverts if overflow * * @param presentValue in wei * @param nominalAnnualRate as percentage in unsigned integer * @param numSeconds in unsigned integer * @return futureValue in wei */ function accruePerSecondCompoundInterest( uint256 presentValue, uint256 nominalAnnualRate, uint256 numSeconds ) public pure returns (uint256 futureValue) { require(nominalAnnualRate <= 100, "> 100%"); uint256 exponent = numSeconds.mul( ( (( nominalAnnualRate.add(SECONDS_IN_YEAR.mul(PERCENT_100)) ) << NUM_FRACTION_BITS) .div(SECONDS_IN_YEAR.mul(PERCENT_100)) ) .logBase2() ); futureValue = exponent.expBase2().mul(presentValue) >> NUM_FRACTION_BITS; } function testUpdateDecimals(uint256 newDecimals) external { decimals = newDecimals; } function testSetTransferFail(bool value) external { testTransferFail = value; } function _totalAssets() internal view returns (uint256) { return token.balanceOf(address(this)); } function harvest() public { uint256 totalAssets = _totalAssets(); uint256 futureValue = accruePerSecondCompoundInterest( totalAssets, NOMINAL_ANNUAL_RATE, block.timestamp.sub(lastReport) ); uint256 interestEarned = futureValue.sub(totalAssets); lastReport = block.timestamp; token.mint(address(this), interestEarned); } function _issueSharesForAmount(address to, uint256 amount) internal returns (uint256) { // Issues `amount` Vault shares to `to`. // Shares must be issued prior to taking on new collateral, or // calculation will be wrong. This means that only *trusted* tokens // (with no capability for exploitative behavior) can be used. uint256 shares = 0; if (totalSupply > 0) { // Mint amount of shares based on what the Vault is managing overall // NOTE: if sqrt(token.totalSupply()) > 1e39, this could potentially revert shares = (amount * totalSupply) / _totalAssets(); } else { // No existing shares, so mint 1:1 shares = amount; } // Mint new shares totalSupply += shares; _balances[to] += shares; return shares; } function _shareValue(uint256 shares) internal view returns (uint256) { // Returns price = 1:1 if vault is empty // https://github.com/crytic/slither/wiki/Detector-Documentation#dangerous-strict-equalities // slither-disable-next-line incorrect-equality if (totalSupply == 0) { return shares; } return (shares * _totalAssets()) / totalSupply; } }
Limit to only the shares they own Ensure we are withdrawing something https:github.com/crytic/slither/wiki/Detector-Documentationreentrancy-vulnerabilities-1 https:github.com/crytic/slither/wiki/Detector-Documentationreentrancy-vulnerabilities-2 slither-disable-next-line reentrancy-no-eth,reentrancy-benign Burn shares (full value of what is being withdrawn) Withdraw remaining balance to _recipient (may be different to msg.sender) (minus fee) https:github.com/crytic/slither/wiki/Detector-Documentationunused-return https:github.com/crytic/slither/wiki/Detector-Documentationunchecked-transfer slither-disable-next-line unused-return,unchecked-transfer
function withdraw( uint256 maxShares, address recipient, uint256 ) external override returns (uint256) { require(shares <= _balances[msg.sender], "exceed shares owned"); require(shares > 0, "0 shares"); harvest(); uint256 value = _shareValue(shares); totalSupply -= shares; _balances[msg.sender] -= shares; token.transfer(recipient, value); return value; }
2,486,470
./partial_match/1/0x9391B14dB2d43687Ea1f6E546390ED4b20766c46/sources/contracts/lib/PolicyStorage.sol
Writes wallet checks to a Policy's pending wallet check removals. self A Policy object. walletChecks The address of one or more Wallet Checks to add to the Policy./
function writeWalletCheckRemovals( Policy storage self, address[] memory walletChecks ) public { for (uint i = 0; i < walletChecks.length; i++) { _writeWalletCheckRemoval(self, walletChecks[i]); } }
3,560,237
./partial_match/4/0x59708c679d45F9670698cC79E0BB1EF1C66C2885/sources/ProposalManagerV3.sol
指定提案id,返回投赞成票用户地址和票数数组
function getProposalYesAll(uint id) public view returns(address[] memory, uint[] memory){ require(proposals[id].isUsed, "id is invalid"); uint length = yesListLength[id]; for(uint i=1; i<= length; i++){ addrList[i-1] = yesAddressList[id][i]; pollList[i-1] = yesVoteUsers[id][addrList[i-1]]; } return (addrList,pollList); }
8,636,270
./full_match/1/0xD7134e2265B78DFCF4e9FA4DC65b18F4D5C03220/sources/contracts/bridgeERC20/layerZero/LayerZeroBridgeERC20.sol
@inheritdoc OFTCoreERC20
function withdraw(uint256 amount, address recipient) external override returns (uint256) { return _withdraw(amount, msg.sender, recipient); }
3,182,962
/** *Submitted for verification at Etherscan.io on 2021-11-01 */ // Sources flattened with hardhat v2.6.7 https://hardhat.org // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File contracts/interfaces/IAccessControl.sol pragma solidity ^0.8.7; /// @title IAccessControl /// @author Forked from OpenZeppelin /// @notice Interface for `AccessControl` contracts interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // File contracts/external/AccessControlUpgradeable.sol pragma solidity ^0.8.7; /** * @dev This contract is fully forked from OpenZeppelin `AccessControlUpgradeable`. * The only difference is the removal of the ERC165 implementation as it's not * needed in Angle. * * Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, IAccessControl { function __AccessControl_init() internal initializer { __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer {} struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, msg.sender); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external override { require(account == msg.sender, "71"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) internal { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes32 role, address account) internal { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } uint256[49] private __gap; } // File contracts/interfaces/IFeeManager.sol pragma solidity ^0.8.7; /// @title IFeeManagerFunctions /// @author Angle Core Team /// @dev Interface for the `FeeManager` contract interface IFeeManagerFunctions is IAccessControl { // ================================= Keepers =================================== function updateUsersSLP() external; function updateHA() external; // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external; function setFees( uint256[] memory xArray, uint64[] memory yArray, uint8 typeChange ) external; function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external; } /// @title IFeeManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev We need these getters as they are used in other contracts of the protocol interface IFeeManager is IFeeManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/interfaces/IERC721.sol pragma solidity ^0.8.7; interface IERC721 is IERC165 { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File contracts/interfaces/IOracle.sol pragma solidity ^0.8.7; /// @title IOracle /// @author Angle Core Team /// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink /// from just UniswapV3 or from just Chainlink interface IOracle { function read() external view returns (uint256); function readAll() external view returns (uint256 lowerRate, uint256 upperRate); function readLower() external view returns (uint256); function readUpper() external view returns (uint256); function readQuote(uint256 baseAmount) external view returns (uint256); function readQuoteLower(uint256 baseAmount) external view returns (uint256); function inBase() external view returns (uint256); } // File contracts/interfaces/IPerpetualManager.sol pragma solidity ^0.8.7; /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev Front interface, meaning only user-facing functions interface IPerpetualManagerFront is IERC721Metadata { function openPerpetual( address owner, uint256 amountBrought, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin ) external returns (uint256 perpetualID); function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external; function addToPerpetual(uint256 perpetualID, uint256 amount) external; function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external; function liquidatePerpetuals(uint256[] memory perpetualIDs) external; function forceClosePerpetuals(uint256[] memory perpetualIDs) external; // ========================= External View Functions ============================= function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256); function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool); } /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev This interface does not contain user facing functions, it just has functions that are /// interacted with in other parts of the protocol interface IPerpetualManagerFunctions is IAccessControl { // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, IFeeManager feeManager, IOracle oracle_ ) external; function setFeeManager(IFeeManager feeManager_) external; function setHAFees( uint64[] memory _xHAFees, uint64[] memory _yHAFees, uint8 deposit ) external; function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external; function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external; function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external; function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external; function setLockTime(uint64 _lockTime) external; function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external; function pause() external; function unpause() external; // ==================================== Keepers ================================ function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external; // =============================== StableMaster ================================ function setOracle(IOracle _oracle) external; } /// @title IPerpetualManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IPerpetualManager is IPerpetualManagerFunctions { function poolManager() external view returns (address); function oracle() external view returns (address); function targetHAHedge() external view returns (uint64); function totalHedgeAmount() external view returns (uint256); } // File contracts/interfaces/IPoolManager.sol pragma solidity ^0.8.7; // Struct for the parameters associated to a strategy interacting with a collateral `PoolManager` // contract struct StrategyParams { // Timestamp of last report made by this strategy // It is also used to check if a strategy has been initialized uint256 lastReport; // Total amount the strategy is expected to have uint256 totalStrategyDebt; // The share of the total assets in the `PoolManager` contract that the `strategy` can access to. uint256 debtRatio; } /// @title IPoolManagerFunctions /// @author Angle Core Team /// @notice Interface for the collateral poolManager contracts handling each one type of collateral for /// a given stablecoin /// @dev Only the functions used in other contracts of the protocol are left here interface IPoolManagerFunctions { // ============================ Constructor ==================================== function deployCollateral( address[] memory governorList, address guardian, IPerpetualManager _perpetualManager, IFeeManager feeManager, IOracle oracle ) external; // ============================ Yield Farming ================================== function creditAvailable() external view returns (uint256); function debtOutstanding() external view returns (uint256); function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external; // ============================ Governance ===================================== function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address _guardian, address guardian) external; function revokeGuardian(address guardian) external; function setFeeManager(IFeeManager _feeManager) external; // ============================= Getters ======================================= function getBalance() external view returns (uint256); function getTotalAsset() external view returns (uint256); } /// @title IPoolManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev Used in other contracts of the protocol interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); } // File contracts/interfaces/IStakingRewards.sol pragma solidity ^0.8.7; /// @title IStakingRewardsFunctions /// @author Angle Core Team /// @notice Interface for the staking rewards contract that interact with the `RewardsDistributor` contract interface IStakingRewardsFunctions { function notifyRewardAmount(uint256 reward) external; function recoverERC20( address tokenAddress, address to, uint256 tokenAmount ) external; function setNewRewardsDistribution(address newRewardsDistribution) external; } /// @title IStakingRewards /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IStakingRewards is IStakingRewardsFunctions { function rewardToken() external view returns (IERC20); } // File contracts/interfaces/IRewardsDistributor.sol pragma solidity ^0.8.7; /// @title IRewardsDistributor /// @author Angle Core Team, inspired from Fei protocol /// (https://github.com/fei-protocol/fei-protocol-core/blob/master/contracts/staking/IRewardsDistributor.sol) /// @notice Rewards Distributor interface interface IRewardsDistributor { // ========================= Public Parameter Getter =========================== function rewardToken() external view returns (IERC20); // ======================== External User Available Function =================== function drip(IStakingRewards stakingContract) external returns (uint256); // ========================= Governor Functions ================================ function governorWithdrawRewardToken(uint256 amount, address governance) external; function governorRecover( address tokenAddress, address to, uint256 amount, IStakingRewards stakingContract ) external; function setUpdateFrequency(uint256 _frequency, IStakingRewards stakingContract) external; function setIncentiveAmount(uint256 _incentiveAmount, IStakingRewards stakingContract) external; function setAmountToDistribute(uint256 _amountToDistribute, IStakingRewards stakingContract) external; function setDuration(uint256 _duration, IStakingRewards stakingContract) external; function setStakingContract( address _stakingContract, uint256 _duration, uint256 _incentiveAmount, uint256 _dripFrequency, uint256 _amountToDistribute ) external; function setNewRewardsDistributor(address newRewardsDistributor) external; function removeStakingContract(IStakingRewards stakingContract) external; } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/ISanToken.sol pragma solidity ^0.8.7; /// @title ISanToken /// @author Angle Core Team /// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs /// contributing to a collateral for a given stablecoin interface ISanToken is IERC20Upgradeable { // ================================== StableMaster ============================= function mint(address account, uint256 amount) external; function burnFrom( uint256 amount, address burner, address sender ) external; function burnSelf(uint256 amount, address burner) external; function stableMaster() external view returns (address); function poolManager() external view returns (address); } // File contracts/interfaces/IStableMaster.sol pragma solidity ^0.8.7; // Normally just importing `IPoolManager` should be sufficient, but for clarity here // we prefer to import all concerned interfaces // Struct to handle all the parameters to manage the fees // related to a given collateral pool (associated to the stablecoin) struct MintBurnData { // Values of the thresholds to compute the minting fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeMint; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeMint; // Values of the thresholds to compute the burning fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeBurn; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeBurn; // Max proportion of collateral from users that can be covered by HAs // It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated // the other changes accordingly uint64 targetHAHedge; // Minting fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusMint; // Burning fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusBurn; // Parameter used to limit the number of stablecoins that can be issued using the concerned collateral uint256 capOnStableMinted; } // Struct to handle all the variables and parameters to handle SLPs in the protocol // including the fraction of interests they receive or the fees to be distributed to // them struct SLPData { // Last timestamp at which the `sanRate` has been updated for SLPs uint256 lastBlockUpdated; // Fees accumulated from previous blocks and to be distributed to SLPs uint256 lockedInterests; // Max interests used to update the `sanRate` in a single block // Should be in collateral token base uint256 maxInterestsDistributed; // Amount of fees left aside for SLPs and that will be distributed // when the protocol is collateralized back again uint256 feesAside; // Part of the fees normally going to SLPs that is left aside // before the protocol is collateralized back again (depends on collateral ratio) // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippageFee; // Portion of the fees from users minting and burning // that goes to SLPs (the rest goes to surplus) uint64 feesForSLPs; // Slippage factor that's applied to SLPs exiting (depends on collateral ratio) // If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippage; // Portion of the interests from lending // that goes to SLPs (the rest goes to surplus) uint64 interestsForSLPs; } /// @title IStableMasterFunctions /// @author Angle Core Team /// @notice Interface for the `StableMaster` contract interface IStableMasterFunctions { function deploy( address[] memory _governorList, address _guardian, address _agToken ) external; // ============================== Lending ====================================== function accumulateInterest(uint256 gain) external; function signalLoss(uint256 loss) external; // ============================== HAs ========================================== function getStocksUsers() external view returns (uint256 maxCAmountInStable); function convertToSLP(uint256 amount, address user) external; // ============================== Keepers ====================================== function getCollateralRatio() external returns (uint256); function setFeeKeeper( uint64 feeMint, uint64 feeBurn, uint64 _slippage, uint64 _slippageFee ) external; // ============================== AgToken ====================================== function updateStocksUsers(uint256 amount, address poolManager) external; // ============================= Governance ==================================== function setCore(address newCore) external; function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address newGuardian, address oldGuardian) external; function revokeGuardian(address oldGuardian) external; function setCapOnStableAndMaxInterests( uint256 _capOnStableMinted, uint256 _maxInterestsDistributed, IPoolManager poolManager ) external; function setIncentivesForSLPs( uint64 _feesForSLPs, uint64 _interestsForSLPs, IPoolManager poolManager ) external; function setUserFees( IPoolManager poolManager, uint64[] memory _xFee, uint64[] memory _yFee, uint8 _mint ) external; function setTargetHAHedge(uint64 _targetHAHedge) external; function pause(bytes32 agent, IPoolManager poolManager) external; function unpause(bytes32 agent, IPoolManager poolManager) external; } /// @title IStableMaster /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings interface IStableMaster is IStableMasterFunctions { function agToken() external view returns (address); function collateralMap(IPoolManager poolManager) external view returns ( IERC20 token, ISanToken sanToken, IPerpetualManager perpetualManager, IOracle oracle, uint256 stocksUsers, uint256 sanRate, uint256 collatBase, SLPData memory slpData, MintBurnData memory feeData ); } // File contracts/utils/FunctionUtils.sol pragma solidity ^0.8.7; /// @title FunctionUtils /// @author Angle Core Team /// @notice Contains all the utility functions that are needed in different places of the protocol /// @dev Functions in this contract should typically be pure functions /// @dev This contract is voluntarily a contract and not a library to save some gas cost every time it is used contract FunctionUtils { /// @notice Base that is used to compute ratios and floating numbers uint256 public constant BASE_TOKENS = 10**18; /// @notice Base that is used to define parameters that need to have a floating value (for instance parameters /// that are defined as ratios) uint256 public constant BASE_PARAMS = 10**9; /// @notice Computes the value of a linear by part function at a given point /// @param x Point of the function we want to compute /// @param xArray List of breaking points (in ascending order) that define the linear by part function /// @param yArray List of values at breaking points (not necessarily in ascending order) /// @dev The evolution of the linear by part function between two breaking points is linear /// @dev Before the first breaking point and after the last one, the function is constant with a value /// equal to the first or last value of the yArray /// @dev This function is relevant if `x` is between O and `BASE_PARAMS`. If `x` is greater than that, then /// everything will be as if `x` is equal to the greater element of the `xArray` function _piecewiseLinear( uint64 x, uint64[] memory xArray, uint64[] memory yArray ) internal pure returns (uint64) { if (x >= xArray[xArray.length - 1]) { return yArray[xArray.length - 1]; } else if (x <= xArray[0]) { return yArray[0]; } else { uint256 lower; uint256 upper = xArray.length - 1; uint256 mid; while (upper - lower > 1) { mid = lower + (upper - lower) / 2; if (xArray[mid] <= x) { lower = mid; } else { upper = mid; } } if (yArray[upper] > yArray[lower]) { // There is no risk of overflow here as in the product of the difference of `y` // with the difference of `x`, the product is inferior to `BASE_PARAMS**2` which does not // overflow for `uint64` return yArray[lower] + ((yArray[upper] - yArray[lower]) * (x - xArray[lower])) / (xArray[upper] - xArray[lower]); } else { return yArray[lower] - ((yArray[lower] - yArray[upper]) * (x - xArray[lower])) / (xArray[upper] - xArray[lower]); } } } /// @notice Checks if the input arrays given by governance to update the fee structure is valid /// @param xArray List of breaking points (in ascending order) that define the linear by part function /// @param yArray List of values at breaking points (not necessarily in ascending order) /// @dev This function is a way to avoid some governance attacks or errors /// @dev The modifier checks if the arrays have a non null length, if their length is the same, if the values /// in the `xArray` are in ascending order and if the values in the `xArray` and in the `yArray` are not superior /// to `BASE_PARAMS` modifier onlyCompatibleInputArrays(uint64[] memory xArray, uint64[] memory yArray) { require(xArray.length == yArray.length && xArray.length > 0, "5"); for (uint256 i = 0; i <= yArray.length - 1; i++) { require(yArray[i] <= uint64(BASE_PARAMS) && xArray[i] <= uint64(BASE_PARAMS), "6"); if (i > 0) { require(xArray[i] > xArray[i - 1], "7"); } } _; } /// @notice Checks if the new value given for the parameter is consistent (it should be inferior to 1 /// if it corresponds to a ratio) /// @param fees Value of the new parameter to check modifier onlyCompatibleFees(uint64 fees) { require(fees <= BASE_PARAMS, "4"); _; } /// @notice Checks if the new address given is not null /// @param newAddress Address to check /// @dev Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#missing-zero-address-validation modifier zeroCheck(address newAddress) { require(newAddress != address(0), "0"); _; } } // File contracts/perpetualManager/PerpetualManagerEvents.sol pragma solidity ^0.8.7; // Used in the `forceCashOutPerpetuals` function to store owners of perpetuals which have been force cashed // out, along with the amount associated to it struct Pairs { address owner; uint256 netCashOutAmount; } /// @title PerpetualManagerEvents /// @author Angle Core Team /// @notice `PerpetualManager` is the contract handling all the Hedging Agents perpetuals /// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol /// @dev This file contains all the events of the `PerpetualManager` contract contract PerpetualManagerEvents { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event PerpetualUpdated(uint256 _perpetualID, uint256 _margin); event PerpetualOpened(uint256 _perpetualID, uint256 _entryRate, uint256 _margin, uint256 _committedAmount); event PerpetualClosed(uint256 _perpetualID, uint256 _closeAmount); event PerpetualsForceClosed(uint256[] perpetualIDs, Pairs[] ownerAndCashOut, address keeper, uint256 reward); event KeeperTransferred(address keeperAddress, uint256 liquidationFees); // ============================== Parameters =================================== event BaseURIUpdated(string _baseURI); event LockTimeUpdated(uint64 _lockTime); event KeeperFeesCapUpdated(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap); event TargetAndLimitHAHedgeUpdated(uint64 _targetHAHedge, uint64 _limitHAHedge); event BoundsPerpetualUpdated(uint64 _maxLeverage, uint64 _maintenanceMargin); event HAFeesUpdated(uint64[] _xHAFees, uint64[] _yHAFees, uint8 deposit); event KeeperFeesLiquidationRatioUpdated(uint64 _keeperFeesLiquidationRatio); event KeeperFeesClosingUpdated(uint64[] xKeeperFeesClosing, uint64[] yKeeperFeesClosing); // =============================== Reward ====================================== event RewardAdded(uint256 _reward); event RewardPaid(address indexed _user, uint256 _reward); event RewardsDistributionUpdated(address indexed _rewardsDistributor); event RewardsDistributionDurationUpdated(uint256 _rewardsDuration, address indexed _rewardsDistributor); event Recovered(address indexed tokenAddress, address indexed to, uint256 amount); } // File contracts/perpetualManager/PerpetualManagerStorage.sol pragma solidity ^0.8.7; struct Perpetual { // Oracle value at the moment of perpetual opening uint256 entryRate; // Timestamp at which the perpetual was opened uint256 entryTimestamp; // Amount initially brought in the perpetual (net from fees) + amount added - amount removed from it // This is the only element that can be modified in the perpetual after its creation uint256 margin; // Amount of collateral covered by the perpetual. This cannot be modified once the perpetual is opened. // The amount covered is used interchangeably with the amount hedged uint256 committedAmount; } /// @title PerpetualManagerStorage /// @author Angle Core Team /// @notice `PerpetualManager` is the contract handling all the Hedging Agents positions and perpetuals /// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol /// @dev This file contains all the parameters and references used in the `PerpetualManager` contract // solhint-disable-next-line max-states-count contract PerpetualManagerStorage is PerpetualManagerEvents, FunctionUtils { // Base used in the collateral implementation (ERC20 decimal) uint256 internal _collatBase; // ============================== Perpetual Variables ========================== /// @notice Total amount of stablecoins that are insured (i.e. that could be redeemed against /// collateral thanks to HAs) /// When a HA opens a perpetual, it covers/hedges a fixed amount of stablecoins for the protocol, equal to /// the committed amount times the entry rate /// `totalHedgeAmount` is the sum of all these hedged amounts uint256 public totalHedgeAmount; // Counter to generate a unique `perpetualID` for each perpetual CountersUpgradeable.Counter internal _perpetualIDcount; // ========================== Mutable References ============================ /// @notice `Oracle` to give the rate feed, that is the price of the collateral /// with respect to the price of the stablecoin /// This reference can be modified by the corresponding `StableMaster` contract IOracle public oracle; // `FeeManager` address allowed to update the way fees are computed for this contract // This reference can be modified by the `PoolManager` contract IFeeManager internal _feeManager; // ========================== Immutable References ========================== /// @notice Interface for the `rewardToken` distributed as a reward /// As of Angle V1, only a single `rewardToken` can be distributed to HAs who own a perpetual /// This implementation assumes that reward tokens have a base of 18 decimals IERC20 public rewardToken; /// @notice Address of the `PoolManager` instance IPoolManager public poolManager; // Address of the `StableMaster` instance IStableMaster internal _stableMaster; // Interface for the underlying token accepted by this contract // This reference cannot be changed, it is taken from the `PoolManager` IERC20 internal _token; // ======================= Fees and other Parameters =========================== /// Deposit fees for HAs depend on the hedge ratio that is the ratio between what is hedged /// (or covered, this is a synonym) by HAs compared with the total amount to hedge /// @notice Thresholds for the ratio between to amount hedged and the amount to hedge /// The bigger the ratio the bigger the fees will be because this means that the max amount /// to insure is soon to be reached uint64[] public xHAFeesDeposit; /// @notice Deposit fees at threshold values /// This array should have the same length as the array above /// The evolution of the fees between two threshold values is linear uint64[] public yHAFeesDeposit; /// Withdraw fees for HAs also depend on the hedge ratio /// @notice Thresholds for the hedge ratio uint64[] public xHAFeesWithdraw; /// @notice Withdraw fees at threshold values uint64[] public yHAFeesWithdraw; /// @notice Maintenance Margin (in `BASE_PARAMS`) for each perpetual /// The margin ratio is defined for a perpetual as: `(initMargin + PnL) / committedAmount` where /// `PnL = committedAmount * (1 - initRate/currentRate)` /// If the `marginRatio` is below `maintenanceMargin`: then the perpetual can be liquidated uint64 public maintenanceMargin; /// @notice Maximum leverage multiplier authorized for HAs (`in BASE_PARAMS`) /// Leverage for a perpetual here corresponds to the ratio between the amount committed /// and the margin of the perpetual uint64 public maxLeverage; /// @notice Target proportion of stablecoins issued using this collateral to insure with HAs. /// This variable is exactly the same as the one in the `StableMaster` contract for this collateral. /// Above this hedge ratio, HAs cannot open new perpetuals /// When keepers are forcing the closing of some perpetuals, they are incentivized to bringing /// the hedge ratio to this proportion uint64 public targetHAHedge; /// @notice Limit proportion of stablecoins issued using this collateral that HAs can insure /// Above this ratio `forceCashOut` is activated and anyone can see its perpetual cashed out uint64 public limitHAHedge; /// @notice Extra parameter from the `FeeManager` contract that is multiplied to the fees from above and that /// can be used to change deposit fees. It works as a bonus - malus fee, if `haBonusMalusDeposit > BASE_PARAMS`, /// then the fee will be larger than `haFeesDeposit`, if `haBonusMalusDeposit < BASE_PARAMS`, fees will be smaller. /// This parameter, updated by keepers in the `FeeManager` contract, could most likely depend on the collateral ratio uint64 public haBonusMalusDeposit; /// @notice Extra parameter from the `FeeManager` contract that is multiplied to the fees from above and that /// can be used to change withdraw fees. It works as a bonus - malus fee, if `haBonusMalusWithdraw > BASE_PARAMS`, /// then the fee will be larger than `haFeesWithdraw`, if `haBonusMalusWithdraw < BASE_PARAMS`, fees will be smaller uint64 public haBonusMalusWithdraw; /// @notice Amount of time before HAs are allowed to withdraw funds from their perpetuals /// either using `removeFromPerpetual` or `closePerpetual`. New perpetuals cannot be forced closed in /// situations where the `forceClosePerpetuals` function is activated before this `lockTime` elapsed uint64 public lockTime; // ================================= Keeper fees ====================================== // All these parameters can be modified by their corresponding governance function /// @notice Portion of the leftover cash out amount of liquidated perpetuals that go to /// liquidating keepers uint64 public keeperFeesLiquidationRatio; /// @notice Cap on the fees that go to keepers liquidating a perpetual /// If a keeper liquidates n perpetuals in a single transaction, then this keeper is entitled to get as much as /// `n * keeperFeesLiquidationCap` as a reward uint256 public keeperFeesLiquidationCap; /// @notice Cap on the fees that go to keepers closing perpetuals when too much collateral is hedged by HAs /// (hedge ratio above `limitHAHedge`) /// If a keeper forces the closing of n perpetuals in a single transaction, then this keeper is entitled to get /// as much as `keeperFeesClosingCap`. This cap amount is independent of the number of perpetuals closed uint256 public keeperFeesClosingCap; /// @notice Thresholds on the values of the rate between the current hedged amount (`totalHedgeAmount`) and the /// target hedged amount by HAs (`targetHedgeAmount`) divided by 2. A value of `0.5` corresponds to a hedge ratio /// of `1`. Doing this allows to maintain an array with values of `x` inferior to `BASE_PARAMS`. uint64[] public xKeeperFeesClosing; /// @notice Values at thresholds of the proportions of the fees that should go to keepers closing perpetuals uint64[] public yKeeperFeesClosing; // =========================== Staking Parameters ============================== /// @notice Below are parameters that can also be found in other staking contracts /// to be able to compute rewards from staking (having perpetuals here) correctly uint256 public periodFinish; uint256 public rewardRate; uint256 public rewardsDuration; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; address public rewardsDistribution; // ============================== ERC721 Base URI ============================== /// @notice URI used for the metadata of the perpetuals string public baseURI; // =============================== Mappings ==================================== /// @notice Mapping from `perpetualID` to perpetual data mapping(uint256 => Perpetual) public perpetualData; /// @notice Mapping used to compute the rewards earned by a perpetual in a timeframe mapping(uint256 => uint256) public perpetualRewardPerTokenPaid; /// @notice Mapping used to get how much rewards in governance tokens are gained by a perpetual // identified by its ID mapping(uint256 => uint256) public rewards; // Mapping from `perpetualID` to owner address mapping(uint256 => address) internal _owners; // Mapping from owner address to perpetual owned count mapping(address => uint256) internal _balances; // Mapping from `perpetualID` to approved address mapping(uint256 => address) internal _perpetualApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; } // File contracts/perpetualManager/PerpetualManagerInternal.sol pragma solidity ^0.8.7; /// @title PerpetualManagerInternal /// @author Angle Core Team /// @notice `PerpetualManager` is the contract handling all the Hedging Agents perpetuals /// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol /// @dev This file contains all the internal functions of the `PerpetualManager` contract contract PerpetualManagerInternal is PerpetualManagerStorage { using Address for address; using SafeERC20 for IERC20; // ======================== State Modifying Functions ========================== /// @notice Cashes out a perpetual, which means that it simply deletes the references to the perpetual /// in the contract /// @param perpetualID ID of the perpetual /// @param perpetual Data of the perpetual function _closePerpetual(uint256 perpetualID, Perpetual memory perpetual) internal { // Handling the staking logic // Reward should always be updated before the `totalHedgeAmount` // Rewards are distributed to the perpetual which is liquidated uint256 hedge = perpetual.committedAmount * perpetual.entryRate; _getReward(perpetualID, hedge); delete perpetualRewardPerTokenPaid[perpetualID]; // Updating `totalHedgeAmount` to represent the fact that less money is insured totalHedgeAmount -= hedge / _collatBase; _burn(perpetualID); } /// @notice Allows the protocol to transfer collateral to an address while handling the case where there are /// not enough reserves /// @param owner Address of the receiver /// @param amount The amount of collateral sent /// @dev If there is not enough collateral in balance (this can happen when money has been lent to strategies), /// then the owner is reimbursed by receiving what is missing in sanTokens at the correct value function _secureTransfer(address owner, uint256 amount) internal { uint256 curBalance = poolManager.getBalance(); if (curBalance >= amount && amount > 0) { // Case where there is enough in reserves to reimburse the person _token.safeTransferFrom(address(poolManager), owner, amount); } else if (amount > 0) { // When there is not enough to reimburse the entire amount, the protocol reimburses // what it can using its reserves and the rest is paid in sanTokens at the current // exchange rate uint256 amountLeft = amount - curBalance; _token.safeTransferFrom(address(poolManager), owner, curBalance); _stableMaster.convertToSLP(amountLeft, owner); } } /// @notice Checks whether the perpetual should be liquidated or not, and if so liquidates the perpetual /// @param perpetualID ID of the perpetual to check and potentially liquidate /// @param perpetual Data of the perpetual to check /// @param rateDown Oracle value to compute the cash out amount of the perpetual /// @return Cash out amount of the perpetual /// @return Whether the perpetual was liquidated or not /// @dev Generally, to check for the liquidation of a perpetual, we use the lowest oracle value possible: /// it's the one that is most at the advantage of the protocol, hence the `rateDown` parameter function _checkLiquidation( uint256 perpetualID, Perpetual memory perpetual, uint256 rateDown ) internal returns (uint256, uint256) { uint256 liquidated; (uint256 cashOutAmount, uint256 reachMaintenanceMargin) = _getCashOutAmount(perpetual, rateDown); if (cashOutAmount == 0 || reachMaintenanceMargin == 1) { _closePerpetual(perpetualID, perpetual); // No need for an event to find out that a perpetual is liquidated liquidated = 1; } return (cashOutAmount, liquidated); } // ========================= Internal View Functions =========================== /// @notice Gets the current cash out amount of a perpetual /// @param perpetual Data of the concerned perpetual /// @param rate Value of the oracle /// @return cashOutAmount Amount that the HA could get by closing this perpetual /// @return reachMaintenanceMargin Whether the position of the perpetual is now too small /// compared with its initial position /// @dev Refer to the whitepaper or the doc for the formulas of the cash out amount /// @dev The notion of `maintenanceMargin` is standard in centralized platforms offering perpetual futures function _getCashOutAmount(Perpetual memory perpetual, uint256 rate) internal view returns (uint256 cashOutAmount, uint256 reachMaintenanceMargin) { // All these computations are made just because we are working with uint and not int // so we cannot do x-y if x<y uint256 newCommit = (perpetual.committedAmount * perpetual.entryRate) / rate; // Checking if a liquidation is needed: for this to happen the `cashOutAmount` should be inferior // to the maintenance margin of the perpetual reachMaintenanceMargin; if (newCommit >= perpetual.committedAmount + perpetual.margin) cashOutAmount = 0; else { // The definition of the margin ratio is `(margin + PnL) / committedAmount` // where `PnL = commit * (1-entryRate/currentRate)` // So here: `newCashOutAmount = margin + PnL` cashOutAmount = perpetual.committedAmount + perpetual.margin - newCommit; if (cashOutAmount * BASE_PARAMS <= perpetual.committedAmount * maintenanceMargin) reachMaintenanceMargin = 1; } } /// @notice Calls the oracle to read both Chainlink and Uniswap rates /// @return The lowest oracle value (between Chainlink and Uniswap) is the first outputted value /// @return The highest oracle value is the second output /// @dev If the oracle only involves a single oracle fees (like just Chainlink for USD-EUR), /// the same value is returned twice function _getOraclePrice() internal view returns (uint256, uint256) { return oracle.readAll(); } /// @notice Computes the incentive for the keeper as a function of the cash out amount of a liquidated perpetual /// which value falls below its maintenance margin /// @param cashOutAmount Value remaining in the perpetual /// @dev By computing keeper fees as a fraction of the cash out amount of a perpetual rather than as a fraction /// of the `committedAmount`, keepers are incentivized to react fast when a perpetual is below the maintenance margin /// @dev Perpetual exchange protocols typically compute liquidation fees using an equivalent of the `committedAmount`, /// this is not the case here function _computeKeeperLiquidationFees(uint256 cashOutAmount) internal view returns (uint256 keeperFees) { keeperFees = (cashOutAmount * keeperFeesLiquidationRatio) / BASE_PARAMS; keeperFees = keeperFees < keeperFeesLiquidationCap ? keeperFees : keeperFeesLiquidationCap; } /// @notice Gets the value of the hedge ratio that is the ratio between the amount currently hedged by HAs /// and the target amount that should be hedged by them /// @param currentHedgeAmount Amount currently covered by HAs /// @return ratio Ratio between the amount of collateral (in stablecoin value) currently hedged /// and the target amount to hedge function _computeHedgeRatio(uint256 currentHedgeAmount) internal view returns (uint64 ratio) { // Fetching info from the `StableMaster`: the amount to hedge is based on the `stocksUsers` // of the given collateral uint256 targetHedgeAmount = (_stableMaster.getStocksUsers() * targetHAHedge) / BASE_PARAMS; if (currentHedgeAmount < targetHedgeAmount) ratio = uint64((currentHedgeAmount * BASE_PARAMS) / targetHedgeAmount); else ratio = uint64(BASE_PARAMS); } // =========================== Fee Computation ================================= /// @notice Gets the net margin corrected from the fees at perpetual opening /// @param margin Amount brought in the perpetual at creation /// @param totalHedgeAmountUpdate Amount of stablecoins that this perpetual is going to insure /// @param committedAmount Committed amount in the perpetual, we need it to compute the fees /// paid by the HA /// @return netMargin Amount that will be written in the perpetual as the `margin` /// @dev The amount of stablecoins insured by a perpetual is `committedAmount * oracleRate / _collatBase` function _getNetMargin( uint256 margin, uint256 totalHedgeAmountUpdate, uint256 committedAmount ) internal view returns (uint256 netMargin) { // Checking if the HA has the right to open a perpetual with such amount // If HAs hedge more than the target amount, then new HAs will not be able to create perpetuals // The amount hedged by HAs after opening the perpetual is going to be: uint64 ratio = _computeHedgeRatio(totalHedgeAmount + totalHedgeAmountUpdate); require(ratio < uint64(BASE_PARAMS), "25"); // Computing the net margin of HAs to store in the perpetual: it consists simply in deducing fees // Those depend on how much is already hedged by HAs compared with what's to hedge uint256 haFeesDeposit = (haBonusMalusDeposit * _piecewiseLinear(ratio, xHAFeesDeposit, yHAFeesDeposit)) / BASE_PARAMS; // Fees are rounded to the advantage of the protocol haFeesDeposit = committedAmount - (committedAmount * (BASE_PARAMS - haFeesDeposit)) / BASE_PARAMS; // Fees are computed based on the committed amount of the perpetual // The following reverts if fees are too big compared to the margin netMargin = margin - haFeesDeposit; } /// @notice Gets the net amount to give to a HA (corrected from the fees) in case of a perpetual closing /// @param committedAmount Committed amount in the perpetual /// @param cashOutAmount The current cash out amount of the perpetual /// @param ratio What's hedged divided by what's to hedge /// @return netCashOutAmount Amount that will be distributed to the HA /// @return feesPaid Amount of fees paid by the HA at perpetual closing /// @dev This function is called by the `closePerpetual` and by the `forceClosePerpetuals` /// function /// @dev The amount of fees paid by the HA is used to compute the incentive given to HAs closing perpetuals /// when too much is covered function _getNetCashOutAmount( uint256 cashOutAmount, uint256 committedAmount, uint64 ratio ) internal view returns (uint256 netCashOutAmount, uint256 feesPaid) { feesPaid = (haBonusMalusWithdraw * _piecewiseLinear(ratio, xHAFeesWithdraw, yHAFeesWithdraw)) / BASE_PARAMS; // Rounding the fees at the protocol's advantage feesPaid = committedAmount - (committedAmount * (BASE_PARAMS - feesPaid)) / BASE_PARAMS; if (feesPaid >= cashOutAmount) { netCashOutAmount = 0; feesPaid = cashOutAmount; } else { netCashOutAmount = cashOutAmount - feesPaid; } } // ========================= Reward Distribution =============================== /// @notice View function to query the last timestamp at which a reward was distributed /// @return Current timestamp if a reward is being distributed or the last timestamp function _lastTimeRewardApplicable() internal view returns (uint256) { uint256 returnValue = block.timestamp < periodFinish ? block.timestamp : periodFinish; return returnValue; } /// @notice Used to actualize the `rewardPerTokenStored` /// @dev It adds to the reward per token: the time elapsed since the `rewardPerTokenStored` /// was last updated multiplied by the `rewardRate` divided by the number of tokens /// @dev Specific attention should be placed on the base here: `rewardRate` is in the base of the reward token /// and `totalHedgeAmount` is in `BASE_TOKENS` here: as this function concerns an amount of reward /// tokens, the output of this function should be in the base of the reward token too function _rewardPerToken() internal view returns (uint256) { if (totalHedgeAmount == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + ((_lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * BASE_TOKENS) / totalHedgeAmount; } /// @notice Allows a perpetual owner to withdraw rewards /// @param perpetualID ID of the perpetual which accumulated tokens /// @param hedge Perpetual commit amount times the entry rate /// @dev Internal version of the `getReward` function /// @dev In case where an approved address calls to close a perpetual, rewards are still going to get distributed /// to the owner of the perpetual, and not necessarily to the address getting the proceeds of the perpetual function _getReward(uint256 perpetualID, uint256 hedge) internal { _updateReward(perpetualID, hedge); uint256 reward = rewards[perpetualID]; if (reward > 0) { rewards[perpetualID] = 0; address owner = _owners[perpetualID]; // Attention here, there may be reentrancy attacks because of the following call // to an external contract done before other things are modified. Yet since the `rewardToken` // is mostly going to be a trusted contract controlled by governance (namely the ANGLE token), then // there is no point in putting an expensive `nonReentrant` modifier in the functions in `PerpetualManagerFront` // that allow indirect interactions with `_updateReward`. If new `rewardTokens` are set, we could think about // upgrading the `PerpetualManagerFront` contract rewardToken.safeTransfer(owner, reward); emit RewardPaid(owner, reward); } } /// @notice Allows to check the amount of gov tokens earned by a perpetual /// @param perpetualID ID of the perpetual which accumulated tokens /// @param hedge Perpetual commit amount times the entry rate /// @return Amount of gov tokens earned by the perpetual /// @dev A specific attention should be paid to have the base here: we consider that each HA stakes an amount /// equal to `committedAmount * entryRate / _collatBase`, here as the `hedge` corresponds to `committedAmount * entryRate`, /// we just need to divide by `_collatBase` /// @dev HAs earn reward tokens which are in base `BASE_TOKENS` function _earned(uint256 perpetualID, uint256 hedge) internal view returns (uint256) { return (hedge * (_rewardPerToken() - perpetualRewardPerTokenPaid[perpetualID])) / BASE_TOKENS / _collatBase + rewards[perpetualID]; } /// @notice Updates the amount of gov tokens earned by a perpetual /// @param perpetualID of the perpetual which earns tokens /// @param hedge Perpetual commit amount times the entry rate /// @dev When this function is called in the code, it has already been checked that the `perpetualID` /// exists function _updateReward(uint256 perpetualID, uint256 hedge) internal { rewardPerTokenStored = _rewardPerToken(); lastUpdateTime = _lastTimeRewardApplicable(); // No need to check if the `perpetualID` exists here, it has already been checked // in the code before when this internal function is called rewards[perpetualID] = _earned(perpetualID, hedge); perpetualRewardPerTokenPaid[perpetualID] = rewardPerTokenStored; } // =============================== ERC721 Logic ================================ /// @notice Gets the owner of a perpetual /// @param perpetualID ID of the concerned perpetual /// @return owner Owner of the perpetual function _ownerOf(uint256 perpetualID) internal view returns (address owner) { owner = _owners[perpetualID]; require(owner != address(0), "2"); } /// @notice Gets the addresses approved for a perpetual /// @param perpetualID ID of the concerned perpetual /// @return Address approved for this perpetual function _getApproved(uint256 perpetualID) internal view returns (address) { return _perpetualApprovals[perpetualID]; } /// @notice Safely transfers `perpetualID` token from `from` to `to`, checking first that contract recipients /// are aware of the ERC721 protocol to prevent tokens from being forever locked /// @param perpetualID ID of the concerned perpetual /// @param _data Additional data, it has no specified format and it is sent in call to `to` /// @dev This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. /// implement alternative mechanisms to perform token transfer, such as signature-based /// @dev Requirements: /// - `from` cannot be the zero address. /// - `to` cannot be the zero address. /// - `perpetualID` token must exist and be owned by `from`. /// - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. function _safeTransfer( address from, address to, uint256 perpetualID, bytes memory _data ) internal { _transfer(from, to, perpetualID); require(_checkOnERC721Received(from, to, perpetualID, _data), "24"); } /// @notice Returns whether `perpetualID` exists /// @dev Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll} /// @dev Tokens start existing when they are minted (`_mint`), /// and stop existing when they are burned (`_burn`) function _exists(uint256 perpetualID) internal view returns (bool) { return _owners[perpetualID] != address(0); } /// @notice Returns whether `spender` is allowed to manage `perpetualID` /// @dev `perpetualID` must exist function _isApprovedOrOwner(address spender, uint256 perpetualID) internal view returns (bool) { // The following checks if the perpetual exists address owner = _ownerOf(perpetualID); return (spender == owner || _getApproved(perpetualID) == spender || _operatorApprovals[owner][spender]); } /// @notice Mints `perpetualID` and transfers it to `to` /// @dev This method is equivalent to the `_safeMint` method used in OpenZeppelin ERC721 contract /// @dev `perpetualID` must not exist and `to` cannot be the zero address /// @dev Before calling this function it is checked that the `perpetualID` does not exist as it /// comes from a counter that has been incremented /// @dev Emits a {Transfer} event function _mint(address to, uint256 perpetualID) internal { _balances[to] += 1; _owners[perpetualID] = to; emit Transfer(address(0), to, perpetualID); require(_checkOnERC721Received(address(0), to, perpetualID, ""), "24"); } /// @notice Destroys `perpetualID` /// @dev `perpetualID` must exist /// @dev Emits a {Transfer} event function _burn(uint256 perpetualID) internal { address owner = _ownerOf(perpetualID); // Clear approvals _approve(address(0), perpetualID); _balances[owner] -= 1; delete _owners[perpetualID]; delete perpetualData[perpetualID]; emit Transfer(owner, address(0), perpetualID); } /// @notice Transfers `perpetualID` from `from` to `to` as opposed to {transferFrom}, /// this imposes no restrictions on msg.sender /// @dev `to` cannot be the zero address and `perpetualID` must be owned by `from` /// @dev Emits a {Transfer} event function _transfer( address from, address to, uint256 perpetualID ) internal { require(_ownerOf(perpetualID) == from, "1"); require(to != address(0), "26"); // Clear approvals from the previous owner _approve(address(0), perpetualID); _balances[from] -= 1; _balances[to] += 1; _owners[perpetualID] = to; emit Transfer(from, to, perpetualID); } /// @notice Approves `to` to operate on `perpetualID` function _approve(address to, uint256 perpetualID) internal { _perpetualApprovals[perpetualID] = to; emit Approval(_ownerOf(perpetualID), to, perpetualID); } /// @notice Internal function to invoke {IERC721Receiver-onERC721Received} on a target address /// The call is not executed if the target address is not a contract /// @param from Address representing the previous owner of the given token ID /// @param to Target address that will receive the tokens /// @param perpetualID ID of the token to be transferred /// @param _data Bytes optional data to send along with the call /// @return Bool whether the call correctly returned the expected magic value function _checkOnERC721Received( address from, address to, uint256 perpetualID, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(msg.sender, from, perpetualID, _data) returns ( bytes4 retval ) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("24"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // File contracts/perpetualManager/PerpetualManager.sol pragma solidity ^0.8.7; /// @title PerpetualManager /// @author Angle Core Team /// @notice `PerpetualManager` is the contract handling all the Hedging Agents positions and perpetuals /// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol /// @dev This file contains the functions of the `PerpetualManager` that can be interacted with /// by `StableMaster`, by the `PoolManager`, by the `FeeManager` and by governance contract PerpetualManager is PerpetualManagerInternal, IPerpetualManagerFunctions, IStakingRewardsFunctions, AccessControlUpgradeable, PausableUpgradeable { using SafeERC20 for IERC20; /// @notice Role for guardians, governors and `StableMaster` /// Made for the `StableMaster` to be able to update some parameters bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); /// @notice Role for `PoolManager` only bytes32 public constant POOLMANAGER_ROLE = keccak256("POOLMANAGER_ROLE"); // ============================== Modifiers ==================================== /// @notice Checks if the person interacting with the perpetual with `perpetualID` is approved /// @param caller Address of the person seeking to interact with the perpetual /// @param perpetualID ID of the concerned perpetual /// @dev Generally in `PerpetualManager`, perpetual owners should store the ID of the perpetuals /// they are able to interact with modifier onlyApprovedOrOwner(address caller, uint256 perpetualID) { require(_isApprovedOrOwner(caller, perpetualID), "21"); _; } /// @notice Checks if the message sender is the rewards distribution address modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "1"); _; } // =============================== Deployer ==================================== /// @notice Notifies the address of the `_feeManager` and of the `oracle` /// to this contract and grants the correct roles /// @param governorList List of governor addresses of the protocol /// @param guardian Address of the guardian of the protocol /// @param feeManager_ Reference to the `FeeManager` contract which will be able to update fees /// @param oracle_ Reference to the `oracle` contract which will be able to update fees /// @dev Called by the `PoolManager` contract when it is activated by the `StableMaster` /// @dev The `governorList` and `guardian` here are those of the `Core` contract function deployCollateral( address[] memory governorList, address guardian, IFeeManager feeManager_, IOracle oracle_ ) external override onlyRole(POOLMANAGER_ROLE) { for (uint256 i = 0; i < governorList.length; i++) { _grantRole(GUARDIAN_ROLE, governorList[i]); } // In the end guardian should be revoked by governance _grantRole(GUARDIAN_ROLE, guardian); _grantRole(GUARDIAN_ROLE, address(_stableMaster)); _feeManager = feeManager_; oracle = oracle_; } // ========================== Rewards Distribution ============================= /// @notice Notifies the contract that rewards are going to be shared among HAs of this pool /// @param reward Amount of governance tokens to be distributed to HAs /// @dev Only the reward distributor contract is allowed to call this function which starts a staking cycle /// @dev This function is the equivalent of the `notifyRewardAmount` function found in all staking contracts function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution { rewardPerTokenStored = _rewardPerToken(); if (block.timestamp >= periodFinish) { // If the period is not done, then the reward rate changes rewardRate = reward / rewardsDuration; } else { uint256 remaining = periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; // If the period is not over, we compute the reward left and increase reward duration rewardRate = (reward + leftover) / rewardsDuration; } // Ensuring the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of `rewardRate` in the earned and `rewardsPerToken` functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = rewardToken.balanceOf(address(this)); require(rewardRate <= balance / rewardsDuration, "22"); lastUpdateTime = block.timestamp; // Change the duration periodFinish = block.timestamp + rewardsDuration; emit RewardAdded(reward); } /// @notice Supports recovering LP Rewards from other systems such as BAL to be distributed to holders /// or tokens that were mistakenly /// @param tokenAddress Address of the token to transfer /// @param to Address to give tokens to /// @param tokenAmount Amount of tokens to transfer function recoverERC20( address tokenAddress, address to, uint256 tokenAmount ) external override onlyRewardsDistribution { require(tokenAddress != address(rewardToken), "20"); IERC20(tokenAddress).safeTransfer(to, tokenAmount); emit Recovered(tokenAddress, to, tokenAmount); } /// @notice Changes the `rewardsDistribution` associated to this contract /// @param _rewardsDistribution Address of the new rewards distributor contract /// @dev This function is part of the staking rewards interface and it is used to propagate /// a change of rewards distributor notified by the current `rewardsDistribution` address /// @dev It has already been checked in the `RewardsDistributor` contract calling /// this function that the `newRewardsDistributor` had a compatible reward token /// @dev With this function, everything is as if `rewardsDistribution` was admin of its own role function setNewRewardsDistribution(address _rewardsDistribution) external override onlyRewardsDistribution { rewardsDistribution = _rewardsDistribution; emit RewardsDistributionUpdated(_rewardsDistribution); } // ================================= Keepers =================================== /// @notice Updates all the fees not depending on individual HA conditions via keeper utils functions /// @param feeDeposit New deposit global fees /// @param feeWithdraw New withdraw global fees /// @dev Governance may decide to incorporate a collateral ratio dependence in the fees for HAs, /// in this case it will be done through the `FeeManager` contract /// @dev This dependence can either be a bonus or a malus function setFeeKeeper(uint64 feeDeposit, uint64 feeWithdraw) external override { require(msg.sender == address(_feeManager), "1"); haBonusMalusDeposit = feeDeposit; haBonusMalusWithdraw = feeWithdraw; } // ======== Governance - Guardian Functions - Staking and Pauses =============== /// @notice Pauses the `getReward` method as well as the functions allowing to open, modify or close perpetuals /// @dev After calling this function, it is going to be impossible for HAs to interact with their perpetuals /// or claim their rewards on it function pause() external override onlyRole(GUARDIAN_ROLE) { _pause(); } /// @notice Unpauses HAs functions function unpause() external override onlyRole(GUARDIAN_ROLE) { _unpause(); } /// @notice Sets the conditions and specifies the duration of the reward distribution /// @param _rewardsDuration Duration for the rewards for this contract /// @param _rewardsDistribution Address which will give the reward tokens /// @dev It allows governance to directly change the rewards distribution contract and the conditions /// at which this distribution is done /// @dev The compatibility of the reward token is not checked here: it is checked /// in the rewards distribution contract when activating this as a staking contract, /// so if a reward distributor is set here but does not have a compatible reward token, then this reward /// distributor will not be able to set this contract as a staking contract function setRewardDistribution(uint256 _rewardsDuration, address _rewardsDistribution) external onlyRole(GUARDIAN_ROLE) zeroCheck(_rewardsDistribution) { rewardsDuration = _rewardsDuration; rewardsDistribution = _rewardsDistribution; emit RewardsDistributionDurationUpdated(rewardsDuration, rewardsDistribution); } // ============ Governance - Guardian Functions - Parameters =================== /// @notice Sets `baseURI` that is the URI to access ERC721 metadata /// @param _baseURI New `baseURI` parameter function setBaseURI(string memory _baseURI) external onlyRole(GUARDIAN_ROLE) { baseURI = _baseURI; emit BaseURIUpdated(_baseURI); } /// @notice Sets `lockTime` that is the minimum amount of time HAs have to stay within the protocol /// @param _lockTime New `lockTime` parameter /// @dev This parameter is used to prevent HAs from exiting before a certain amount of time and taking advantage /// of insiders' information they may have due to oracle latency function setLockTime(uint64 _lockTime) external override onlyRole(GUARDIAN_ROLE) { lockTime = _lockTime; emit LockTimeUpdated(_lockTime); } /// @notice Changes the maximum leverage authorized (commit/margin) and the maintenance margin under which /// perpetuals can be liquidated /// @param _maxLeverage New value of the maximum leverage allowed /// @param _maintenanceMargin The new maintenance margin /// @dev For a perpetual, the leverage is defined as the ratio between the committed amount and the margin /// @dev For a perpetual, the maintenance margin is defined as the ratio between the margin ratio / the committed amount function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleFees(_maintenanceMargin) { // Checking the compatibility of the parameters require(BASE_PARAMS**2 > _maxLeverage * _maintenanceMargin, "8"); maxLeverage = _maxLeverage; maintenanceMargin = _maintenanceMargin; emit BoundsPerpetualUpdated(_maxLeverage, _maintenanceMargin); } /// @notice Sets `xHAFees` that is the thresholds of values of the ratio between what's covered (hedged) /// divided by what's to hedge with HAs at which fees will change as well as /// `yHAFees` that is the value of the deposit or withdraw fees at threshold /// @param _xHAFees Array of the x-axis value for the fees (deposit or withdraw) /// @param _yHAFees Array of the y-axis value for the fees (deposit or withdraw) /// @param deposit Whether deposit or withdraw fees should be updated /// @dev Evolution of the fees is linear between two values of thresholds /// @dev These x values should be ranked in ascending order /// @dev For deposit fees, the higher the x that is the ratio between what's to hedge and what's hedged /// the higher y should be (the more expensive it should be for HAs to come in) /// @dev For withdraw fees, evolution should follow an opposite logic function setHAFees( uint64[] memory _xHAFees, uint64[] memory _yHAFees, uint8 deposit ) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleInputArrays(_xHAFees, _yHAFees) { if (deposit == 1) { xHAFeesDeposit = _xHAFees; yHAFeesDeposit = _yHAFees; } else { xHAFeesWithdraw = _xHAFees; yHAFeesWithdraw = _yHAFees; } emit HAFeesUpdated(_xHAFees, _yHAFees, deposit); } /// @notice Sets the target and limit proportions of collateral from users that can be insured by HAs /// @param _targetHAHedge Proportion of collateral from users that HAs should hedge /// @param _limitHAHedge Proportion of collateral from users above which HAs can see their perpetuals /// cashed out /// @dev `targetHAHedge` equal to `BASE_PARAMS` means that all the collateral from users should be insured by HAs /// @dev `targetHAHedge` equal to 0 means HA should not cover (hedge) anything function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleFees(_targetHAHedge) onlyCompatibleFees(_limitHAHedge) { require(_targetHAHedge <= _limitHAHedge, "8"); limitHAHedge = _limitHAHedge; targetHAHedge = _targetHAHedge; // Updating the value in the `stableMaster` contract _stableMaster.setTargetHAHedge(_targetHAHedge); emit TargetAndLimitHAHedgeUpdated(_targetHAHedge, _limitHAHedge); } /// @notice Sets the portion of the leftover cash out amount of liquidated perpetuals that go to keepers /// @param _keeperFeesLiquidationRatio Proportion to keepers /// @dev This proportion should be inferior to `BASE_PARAMS` function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleFees(_keeperFeesLiquidationRatio) { keeperFeesLiquidationRatio = _keeperFeesLiquidationRatio; emit KeeperFeesLiquidationRatioUpdated(keeperFeesLiquidationRatio); } /// @notice Sets the maximum amounts going to the keepers when closing perpetuals /// because too much was hedged by HAs or when liquidating a perpetual /// @param _keeperFeesLiquidationCap Maximum reward going to the keeper liquidating a perpetual /// @param _keeperFeesClosingCap Maximum reward going to the keeper forcing the closing of an ensemble /// of perpetuals function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external override onlyRole(GUARDIAN_ROLE) { keeperFeesLiquidationCap = _keeperFeesLiquidationCap; keeperFeesClosingCap = _keeperFeesClosingCap; emit KeeperFeesCapUpdated(keeperFeesLiquidationCap, keeperFeesClosingCap); } /// @notice Sets the x-array (ie thresholds) for `FeeManager` when closing perpetuals and the y-array that is the /// value of the proportions of the fees going to keepers closing perpetuals /// @param _xKeeperFeesClosing Thresholds for closing fees /// @param _yKeeperFeesClosing Value of the fees at the different threshold values specified in `xKeeperFeesClosing` /// @dev The x thresholds correspond to values of the hedge ratio divided by two /// @dev `xKeeperFeesClosing` and `yKeeperFeesClosing` should have the same length function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleInputArrays(_xKeeperFeesClosing, _yKeeperFeesClosing) { xKeeperFeesClosing = _xKeeperFeesClosing; yKeeperFeesClosing = _yKeeperFeesClosing; emit KeeperFeesClosingUpdated(xKeeperFeesClosing, yKeeperFeesClosing); } // ================ Governance - `PoolManager` Functions ======================= /// @notice Changes the reference to the `FeeManager` contract /// @param feeManager_ New `FeeManager` contract /// @dev This allows the `PoolManager` contract to propagate changes to the `PerpetualManager` /// @dev This is the only place where the `_feeManager` can be changed, it is as if there was /// a `FEEMANAGER_ROLE` for which `PoolManager` was the admin function setFeeManager(IFeeManager feeManager_) external override onlyRole(POOLMANAGER_ROLE) { _feeManager = feeManager_; } // ======================= `StableMaster` Function ============================= /// @notice Changes the oracle contract used to compute collateral price with respect to the stablecoin's price /// @param oracle_ Oracle contract /// @dev The collateral `PoolManager` does not store a reference to an oracle, the value of the oracle /// is hence directly set by the `StableMaster` function setOracle(IOracle oracle_) external override { require(msg.sender == address(_stableMaster), "1"); oracle = oracle_; } } // File contracts/perpetualManager/PerpetualManagerFront.sol pragma solidity ^0.8.7; /// @title PerpetualManagerFront /// @author Angle Core Team /// @notice `PerpetualManager` is the contract handling all the Hedging Agents perpetuals /// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol /// @dev This file contains the functions of the `PerpetualManager` that can be directly interacted /// with by external agents. These functions are the ones that need to be called to open, modify or close /// perpetuals /// @dev `PerpetualManager` naturally handles staking, the code allowing HAs to stake has been inspired from /// https://github.com/SetProtocol/index-coop-contracts/blob/master/contracts/staking/StakingRewardsV2.sol /// @dev Perpetuals at Angle protocol are treated as NFTs, this contract handles the logic for that contract PerpetualManagerFront is PerpetualManager, IPerpetualManagerFront { using SafeERC20 for IERC20; using CountersUpgradeable for CountersUpgradeable.Counter; // =============================== Deployer ==================================== /// @notice Initializes the `PerpetualManager` contract /// @param poolManager_ Reference to the `PoolManager` contract handling the collateral associated to the `PerpetualManager` /// @param rewardToken_ Reference to the `rewardtoken` that can be distributed to HAs as they have open positions /// @dev The reward token is most likely going to be the ANGLE token /// @dev Since this contract is upgradeable, this function is an `initialize` and not a `constructor` /// @dev Zero checks are only performed on addresses for which no external calls are made, in this case just /// the `rewardToken_` is checked /// @dev After initializing this contract, all the fee parameters should be initialized by governance using /// the setters in this contract function initialize(IPoolManager poolManager_, IERC20 rewardToken_) external initializer zeroCheck(address(rewardToken_)) { // Initializing contracts __Pausable_init(); __AccessControl_init(); // Creating references poolManager = poolManager_; _token = IERC20(poolManager_.token()); _stableMaster = IStableMaster(poolManager_.stableMaster()); rewardToken = rewardToken_; _collatBase = 10**(IERC20Metadata(address(_token)).decimals()); // The references to the `feeManager` and to the `oracle` contracts are to be set when the contract is deployed // Setting up Access Control for this contract // There is no need to store the reference to the `PoolManager` address here // Once the `POOLMANAGER_ROLE` has been granted, no new addresses can be granted or revoked // from this role: a `PerpetualManager` contract can only have one `PoolManager` associated _setupRole(POOLMANAGER_ROLE, address(poolManager)); // `PoolManager` is admin of all the roles. Most of the time, changes are propagated from it _setRoleAdmin(GUARDIAN_ROLE, POOLMANAGER_ROLE); _setRoleAdmin(POOLMANAGER_ROLE, POOLMANAGER_ROLE); // Pausing the contract because it is not functional till the collateral has really been deployed by the // `StableMaster` _pause(); } /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} // ================================= HAs ======================================= /// @notice Lets a HA join the protocol and create a perpetual /// @param owner Address of the future owner of the perpetual /// @param margin Amount of collateral brought by the HA /// @param committedAmount Amount of collateral covered by the HA /// @param maxOracleRate Maximum oracle value that the HA wants to see stored in the perpetual /// @param minNetMargin Minimum net margin that the HA is willing to see stored in the perpetual /// @return perpetualID The ID of the perpetual opened by this HA /// @dev The future owner of the perpetual cannot be the zero address /// @dev It is possible to open a perpetual on behalf of someone else /// @dev The `maxOracleRate` parameter serves as a protection against oracle manipulations for HAs opening perpetuals /// @dev `minNetMargin` is a protection against too big variations in the fees for HAs function openPerpetual( address owner, uint256 margin, uint256 committedAmount, uint256 maxOracleRate, uint256 minNetMargin ) external override whenNotPaused zeroCheck(owner) returns (uint256 perpetualID) { // Transaction will revert anyway if `margin` is zero require(committedAmount > 0, "27"); // There could be a reentrancy attack as a call to an external contract is done before state variables // updates. Yet in this case, the call involves a transfer from the `msg.sender` to the contract which // eliminates the risk _token.safeTransferFrom(msg.sender, address(poolManager), margin); // Computing the oracle value // Only the highest oracle value (between Chainlink and Uniswap) we get is stored in the perpetual (, uint256 rateUp) = _getOraclePrice(); // Checking if the oracle rate is not too big: a too big oracle rate could mean for a HA that the price // has become too high to make it interesting to open a perpetual require(rateUp <= maxOracleRate, "28"); // Computing the total amount of stablecoins that this perpetual is going to hedge for the protocol uint256 totalHedgeAmountUpdate = (committedAmount * rateUp) / _collatBase; // Computing the net amount brought by the HAs to store in the perpetual uint256 netMargin = _getNetMargin(margin, totalHedgeAmountUpdate, committedAmount); require(netMargin >= minNetMargin, "29"); // Checking if the perpetual is not too leveraged, even after computing the fees require((committedAmount * BASE_PARAMS) <= maxLeverage * netMargin, "30"); // ERC721 logic _perpetualIDcount.increment(); perpetualID = _perpetualIDcount.current(); // In the logic of the staking contract, the `_updateReward` should be called // before the perpetual is opened _updateReward(perpetualID, 0); // Updating the total amount of stablecoins hedged by HAs and creating the perpetual totalHedgeAmount += totalHedgeAmountUpdate; perpetualData[perpetualID] = Perpetual(rateUp, block.timestamp, netMargin, committedAmount); // Following ERC721 logic, the function `_mint(...)` calls `_checkOnERC721Received` and could then be used as // a reentrancy vector. Minting should then only be done at the very end after updating all variables. _mint(owner, perpetualID); emit PerpetualOpened(perpetualID, rateUp, netMargin, committedAmount); } /// @notice Lets a HA close a perpetual owned or controlled for the stablecoin/collateral pair associated /// to this `PerpetualManager` contract /// @param perpetualID ID of the perpetual to close /// @param to Address which will receive the proceeds from this perpetual /// @param minCashOutAmount Minimum net cash out amount that the HA is willing to get for closing the /// perpetual /// @dev The HA gets the current amount of her position depending on the entry oracle value /// and current oracle value minus some transaction fees computed on the committed amount /// @dev `msg.sender` should be the owner of `perpetualID` or be approved for this perpetual /// @dev If the `PoolManager` does not have enough collateral, the perpetual owner will be converted to a SLP and /// receive sanTokens /// @dev The `minCashOutAmount` serves as a protection for HAs closing their perpetuals: it protects them both /// from fees that would have become too high and from a too big decrease in oracle value function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external override whenNotPaused onlyApprovedOrOwner(msg.sender, perpetualID) { // Loading perpetual data and getting the oracle price Perpetual memory perpetual = perpetualData[perpetualID]; (uint256 rateDown, ) = _getOraclePrice(); // The lowest oracle price between Chainlink and Uniswap is used to compute the perpetual's position at // the time of closing: it is the one that is most at the advantage of the protocol (uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown); if (liquidated == 0) { // You need to wait `lockTime` before being able to withdraw funds from the protocol as a HA require(perpetual.entryTimestamp + lockTime <= block.timestamp, "31"); // Cashing out the perpetual internally _closePerpetual(perpetualID, perpetual); // Computing exit fees: they depend on how much is already hedgeded by HAs compared with what's to hedge (uint256 netCashOutAmount, ) = _getNetCashOutAmount( cashOutAmount, perpetual.committedAmount, // The perpetual has already been cashed out when calling this function, so there is no // `committedAmount` to add to the `totalHedgeAmount` to get the `currentHedgeAmount` _computeHedgeRatio(totalHedgeAmount) ); require(netCashOutAmount >= minCashOutAmount, "32"); emit PerpetualClosed(perpetualID, netCashOutAmount); _secureTransfer(to, netCashOutAmount); } } /// @notice Lets a HA increase the `margin` in a perpetual she controls for this /// stablecoin/collateral pair /// @param perpetualID ID of the perpetual to which amount should be added to `margin` /// @param amount Amount to add to the perpetual's `margin` /// @dev This decreases the leverage multiple of this perpetual /// @dev If this perpetual is to be liquidated, the HA is not going to be able to add liquidity to it /// @dev Since this function can be used to add liquidity to a perpetual, there is no need to restrict /// it to the owner of the perpetual /// @dev Calling this function on a non-existing perpetual makes it revert function addToPerpetual(uint256 perpetualID, uint256 amount) external override whenNotPaused { // Loading perpetual data and getting the oracle price Perpetual memory perpetual = perpetualData[perpetualID]; (uint256 rateDown, ) = _getOraclePrice(); (, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown); if (liquidated == 0) { // Overflow check _token.safeTransferFrom(msg.sender, address(poolManager), amount); perpetualData[perpetualID].margin += amount; emit PerpetualUpdated(perpetualID, perpetual.margin + amount); } } /// @notice Lets a HA decrease the `margin` in a perpetual she controls for this /// stablecoin/collateral pair /// @param perpetualID ID of the perpetual from which collateral should be removed /// @param amount Amount to remove from the perpetual's `margin` /// @param to Address which will receive the collateral removed from this perpetual /// @dev This increases the leverage multiple of this perpetual /// @dev `msg.sender` should be the owner of `perpetualID` or be approved for this perpetual function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external override whenNotPaused onlyApprovedOrOwner(msg.sender, perpetualID) { // Loading perpetual data and getting the oracle price Perpetual memory perpetual = perpetualData[perpetualID]; (uint256 rateDown, ) = _getOraclePrice(); (uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown); if (liquidated == 0) { // Checking if money can be withdrawn from the perpetual require( // The perpetual should not have been opened too soon (perpetual.entryTimestamp + lockTime <= block.timestamp) && // The amount to withdraw should not be more important than the perpetual's `cashOutAmount` and `margin` (amount < cashOutAmount) && (amount < perpetual.margin) && // Withdrawing collateral should not make the leverage of the perpetual too important // Checking both on `cashOutAmount` and `perpetual.margin` (as we can have either // `cashOutAmount >= perpetual.margin` or `cashOutAmount<perpetual.margin`) // No checks are done on `maintenanceMargin`, as conditions on `maxLeverage` are more restrictive perpetual.committedAmount * BASE_PARAMS <= (cashOutAmount - amount) * maxLeverage && perpetual.committedAmount * BASE_PARAMS <= (perpetual.margin - amount) * maxLeverage, "33" ); perpetualData[perpetualID].margin -= amount; emit PerpetualUpdated(perpetualID, perpetual.margin - amount); _secureTransfer(to, amount); } } /// @notice Allows an outside caller to liquidate perpetuals if their margin ratio is /// under the maintenance margin /// @param perpetualIDs ID of the targeted perpetuals /// @dev Liquidation of a perpetual will succeed if the `cashOutAmount` of the perpetual is under the maintenance margin, /// and nothing will happen if the perpetual is still healthy /// @dev The outside caller (namely a keeper) gets a portion of the leftover cash out amount of the perpetual /// @dev As keepers may directly profit from this function, there may be front-running problems with miners bots, /// we may have to put an access control logic for this function to only allow white-listed addresses to act /// as keepers for the protocol function liquidatePerpetuals(uint256[] memory perpetualIDs) external override whenNotPaused { // Getting the oracle price (uint256 rateDown, ) = _getOraclePrice(); uint256 liquidationFees; for (uint256 i = 0; i < perpetualIDs.length; i++) { uint256 perpetualID = perpetualIDs[i]; if (_exists(perpetualID)) { // Loading perpetual data Perpetual memory perpetual = perpetualData[perpetualID]; (uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown); if (liquidated == 1) { // Computing the incentive for the keeper as a function of the `cashOutAmount` of the perpetual // This incentivizes keepers to react fast when the price starts to go below the liquidation // margin liquidationFees += _computeKeeperLiquidationFees(cashOutAmount); } } } emit KeeperTransferred(msg.sender, liquidationFees); _secureTransfer(msg.sender, liquidationFees); } /// @notice Allows an outside caller to close perpetuals if too much of the collateral from /// users is hedged by HAs /// @param perpetualIDs IDs of the targeted perpetuals /// @dev This function allows to make sure that the protocol will not have too much HAs for a long period of time /// @dev A HA that owns a targeted perpetual will get the current value of her perpetual /// @dev The call to the function above will revert if HAs cannot be cashed out /// @dev As keepers may directly profit from this function, there may be front-running problems with miners bots, /// we may have to put an access control logic for this function to only allow white-listed addresses to act /// as keepers for the protocol function forceClosePerpetuals(uint256[] memory perpetualIDs) external override whenNotPaused { // Getting the oracle prices // `rateUp` is used to compute the cost of manipulation of the covered amounts (uint256 rateDown, uint256 rateUp) = _getOraclePrice(); // Fetching `stocksUsers` to check if perpetuals cover too much collateral uint256 stocksUsers = _stableMaster.getStocksUsers(); uint256 targetHedgeAmount = (stocksUsers * targetHAHedge) / BASE_PARAMS; // `totalHedgeAmount` should be greater than the limit hedge amount require(totalHedgeAmount > (stocksUsers * limitHAHedge) / BASE_PARAMS, "34"); uint256 liquidationFees; uint256 cashOutFees; // Array of pairs `(owner, netCashOutAmount)` Pairs[] memory outputPairs = new Pairs[](perpetualIDs.length); for (uint256 i = 0; i < perpetualIDs.length; i++) { uint256 perpetualID = perpetualIDs[i]; address owner = _owners[perpetualID]; if (owner != address(0)) { // Loading perpetual data and getting the oracle price Perpetual memory perpetual = perpetualData[perpetualID]; // First checking if the perpetual should not be liquidated (uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown); if (liquidated == 1) { // This results in the perpetual being liquidated and the keeper being paid the same amount of fees as // what would have been paid if the perpetual had been liquidated using the `liquidatePerpetualFunction` // Computing the incentive for the keeper as a function of the `cashOutAmount` of the perpetual // This incentivizes keepers to react fast liquidationFees += _computeKeeperLiquidationFees(cashOutAmount); } else if (perpetual.entryTimestamp + lockTime <= block.timestamp) { // It is impossible to force the closing a perpetual that was just created: in the other case, this // function could be used to do some insider trading and to bypass the `lockTime` limit // If too much collateral is hedged by HAs, then the perpetual can be cashed out _closePerpetual(perpetualID, perpetual); uint64 ratioPostCashOut; // In this situation, `totalHedgeAmount` is the `currentHedgeAmount` if (targetHedgeAmount > totalHedgeAmount) { ratioPostCashOut = uint64((totalHedgeAmount * BASE_PARAMS) / targetHedgeAmount); } else { ratioPostCashOut = uint64(BASE_PARAMS); } // Computing how much the HA will get and the amount of fees paid at closing (uint256 netCashOutAmount, uint256 fees) = _getNetCashOutAmount( cashOutAmount, perpetual.committedAmount, ratioPostCashOut ); cashOutFees += fees; // Storing the owners of perpetuals that were forced cash out in a memory array to avoid // reentrancy attacks outputPairs[i] = Pairs(owner, netCashOutAmount); } // Checking if at this point enough perpetuals have been cashed out if (totalHedgeAmount <= targetHedgeAmount) break; } } uint64 ratio = (targetHedgeAmount == 0) ? 0 : uint64((totalHedgeAmount * BASE_PARAMS) / (2 * targetHedgeAmount)); // Computing the rewards given to the keeper calling this function // and transferring the rewards to the keeper // Using a cache value of `cashOutFees` to save some gas // The value below is the amount of fees that should go to the keeper forcing the closing of perpetuals // In the linear by part function, if `xKeeperFeesClosing` is greater than 0.5 (meaning we are not at target yet) // then keepers should get almost no fees cashOutFees = (cashOutFees * _piecewiseLinear(ratio, xKeeperFeesClosing, yKeeperFeesClosing)) / BASE_PARAMS; // The amount of fees that can go to keepers is capped by a parameter set by governance cashOutFees = cashOutFees < keeperFeesClosingCap ? cashOutFees : keeperFeesClosingCap; // A malicious attacker could take advantage of this function to take a flash loan, burn agTokens // to diminish the stocks users and then force close some perpetuals. We also need to check that assuming // really small burn transaction fees (of 0.05%), an attacker could make a profit with such flash loan // if current hedge is below the target hedge by making such flash loan. // The formula for the cost of such flash loan is: // `fees * (limitHAHedge - targetHAHedge) * stocksUsers / oracle` // In order to avoid doing multiplications after divisions, and to get everything in the correct base, we do: uint256 estimatedCost = (5 * (limitHAHedge - targetHAHedge) * stocksUsers * _collatBase) / (rateUp * 10000 * BASE_PARAMS); cashOutFees = cashOutFees < estimatedCost ? cashOutFees : estimatedCost; emit PerpetualsForceClosed(perpetualIDs, outputPairs, msg.sender, cashOutFees + liquidationFees); // Processing transfers after all calculations have been performed for (uint256 j = 0; j < perpetualIDs.length; j++) { if (outputPairs[j].netCashOutAmount > 0) { _secureTransfer(outputPairs[j].owner, outputPairs[j].netCashOutAmount); } } _secureTransfer(msg.sender, cashOutFees + liquidationFees); } // =========================== External View Function ========================== /// @notice Returns the `cashOutAmount` of the perpetual owned by someone at a given oracle value /// @param perpetualID ID of the perpetual /// @param rate Oracle value /// @return The `cashOutAmount` of the perpetual /// @return Whether the position of the perpetual is now too small compared with its initial position and should hence /// be liquidated /// @dev This function is used by the Collateral Settlement contract function getCashOutAmount(uint256 perpetualID, uint256 rate) external view override returns (uint256, uint256) { Perpetual memory perpetual = perpetualData[perpetualID]; return _getCashOutAmount(perpetual, rate); } // =========================== Reward Distribution ============================= /// @notice Allows to check the amount of reward tokens earned by a perpetual /// @param perpetualID ID of the perpetual to check function earned(uint256 perpetualID) external view returns (uint256) { return _earned(perpetualID, perpetualData[perpetualID].committedAmount * perpetualData[perpetualID].entryRate); } /// @notice Allows a perpetual owner to withdraw rewards /// @param perpetualID ID of the perpetual which accumulated tokens /// @dev Only an approved caller can claim the rewards for the perpetual with perpetualID function getReward(uint256 perpetualID) external whenNotPaused onlyApprovedOrOwner(msg.sender, perpetualID) { _getReward(perpetualID, perpetualData[perpetualID].committedAmount * perpetualData[perpetualID].entryRate); } // =============================== ERC721 logic ================================ /// @notice Gets the name of the NFT collection implemented by this contract function name() external pure override returns (string memory) { return "AnglePerp"; } /// @notice Gets the symbol of the NFT collection implemented by this contract function symbol() external pure override returns (string memory) { return "AnglePerp"; } /// @notice Gets the URI containing metadata /// @param perpetualID ID of the perpetual function tokenURI(uint256 perpetualID) external view override returns (string memory) { require(_exists(perpetualID), "2"); // There is no perpetual with `perpetualID` equal to 0, so the following variable is // always greater than zero uint256 temp = perpetualID; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (perpetualID != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(perpetualID % 10))); perpetualID /= 10; } return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, string(buffer))) : ""; } /// @notice Gets the balance of an owner /// @param owner Address of the owner /// @dev Balance here represents the number of perpetuals owned by a HA function balanceOf(address owner) external view override returns (uint256) { require(owner != address(0), "0"); return _balances[owner]; } /// @notice Gets the owner of the perpetual with ID perpetualID /// @param perpetualID ID of the perpetual function ownerOf(uint256 perpetualID) external view override returns (address) { return _ownerOf(perpetualID); } /// @notice Approves to an address specified by `to` a perpetual specified by `perpetualID` /// @param to Address to approve the perpetual to /// @param perpetualID ID of the perpetual /// @dev The approved address will have the right to transfer the perpetual, to cash it out /// on behalf of the owner, to add or remove collateral in it and to choose the destination /// address that will be able to receive the proceeds of the perpetual function approve(address to, uint256 perpetualID) external override { address owner = _ownerOf(perpetualID); require(to != owner, "35"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "21"); _approve(to, perpetualID); } /// @notice Gets the approved address by a perpetual owner /// @param perpetualID ID of the concerned perpetual function getApproved(uint256 perpetualID) external view override returns (address) { require(_exists(perpetualID), "2"); return _getApproved(perpetualID); } /// @notice Sets approval on all perpetuals owned by the owner to an operator /// @param operator Address to approve (or block) on all perpetuals /// @param approved Whether the sender wants to approve or block the operator function setApprovalForAll(address operator, bool approved) external override { require(operator != msg.sender, "36"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /// @notice Gets if the operator address is approved on all perpetuals by the owner /// @param owner Owner of perpetuals /// @param operator Address to check if approved function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /// @notice Gets if the sender address is approved for the perpetualId /// @param perpetualID ID of the perpetual function isApprovedOrOwner(address spender, uint256 perpetualID) external view override returns (bool) { return _isApprovedOrOwner(spender, perpetualID); } /// @notice Transfers the `perpetualID` from an address to another /// @param from Source address /// @param to Destination a address /// @param perpetualID ID of the perpetual to transfer function transferFrom( address from, address to, uint256 perpetualID ) external override onlyApprovedOrOwner(msg.sender, perpetualID) { _transfer(from, to, perpetualID); } /// @notice Safely transfers the `perpetualID` from an address to another without data in it /// @param from Source address /// @param to Destination a address /// @param perpetualID ID of the perpetual to transfer function safeTransferFrom( address from, address to, uint256 perpetualID ) external override { safeTransferFrom(from, to, perpetualID, ""); } /// @notice Safely transfers the `perpetualID` from an address to another with data in the transfer /// @param from Source address /// @param to Destination a address /// @param perpetualID ID of the perpetual to transfer function safeTransferFrom( address from, address to, uint256 perpetualID, bytes memory _data ) public override onlyApprovedOrOwner(msg.sender, perpetualID) { _safeTransfer(from, to, perpetualID, _data); } // =============================== ERC165 logic ================================ /// @notice Queries if a contract implements an interface /// @param interfaceId The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function uses less than 30,000 gas. /// Required by the ERC721 standard, so used to check that the IERC721 is implemented. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external pure override(IERC165) returns (bool) { return interfaceId == type(IPerpetualManagerFront).interfaceId || interfaceId == type(IPerpetualManagerFunctions).interfaceId || interfaceId == type(IStakingRewards).interfaceId || interfaceId == type(IStakingRewardsFunctions).interfaceId || interfaceId == type(IAccessControl).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC165).interfaceId; } }
Safely transfers the `perpetualID` from an address to another without data in it from Source address to Destination a address perpetualID ID of the perpetual to transfer
function safeTransferFrom( address from, address to, uint256 perpetualID ) external override { safeTransferFrom(from, to, perpetualID, ""); }
7,761,030
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./NectarToken.sol"; contract OfferMultiSig is Pausable { using SafeMath for uint256; string public constant VERSION = "1.2.0"; string public constant NAME = "Offer MultiSig"; uint256 public constant MIN_SETTLEMENT_PERIOD = 10; uint256 public constant MAX_SETTLEMENT_PERIOD = 3600; event CommunicationsSet( bytes32 websocketUri ); event OpenedAgreement( address _ambassador ); event CanceledAgreement( address _ambassador ); event JoinedAgreement( address _expert ); event ClosedAgreement( address _expert, address _ambassador ); event FundsDeposited( address _ambassador, address _expert, uint256 ambassadorBalance, uint256 expertBalance ); event StartedSettle( address initiator, uint sequence, uint settlementPeriodEnd ); event SettleStateChallenged( address challenger, uint sequence, uint settlementPeriodEnd ); address public nectarAddress; // Address of offer nectar token address public ambassador; // Address of first channel participant address public expert; // Address of second channel participant bool public isOpen = false; // true when both parties have joined bool public isPending = false; // true when waiting for counterparty to join agreement uint public settlementPeriodLength; // How long challengers have to reply to settle engagement uint public isClosed; // if the period has closed uint public sequence; // state nonce used in during settlement uint public isInSettlementState; // meta channel is in settling 1: Not settling 0 uint public settlementPeriodEnd; // The time when challenges are no longer accepted after bytes public state; // the current state bytes32 public websocketUri; // a geth node running whisper (shh) constructor(address _nectarAddress, address _ambassador, address _expert, uint _settlementPeriodLength) public { require(_ambassador != address(0), "No ambassador lib provided to constructor"); require(_expert != address(0), "No expert provided to constructor"); require(_nectarAddress != address(0), "No token provided to constructor"); // solium-disable-next-line indentation require(_settlementPeriodLength >= MIN_SETTLEMENT_PERIOD && _settlementPeriodLength <= MAX_SETTLEMENT_PERIOD, "Settlement period out of range"); ambassador = _ambassador; expert = _expert; settlementPeriodLength = _settlementPeriodLength; nectarAddress = _nectarAddress; } /** Function only callable by participants */ modifier onlyParticipants() { require(msg.sender == ambassador || msg.sender == expert, "msg.sender is not a participant"); _; } /** * Function called by ambassador to open channel with _expert * * @param _state inital offer state * @param _v the recovery id from signature of state * @param _r output of ECDSA signature of state * @param _s output of ECDSA signature of state */ function openAgreement(bytes memory _state, uint8 _v, bytes32 _r, bytes32 _s) public whenNotPaused { // require the channel is not open yet require(isOpen == false, "openAgreement already called, isOpen true"); require(isPending == false, "openAgreement already called, isPending true"); require(msg.sender == ambassador, "msg.sender is not the ambassador"); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(msg.sender == getPartyA(_state), "Party A does not match signature recovery"); // check the account opening a channel signed the initial state address initiator = getSig(_state, _v, _r, _s); require(ambassador == initiator, "Initiator in state is not the ambassador"); isPending = true; state = _state; open(_state); emit OpenedAgreement(ambassador); } /** * Function called by ambassador to cancel a channel that hasn't been joined yet */ function cancelAgreement() public whenNotPaused { // require the channel is not open yet require(isPending == true, "Only a channel in a pending state can be canceled"); require(msg.sender == ambassador, "Only an ambassador can cancel an agreement"); isPending = false; cancel(nectarAddress); emit CanceledAgreement(ambassador); } /** * Function called by expert to complete opening the channel with an ambassador defined in the _state * * @param _state offer state from ambassador * @param _v the recovery id from signature of state * @param _r output of ECDSA signature of state * @param _s output of ECDSA signature of state */ function joinAgreement(bytes memory _state, uint8 _v, bytes32 _r, bytes32 _s) public whenNotPaused { require(isOpen == false, "openAgreement already called, isOpen true"); require(msg.sender == expert, "msg.sender is not the expert"); require(isPending, "Offer not pending"); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); // check that the state is signed by the sender and sender is in the state address joiningParty = getSig(_state, _v, _r, _s); require(expert == joiningParty, "Joining party in state is not the expert"); // no longer allow joining functions to be called isOpen = true; isPending = false; join(state); emit JoinedAgreement(expert); } /** * Function called by ambassador to update balance and add to escrow * by default to escrows the allowed balance * @param _state offer state from ambassador * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties * @dev index 0 is the ambassador signature * @dev index 1 is the expert signature */ function depositFunds( bytes memory _state, uint8[2] memory _sigV, bytes32[2] memory _sigR, bytes32[2] memory _sigS) public onlyParticipants whenNotPaused { require(isOpen == true, "Tried adding funds to a closed msig wallet"); address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); // Require both signatures require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); state = _state; update(_state); emit FundsDeposited(_ambassador, _expert, getBalanceA(_state), getBalanceB(_state)); } /** * Function called by ambassador or expert to close a their channel after a dispute has timedout * * @param _state final offer state agreed on by both parties through dispute settlement * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties * @dev index 0 is the ambassador signature * @dev index 1 is the expert signature */ function closeAgreementWithTimeout( bytes memory _state, uint8[2] memory _sigV, bytes32[2] memory _sigR, bytes32[2] memory _sigS) public onlyParticipants whenNotPaused { address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(settlementPeriodEnd <= block.number, "Settlement period hasn't ended"); require(isClosed == 0, "Offer is closed"); require(isInSettlementState == 1, "Offer is not in settlement state"); require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); require(keccak256(state) == keccak256(_state), "State hash mismatch"); isClosed = 1; finalize(_state); isOpen = false; emit ClosedAgreement(_expert, _ambassador); } /** * Function called by ambassador or expert to close a their channel with close flag * * @param _state final offer state agreed on by both parties with close flag * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties * @dev index 0 is the ambassador signature * @dev index 1 is the expert signature */ function closeAgreement( bytes memory _state, uint8[2] memory _sigV, bytes32[2] memory _sigR, bytes32[2] memory _sigS) public onlyParticipants whenNotPaused { address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(isClosed == 0, "Offer is closed"); /// @dev make sure we're not in dispute require(isInSettlementState == 0, "Offer is in settlement state"); /// @dev must have close flag require(_isClosed(_state), "State did not have a signed close out state"); require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); isClosed = 1; state = _state; finalize(_state); isOpen = false; emit ClosedAgreement(_expert, _ambassador); } /** * Function called by ambassador or expert to start initalize a disputed settlement * using an agreed upon state. It starts a timeout for a reply using `settlementPeriodLength` * * @param _state offer state agreed on by both parties * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties */ function startSettle( bytes memory _state, uint8[2] memory _sigV, bytes32[2] memory _sigR, bytes32[2] memory _sigS) public onlyParticipants whenNotPaused { address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); require(isClosed == 0, "Offer is closed"); require(isInSettlementState == 0, "Offer is in settlement state"); state = _state; sequence = getSequence(_state); isInSettlementState = 1; settlementPeriodEnd = block.number.add(settlementPeriodLength); emit StartedSettle(msg.sender, sequence, settlementPeriodEnd); } /** * Function called by ambassador or expert to challenge a disputed state * The new state is accepted if it is signed by both parties and has a higher sequence number * * @param _state offer state agreed on by both parties * @param _sigV the recovery id from signature of state by both parties * @param _sigR output of ECDSA signature of state by both parties * @param _sigS output of ECDSA signature of state by both parties */ function challengeSettle( bytes memory _state, uint8[2] memory _sigV, bytes32[2] memory _sigR, bytes32[2] memory _sigS) public onlyParticipants whenNotPaused { address _ambassador = getSig(_state, _sigV[0], _sigR[0], _sigS[0]); address _expert = getSig(_state, _sigV[1], _sigR[1], _sigS[1]); require(getTokenAddress(_state) == nectarAddress, "Invalid token address"); require(_hasAllSigs(_ambassador, _expert), "Missing signatures"); require(isInSettlementState == 1, "Offer is not in settlement state"); require(block.number < settlementPeriodEnd, "Settlement period has ended"); require(getSequence(_state) > sequence, "Sequence number is too old"); settlementPeriodEnd = block.number.add(settlementPeriodLength); state = _state; sequence = getSequence(_state); emit SettleStateChallenged(msg.sender, sequence, settlementPeriodEnd); } /** * Return when the settlement period is going to end. This is the amount of time * an ambassor or expert has to reply with a new state */ function getSettlementPeriodEnd() public view returns (uint) { return settlementPeriodEnd; } /** * Function to be called by ambassador to set comunication information * * @param _websocketUri uri of whisper node */ function setCommunicationUri(bytes32 _websocketUri) external whenNotPaused { require(msg.sender == ambassador, "msg.sender is not the ambassador"); websocketUri = _websocketUri; emit CommunicationsSet(websocketUri); } /** * Function called to get the state sequence/nonce * * @param _state offer state */ function getSequence(bytes memory _state) public pure returns (uint _seq) { // solium-disable-next-line security/no-inline-assembly assembly { _seq := mload(add(_state, 64)) } } function isChannelOpen() public view returns (bool) { return isOpen; } function getWebsocketUri() public view returns (bytes32) { return websocketUri; } /** * A utility function to check if both parties have signed * * @param _a ambassador address * @param _b expert address */ function _hasAllSigs(address _a, address _b) internal view returns (bool) { require(_a == ambassador && _b == expert, "Signatures do not match parties in state"); return true; } /** * A utility function to check for the closed flag in the offer state * * @param _state current offer state */ function _isClosed(bytes memory _state) internal pure returns (bool) { require(getCloseFlag(_state) == 1, "Offer is not closed"); return true; } function getCloseFlag(bytes memory _state) public pure returns (uint8 _flag) { // solium-disable-next-line security/no-inline-assembly assembly { _flag := mload(add(_state, 32)) } } function getPartyA(bytes memory _state) public pure returns (address _ambassador) { // solium-disable-next-line security/no-inline-assembly assembly { _ambassador := mload(add(_state, 96)) } } function getPartyB(bytes memory _state) public pure returns (address _expert) { // solium-disable-next-line security/no-inline-assembly assembly { _expert := mload(add(_state, 128)) } } function getBalanceA(bytes memory _state) public pure returns (uint256 _balanceA) { // solium-disable-next-line security/no-inline-assembly assembly { _balanceA := mload(add(_state, 192)) } } function getBalanceB(bytes memory _state) public pure returns (uint256 _balanceB) { // solium-disable-next-line security/no-inline-assembly assembly { _balanceB := mload(add(_state, 224)) } } function getTokenAddress(bytes memory _state) public pure returns (address _token) { // solium-disable-next-line security/no-inline-assembly assembly { _token := mload(add(_state, 256)) } } function getTotal(bytes memory _state) public pure returns (uint256) { uint256 _a = getBalanceA(_state); uint256 _b = getBalanceB(_state); return _a.add(_b); } function open(bytes memory _state) internal returns (bool) { require(msg.sender == getPartyA(_state), "Party A does not match signature recovery"); // get the token instance used to allow funds to msig NectarToken _t = NectarToken(getTokenAddress(_state)); // ensure the amount sent to open channel matches the signed state balance require(_t.allowance(getPartyA(_state), address(this)) == getBalanceA(_state), "value does not match ambassador state balance"); // complete the tranfer of ambassador approved tokens require(_t.transferFrom(getPartyA(_state), address(this), getBalanceA(_state)), "failed tranfering approved balance from ambassador"); return true; } function join(bytes memory _state) internal view returns (bool) { // get the token instance used to allow funds to msig NectarToken _t = NectarToken(getTokenAddress(_state)); // ensure the amount sent to join channel matches the signed state balance require(msg.sender == getPartyB(_state), "Party B does not match signature recovery"); // Require bonded is the sum of balances in state require(getTotal(_state) == _t.balanceOf(address(this)), "token total deposited does not match state balance"); return true; } function update(bytes memory _state) internal returns (bool) { // get the token instance used to allow funds to msig NectarToken _t = NectarToken(getTokenAddress(_state)); if(_t.allowance(getPartyA(_state), address(this)) > 0) { require(_t.transferFrom(getPartyA(_state), address(this), _t.allowance(getPartyA(_state), address(this))), "failed transfering deposit from party A to contract"); } require(getTotal(_state) == _t.balanceOf(address(this)), "token total deposited does not match state balance"); } function cancel(address tokenAddress) internal returns (bool) { NectarToken _t = NectarToken(tokenAddress); return _t.transfer(msg.sender, _t.balanceOf(address(this))); } /** * Function called by closeAgreementWithTimeout or closeAgreement to disperse payouts * * @param _state final offer state agreed on by both parties with close flag */ function finalize(bytes memory _state) internal returns (bool) { address _a = getPartyA(_state); address _b = getPartyB(_state); NectarToken _t = NectarToken(getTokenAddress(_state)); require(getTotal(_state) == _t.balanceOf(address(this)), "tried finalizing token state that does not match bonded value"); require(_t.transfer(_a, getBalanceA(_state)), "failed transfering balance to party A"); require(_t.transfer(_b, getBalanceB(_state)), "failed transfering balance to party B"); } /** * A utility function to return the address of the person that signed the state * * @param _state offer state that was signed * @param _v the recovery id from signature of state by both parties * @param _r output of ECDSA signature of state by both parties * @param _s output of ECDSA signature of state by both parties */ function getSig(bytes memory _state, uint8 _v, bytes32 _r, bytes32 _s) internal pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 h = keccak256(_state); bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, h)); address a = ecrecover(prefixedHash, _v, _r, _s); return a; } }
solium-disable-next-line security/no-inline-assembly
function getTokenAddress(bytes memory _state) public pure returns (address _token) { assembly { _token := mload(add(_state, 256)) } }
2,509,414
./full_match/80001/0x2CFA8424EE31DFaf0Bb315a94593f5B34b28B0fb/sources/contracts/WasteDisposalSystem.sol
Function to retrieve a list of all waste disposal reports stored in the app.
function getReports() public view returns (Report[] memory) { Report[] memory allReports = new Report[](reportCount); for (uint256 i = 0; i < reportCount; i++) { allReports[i] = reports[i]; } return allReports; }
5,614,100
pragma solidity ^0.4.24; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : dave@akomba.com // released under Apache 2.0 licence library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Owned { event OwnershipTransferred(address indexed _from, address indexed _to); address public owner; address public newOwner; modifier onlyOwner { require(msg.sender == owner); _; } constructor() public { owner = msg.sender; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); owner = newOwner; newOwner = address(0); emit OwnershipTransferred(owner, newOwner); } } contract StandardToken is ERC20 { using SafeMath for uint256; uint256 totalSupply_; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) internal allowed; /** * @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(_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 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 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 Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, 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; } } library SafeERC20 { function safeTransfer(ERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } contract PetCoin is StandardToken, Owned { using SafeMath for uint256; // Token metadata string public constant name = "Petcoin"; string public constant symbol = "PETC"; uint256 public constant decimals = 18; // Token supply breakdown uint256 public constant initialSupply = 2340 * (10**6) * 10**decimals; // 2.34 billion uint256 public constant stageOneSupply = (10**5) * 10**decimals; // 100,000 tokens for ICO stage 1 uint256 public constant stageTwoSupply = (10**6) * 10**decimals; // 1,000,000 tokens for ICO stage 2 uint256 public constant stageThreeSupply = (10**7) * 10**decimals; // 10,000,000 tokens for ICO stage 3 // Initial Token holder addresses. // one billion token holders address public constant appWallet = 0x9F6899364610B96D7718Fe3c03A6BD1Deb8623CE; address public constant genWallet = 0x530E6B9A17e9AbB77CF4E125b99Bf5D5CAD69942; // one hundred million token holders address public constant ceoWallet = 0x388Ed3f7Aa1C4461460197FcCE5cfEf84D562c6A; address public constant cooWallet = 0xa2c59e6a91B4E502CF8C95A61F50D3aB1AB30cBA; address public constant devWallet = 0x7D2ea29E2d4A95f4725f52B941c518C15eAE3c64; // the rest token holder address public constant poolWallet = 0x7e75fe6b73993D9Be9cb975364ec70Ee2C22c13A; // mint configuration uint256 public constant yearlyMintCap = (10*7) * 10*decimals; //10,000,000 tokens each year uint16 public mintStartYear = 2019; uint16 public mintEndYear = 2118; mapping (uint16 => bool) minted; constructor() public { totalSupply_ = initialSupply.add(stageOneSupply).add(stageTwoSupply).add(stageThreeSupply); uint256 oneBillion = (10**9) * 10**decimals; uint256 oneHundredMillion = 100 * (10**6) * 10**decimals; balances[appWallet] = oneBillion; emit Transfer(address(0), appWallet, oneBillion); balances[genWallet] = oneBillion; emit Transfer(address(0), genWallet, oneBillion); balances[ceoWallet] = oneHundredMillion; emit Transfer(address(0), ceoWallet, oneHundredMillion); balances[cooWallet] = oneHundredMillion; emit Transfer(address(0), cooWallet, oneHundredMillion); balances[devWallet] = oneHundredMillion; emit Transfer(address(0), devWallet, oneHundredMillion); balances[poolWallet] = initialSupply.sub(balances[appWallet]) .sub(balances[genWallet]) .sub(balances[ceoWallet]) .sub(balances[cooWallet]) .sub(balances[devWallet]); emit Transfer(address(0), poolWallet, balances[poolWallet]); balances[msg.sender] = stageOneSupply.add(stageTwoSupply).add(stageThreeSupply); emit Transfer(address(0), msg.sender, balances[msg.sender]); } event Mint(address indexed to, uint256 amount); /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @return A boolean that indicates if the operation was successful. */ function mint( address _to ) onlyOwner external returns (bool) { uint16 year = _getYear(now); require (year >= mintStartYear && year <= mintEndYear && !minted[year]); require (_to != address(0)); totalSupply_ = totalSupply_.add(yearlyMintCap); balances[_to] = balances[_to].add(yearlyMintCap); minted[year] = true; emit Mint(_to, yearlyMintCap); emit Transfer(address(0), _to, yearlyMintCap); return true; } function _getYear(uint256 timestamp) internal pure returns (uint16) { uint16 ORIGIN_YEAR = 1970; uint256 YEAR_IN_SECONDS = 31536000; uint256 LEAP_YEAR_IN_SECONDS = 31622400; uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = _leapYearsBefore(year) - _leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (_isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function _isLeapYear(uint16 year) internal pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function _leapYearsBefore(uint year) internal pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } } contract PetCoinCrowdSale is Owned { using SafeMath for uint256; using SafeERC20 for PetCoin; // Conversion rates uint256 public stageOneRate = 4500; // 1 ETH = 4500 PETC uint256 public stageTwoRate = 3000; // 1 ETH = 3000 PETC uint256 public stageThreeRate = 2557; // 1 ETH = 2557 PETC // The token being sold PetCoin public token; // Address where funds are collected address public wallet; // Amount of wei raised uint256 public weiRaised; // Token Sale State Definitions enum TokenSaleState { NOT_STARTED, STAGE_ONE, STAGE_TWO, STAGE_THREE, COMPLETED } TokenSaleState public state; struct Stage { uint256 rate; uint256 remaining; } // Enum as mapping key not supported by Solidity yet mapping(uint256 => Stage) public stages; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, uint256 value, uint256 amount ); /** * Event for refund in case remaining tokens are not sufficient * @param purchaser who paid for the tokens * @param value weis refunded */ event Refund( address indexed purchaser, uint256 value ); /** * Event for move stage * @param oldState old state * @param newState new state */ event MoveStage( TokenSaleState oldState, TokenSaleState newState ); /** * Event for rates update * @param who updated the rates * @param stageOneRate new stageOneRate * @param stageTwoRate new stageTwoRate * @param stageThreeRate new stageThreeRate */ event RatesUpdate( address indexed who, uint256 stageOneRate, uint256 stageTwoRate, uint256 stageThreeRate ); /** * @param _token Address of the token being sold * @param _wallet Address where collected funds will be forwarded to */ constructor(PetCoin _token, address _wallet) public { require(_token != address(0)); require(_wallet != address(0)); token = _token; wallet = _wallet; state = TokenSaleState.NOT_STARTED; stages[uint256(TokenSaleState.STAGE_ONE)] = Stage(stageOneRate, token.stageOneSupply()); stages[uint256(TokenSaleState.STAGE_TWO)] = Stage(stageTwoRate, token.stageTwoSupply()); stages[uint256(TokenSaleState.STAGE_THREE)] = Stage(stageThreeRate, token.stageThreeSupply()); } // Modifiers modifier notStarted() { require (state == TokenSaleState.NOT_STARTED); _; } modifier stageOne() { require (state == TokenSaleState.STAGE_ONE); _; } modifier stageTwo() { require (state == TokenSaleState.STAGE_TWO); _; } modifier stageThree() { require (state == TokenSaleState.STAGE_THREE); _; } modifier completed() { require (state == TokenSaleState.COMPLETED); _; } modifier saleInProgress() { require (state == TokenSaleState.STAGE_ONE || state == TokenSaleState.STAGE_TWO || state == TokenSaleState.STAGE_THREE); _; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- function kickoff() external onlyOwner notStarted { _moveStage(); } function updateRates(uint256 _stageOneRate, uint256 _stageTwoRate, uint256 _stageThreeRate) external onlyOwner { stageOneRate = _stageOneRate; stageTwoRate = _stageTwoRate; stageThreeRate = _stageThreeRate; stages[uint256(TokenSaleState.STAGE_ONE)].rate = stageOneRate; stages[uint256(TokenSaleState.STAGE_TWO)].rate = stageTwoRate; stages[uint256(TokenSaleState.STAGE_THREE)].rate = stageThreeRate; emit RatesUpdate(msg.sender, stageOneRate, stageTwoRate, stageThreeRate); } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable saleInProgress { require(stages[uint256(state)].rate > 0); require(stages[uint256(state)].remaining > 0); require(msg.value > 0); uint256 weiAmount = msg.value; uint256 refund = 0; // calculate token amount to be created uint256 tokens = weiAmount.mul(stages[uint256(state)].rate); if (tokens > stages[uint256(state)].remaining) { // calculate wei needed to purchase the remaining tokens tokens = stages[uint256(state)].remaining; weiAmount = tokens.div(stages[uint256(state)].rate); refund = msg.value - weiAmount; } // update state weiRaised = weiRaised.add(weiAmount); emit TokenPurchase( msg.sender, weiAmount, tokens ); // update remaining of the stage stages[uint256(state)].remaining -= tokens; assert(stages[uint256(state)].remaining >= 0); if (stages[uint256(state)].remaining == 0) { _moveStage(); } // transfer tokens to buyer token.safeTransfer(msg.sender, tokens); // forward ETH to the wallet _forwardFunds(weiAmount); if (refund > 0) { // refund the purchaser if required msg.sender.transfer(refund); emit Refund( msg.sender, refund ); } } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- function _moveStage() internal { TokenSaleState oldState = state; if (state == TokenSaleState.NOT_STARTED) { state = TokenSaleState.STAGE_ONE; } else if (state == TokenSaleState.STAGE_ONE) { state = TokenSaleState.STAGE_TWO; } else if (state == TokenSaleState.STAGE_TWO) { state = TokenSaleState.STAGE_THREE; } else if (state == TokenSaleState.STAGE_THREE) { state = TokenSaleState.COMPLETED; } emit MoveStage(oldState, state); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds(uint256 weiAmount) internal { wallet.transfer(weiAmount); } }
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 _spender The address which will spend the funds. _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; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
5,417,507
./partial_match/56/0x13abDF9645E971188DA4425C994B89488a848f4c/sources/MasterChef.sol
View function to see pending SMILEs on frontend.
function pendingSmile(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSmilePerShare = pool.accSmilePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 smileReward = multiplier.mul(smilePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSmilePerShare = accSmilePerShare.add(smileReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSmilePerShare).div(1e12).sub(user.rewardDebt); }
11,085,667
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.5; pragma abicoder v2; import "../libraries/SafeMath.sol"; import "../libraries/FixedPoint.sol"; import "../interfaces/IBondingCalculator.sol"; import "../interfaces/IXTokenWeth.sol"; import "../interfaces/INFTXLPStaking.sol"; import "../interfaces/INFTXVault.sol"; import "../interfaces/ITreasury.sol"; contract NFTXXTokenWethCalculator is IBondingCalculator { using FixedPoint for *; using SafeMath for uint256; INFTXLPStaking public immutable nftxLpStaking; ITreasury public immutable treasury; constructor(address _nftxLpStaking, address _treasury) { require(_nftxLpStaking != address(0), "Zero address: _nftxLpStaking"); require(_treasury!= address(0), "Zero address: _treasury"); nftxLpStaking = INFTXLPStaking(_nftxLpStaking); treasury = ITreasury(_treasury); } function valuation(address xTokenWeth_, uint256 amount_) external view override returns (uint256 _value) { IXTokenWeth _xTokenWeth = IXTokenWeth(xTokenWeth_); // Get the vault ID from the xToken address INFTXVault _nftxVault = INFTXVault(_xTokenWeth.target()); uint256 _vaultId = _nftxVault.vaultId(); // Return the Treasury value of the underlying SLP amount _value = treasury.tokenValue(_getStakingPool(_vaultId).stakingToken, amount_); } function _getStakingPool(uint256 _vaultId) internal view returns (INFTXLPStaking.StakingPool memory stakingPool) { stakingPool = nftxLpStaking.vaultStakingInfo(_vaultId); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.5; // TODO(zx): Replace all instances of SafeMath with OZ implementation library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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; } // Only used in the BondingCalculator.sol function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.5; import "./FullMath.sol"; library Babylonian { function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.7.5; interface IBondingCalculator { function valuation(address pair_, uint256 amount_) external view returns (uint256 _value); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.5; interface IXTokenWeth { function target() external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; interface INFTXLPStaking { struct StakingPool { address stakingToken; address rewardToken; } function deposit(uint256 vaultId, uint256 amount) external; function exit(uint256 vaultId, uint256 amount) external; function withdraw(uint256 vaultId, uint256 amount) external; function claimRewards(uint256 vaultId) external; function vaultStakingInfo(uint256 vaultId) external view returns (StakingPool memory stakingPool); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.5; interface INFTXVault { function vaultId() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.7.5; interface ITreasury { function bondCalculator(address _address) external view returns (address); function deposit(uint256 _amount, address _token, uint256 _profit) external returns (uint256); function withdraw(uint256 _amount, address _token) external; function depositERC721(address _token, uint256 _tokenId) external; function withdrawERC721(address _token, uint256 _tokenId) external; function tokenValue(address _token, uint256 _amount) external view returns (uint256 value_); function mint(address _recipient, uint256 _amount) external; function manage(address _token, uint256 _amount) external; function allocatorManage(address _token, uint256 _amount) external; function claimNFTXRewards(address _liquidityStaking, uint256 _vaultId, address _rewardToken) external; function incurDebt(uint256 amount_, address token_) external; function repayDebtWithReserve(uint256 amount_, address token_) external; function excessReserves() external view returns (uint256); function riskOffValuation(address _token) external view returns (uint256); function baseSupply() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.5; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } }
Get the vault ID from the xToken address Return the Treasury value of the underlying SLP amount
function valuation(address xTokenWeth_, uint256 amount_) external view override returns (uint256 _value) { IXTokenWeth _xTokenWeth = IXTokenWeth(xTokenWeth_); INFTXVault _nftxVault = INFTXVault(_xTokenWeth.target()); uint256 _vaultId = _nftxVault.vaultId(); _value = treasury.tokenValue(_getStakingPool(_vaultId).stakingToken, amount_); }
6,919,965
./full_match/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/api/Orders.sol
Submits a new order params Order to submit tpPrice 18 decimal take profit price slPrice 18 decimal stop loss price order cant be reduce-only if take profit or stop loss order is submitted alongside main order tp/sl price checks submit take profit order Order is reduce-only so valueConsumed is always zero submit stop loss order Order is reduce-only so valueConsumed is always zero Update orders to cancel each other Refund msg.value excess, if any
function submitOrder( OrderStore.Order memory params, uint256 tpPrice, uint256 slPrice ) external payable ifNotPaused { if (tpPrice > 0 || slPrice > 0) { params.isReduceOnly = false; } (, valueConsumed) = _submitOrder(params); if (tpPrice > 0 || slPrice > 0) { if (params.price > 0) { if (tpPrice > 0) { require( (params.isLong && tpPrice > params.price) || (!params.isLong && tpPrice < params.price), '!tp-invalid' ); } if (slPrice > 0) { require( (params.isLong && slPrice < params.price) || (!params.isLong && slPrice > params.price), '!sl-invalid' ); } } if (tpPrice > 0 && slPrice > 0) { require((params.isLong && tpPrice > slPrice) || (!params.isLong && tpPrice < slPrice), '!tpsl-invalid'); } uint256 slOrderId; if (tpPrice > 0) { params.price = tpPrice; params.orderType = 1; params.isReduceOnly = true; (tpOrderId, ) = _submitOrder(params); } if (slPrice > 0) { params.price = slPrice; params.orderType = 2; params.isReduceOnly = true; (slOrderId, ) = _submitOrder(params); } if (tpOrderId > 0 && slOrderId > 0) { orderStore.updateCancelOrderId(tpOrderId, slOrderId); orderStore.updateCancelOrderId(slOrderId, tpOrderId); } } if (params.asset == address(0)) { uint256 diff = msg.value - valueConsumed; if (diff > 0) { payable(msg.sender).sendValue(diff); } } }
11,525,653
./full_match/1/0x011E128Ec62840186F4A07E85E3ACe28858c5606/sources/contracts/token/oft/OFTCore.sol
mock the payload for sendFrom()
function estimateSendFee( uint16 _dstChainId, bytes calldata _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams ) public view virtual override returns (uint nativeFee, uint zroFee) { bytes memory payload = abi.encode(PT_SEND, _toAddress, _amount); return lzEndpoint.estimateFees( _dstChainId, address(this), payload, _useZro, _adapterParams ); }
16,518,298
./partial_match/1313161554/0xF14A74E528eD1Ca65A93aDFf66341B02C4025362/sources/ReaperStrategyTrisolaris.sol
only DEFAULT_ADMIN_ROLE can update treasury address./
function updateTreasury(address newTreasury) external { _atLeastRole(DEFAULT_ADMIN_ROLE); treasury = newTreasury; }
16,923,814
pragma solidity ^0.4.18; // 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: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to 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(); } } // 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/CurrentToken.sol contract CurrentToken is StandardToken, Pausable { string constant public name = "CurrentCoin"; string constant public symbol = "CUR"; uint8 constant public decimals = 18; uint256 constant public INITIAL_TOTAL_SUPPLY = 1e11 * (uint256(10) ** decimals); address private addressIco; modifier onlyIco() { require(msg.sender == addressIco); _; } /** * @dev Create CurrentToken contract and set pause * @param _ico The address of ICO contract. */ function CurrentToken (address _ico) public { require(_ico != address(0)); addressIco = _ico; totalSupply_ = totalSupply_.add(INITIAL_TOTAL_SUPPLY); balances[_ico] = balances[_ico].add(INITIAL_TOTAL_SUPPLY); Transfer(address(0), _ico, INITIAL_TOTAL_SUPPLY); pause(); } /** * @dev Transfer token for a specified address with pause feature 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) { super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another with pause feature 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) { super.transferFrom(_from, _to, _value); } /** * @dev Transfer tokens from ICO address to another address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferFromIco(address _to, uint256 _value) onlyIco public returns (bool) { super.transfer(_to, _value); } /** * @dev Burn remaining tokens from the ICO balance. */ function burnFromIco() onlyIco public { uint256 remainingTokens = balanceOf(addressIco); balances[addressIco] = balances[addressIco].sub(remainingTokens); totalSupply_ = totalSupply_.sub(remainingTokens); Transfer(addressIco, address(0), remainingTokens); } /** * @dev Burn all tokens form balance of token holder during refund process. * @param _from The address of token holder whose tokens to be burned. */ function burnFromAddress(address _from) onlyIco public { uint256 amount = balances[_from]; balances[_from] = 0; totalSupply_ = totalSupply_.sub(amount); Transfer(_from, address(0), amount); } } // File: contracts/Whitelist.sol /** * @title Whitelist contract * @dev Whitelist for wallets. */ contract Whitelist is Ownable { mapping(address => bool) whitelist; uint256 public whitelistLength = 0; /** * @dev Add wallet to whitelist. * @dev Accept request from the owner only. * @param _wallet The address of wallet to add. */ function addWallet(address _wallet) onlyOwner public { require(_wallet != address(0)); require(!isWhitelisted(_wallet)); whitelist[_wallet] = true; whitelistLength++; } /** * @dev Remove wallet from whitelist. * @dev Accept request from the owner only. * @param _wallet The address of whitelisted wallet to remove. */ function removeWallet(address _wallet) onlyOwner public { require(_wallet != address(0)); require(isWhitelisted(_wallet)); whitelist[_wallet] = false; whitelistLength--; } /** * @dev Check the specified wallet whether it is in the whitelist. * @param _wallet The address of wallet to check. */ function isWhitelisted(address _wallet) constant public returns (bool) { return whitelist[_wallet]; } } // File: contracts/Whitelistable.sol contract Whitelistable { Whitelist public whitelist; modifier whenWhitelisted(address _wallet) { require(whitelist.isWhitelisted(_wallet)); _; } /** * @dev Constructor for Whitelistable contract. */ function Whitelistable() public { whitelist = new Whitelist(); } } // File: contracts/CurrentCrowdsale.sol contract CurrentCrowdsale is Pausable, Whitelistable { using SafeMath for uint256; uint256 constant private DECIMALS = 18; uint256 constant public RESERVED_TOKENS_FOUNDERS = 40e9 * (10 ** DECIMALS); uint256 constant public RESERVED_TOKENS_OPERATIONAL_EXPENSES = 10e9 * (10 ** DECIMALS); uint256 constant public HARDCAP_TOKENS_PRE_ICO = 100e6 * (10 ** DECIMALS); uint256 constant public HARDCAP_TOKENS_ICO = 499e8 * (10 ** DECIMALS); uint256 public startTimePreIco = 0; uint256 public endTimePreIco = 0; uint256 public startTimeIco = 0; uint256 public endTimeIco = 0; uint256 public exchangeRatePreIco = 0; bool public isTokenRateCalculated = false; uint256 public exchangeRateIco = 0; uint256 public mincap = 0; uint256 public maxcap = 0; mapping(address => uint256) private investments; uint256 public tokensSoldIco = 0; uint256 public tokensRemainingIco = HARDCAP_TOKENS_ICO; uint256 public tokensSoldTotal = 0; uint256 public weiRaisedPreIco = 0; uint256 public weiRaisedIco = 0; uint256 public weiRaisedTotal = 0; mapping(address => uint256) private investmentsPreIco; address[] private investorsPreIco; address private withdrawalWallet; bool public isTokensPreIcoDistributed = false; uint256 public distributionPreIcoCount = 0; CurrentToken public token = new CurrentToken(this); modifier beforeReachingHardCap() { require(tokensRemainingIco > 0 && weiRaisedTotal < maxcap); _; } modifier whenPreIcoSaleHasEnded() { require(now > endTimePreIco); _; } modifier whenIcoSaleHasEnded() { require(endTimeIco > 0 && now > endTimeIco); _; } /** * @dev Constructor for CurrentCrowdsale contract. * @dev Set the owner who can manage whitelist and token. * @param _mincap The mincap value. * @param _startTimePreIco The pre-ICO start time. * @param _endTimePreIco The pre-ICO end time. * @param _foundersWallet The address to which reserved tokens for founders will be transferred. * @param _operationalExpensesWallet The address to which reserved tokens for operational expenses will be transferred. * @param _withdrawalWallet The address to which raised funds will be withdrawn. */ function CurrentCrowdsale( uint256 _mincap, uint256 _maxcap, uint256 _startTimePreIco, uint256 _endTimePreIco, address _foundersWallet, address _operationalExpensesWallet, address _withdrawalWallet ) Whitelistable() public { require(_foundersWallet != address(0) && _operationalExpensesWallet != address(0) && _withdrawalWallet != address(0)); require(_startTimePreIco >= now && _endTimePreIco > _startTimePreIco); require(_mincap > 0 && _maxcap > _mincap); startTimePreIco = _startTimePreIco; endTimePreIco = _endTimePreIco; withdrawalWallet = _withdrawalWallet; mincap = _mincap; maxcap = _maxcap; whitelist.transferOwnership(msg.sender); token.transferFromIco(_foundersWallet, RESERVED_TOKENS_FOUNDERS); token.transferFromIco(_operationalExpensesWallet, RESERVED_TOKENS_OPERATIONAL_EXPENSES); token.transferOwnership(msg.sender); } /** * @dev Fallback function can be used to buy tokens. */ function() public payable { if (isPreIco()) { sellTokensPreIco(); } else if (isIco()) { sellTokensIco(); } else { revert(); } } /** * @dev Check whether the pre-ICO is active at the moment. */ function isPreIco() public constant returns (bool) { bool withinPreIco = now >= startTimePreIco && now <= endTimePreIco; return withinPreIco; } /** * @dev Check whether the ICO is active at the moment. */ function isIco() public constant returns (bool) { bool withinIco = now >= startTimeIco && now <= endTimeIco; return withinIco; } /** * @dev Manual refund if mincap has not been reached. * @dev Only applies when the ICO was ended. */ function manualRefund() whenIcoSaleHasEnded public { require(weiRaisedTotal < mincap); uint256 weiAmountTotal = investments[msg.sender]; require(weiAmountTotal > 0); investments[msg.sender] = 0; uint256 weiAmountPreIco = investmentsPreIco[msg.sender]; uint256 weiAmountIco = weiAmountTotal; if (weiAmountPreIco > 0) { investmentsPreIco[msg.sender] = 0; weiRaisedPreIco = weiRaisedPreIco.sub(weiAmountPreIco); weiAmountIco = weiAmountIco.sub(weiAmountPreIco); } if (weiAmountIco > 0) { weiRaisedIco = weiRaisedIco.sub(weiAmountIco); uint256 tokensIco = weiAmountIco.mul(exchangeRateIco); tokensSoldIco = tokensSoldIco.sub(tokensIco); } weiRaisedTotal = weiRaisedTotal.sub(weiAmountTotal); uint256 tokensAmount = token.balanceOf(msg.sender); tokensSoldTotal = tokensSoldTotal.sub(tokensAmount); token.burnFromAddress(msg.sender); msg.sender.transfer(weiAmountTotal); } /** * @dev Sell tokens during pre-ICO. * @dev Sell tokens only for whitelisted wallets. */ function sellTokensPreIco() beforeReachingHardCap whenWhitelisted(msg.sender) whenNotPaused public payable { require(isPreIco()); require(msg.value > 0); uint256 weiAmount = msg.value; uint256 excessiveFunds = 0; uint256 plannedWeiTotal = weiRaisedTotal.add(weiAmount); if (plannedWeiTotal > maxcap) { excessiveFunds = plannedWeiTotal.sub(maxcap); weiAmount = maxcap.sub(weiRaisedTotal); } investments[msg.sender] = investments[msg.sender].add(weiAmount); weiRaisedPreIco = weiRaisedPreIco.add(weiAmount); weiRaisedTotal = weiRaisedTotal.add(weiAmount); addInvestmentPreIco(msg.sender, weiAmount); if (excessiveFunds > 0) { msg.sender.transfer(excessiveFunds); } } /** * @dev Sell tokens during ICO. * @dev Sell tokens only for whitelisted wallets. */ function sellTokensIco() beforeReachingHardCap whenWhitelisted(msg.sender) whenNotPaused public payable { require(isIco()); require(msg.value > 0); uint256 weiAmount = msg.value; uint256 excessiveFunds = 0; uint256 plannedWeiTotal = weiRaisedTotal.add(weiAmount); if (plannedWeiTotal > maxcap) { excessiveFunds = plannedWeiTotal.sub(maxcap); weiAmount = maxcap.sub(weiRaisedTotal); } uint256 tokensAmount = weiAmount.mul(exchangeRateIco); if (tokensAmount > tokensRemainingIco) { uint256 weiToAccept = tokensRemainingIco.div(exchangeRateIco); excessiveFunds = excessiveFunds.add(weiAmount.sub(weiToAccept)); tokensAmount = tokensRemainingIco; weiAmount = weiToAccept; } investments[msg.sender] = investments[msg.sender].add(weiAmount); tokensSoldIco = tokensSoldIco.add(tokensAmount); tokensSoldTotal = tokensSoldTotal.add(tokensAmount); tokensRemainingIco = tokensRemainingIco.sub(tokensAmount); weiRaisedIco = weiRaisedIco.add(weiAmount); weiRaisedTotal = weiRaisedTotal.add(weiAmount); token.transferFromIco(msg.sender, tokensAmount); if (excessiveFunds > 0) { msg.sender.transfer(excessiveFunds); } } /** * @dev Send raised funds to the withdrawal wallet. */ function forwardFunds() onlyOwner public { require(weiRaisedTotal >= mincap); withdrawalWallet.transfer(this.balance); } /** * @dev Calculate token exchange rate for pre-ICO and ICO. * @dev Only applies when the pre-ICO was ended. * @dev May be called only once. */ function calcTokenRate() whenPreIcoSaleHasEnded onlyOwner public { require(!isTokenRateCalculated); require(weiRaisedPreIco > 0); exchangeRatePreIco = HARDCAP_TOKENS_PRE_ICO.div(weiRaisedPreIco); exchangeRateIco = exchangeRatePreIco.div(2); isTokenRateCalculated = true; } /** * @dev Distribute tokens to pre-ICO investors using pagination. * @dev Pagination proceeds the set value (paginationCount) of tokens distributions per one function call. * @param _paginationCount The value that used for pagination. */ function distributeTokensPreIco(uint256 _paginationCount) onlyOwner public { require(isTokenRateCalculated && !isTokensPreIcoDistributed); require(_paginationCount > 0); uint256 count = 0; for (uint256 i = distributionPreIcoCount; i < getPreIcoInvestorsCount(); i++) { if (count == _paginationCount) { break; } uint256 investment = getPreIcoInvestment(getPreIcoInvestor(i)); uint256 tokensAmount = investment.mul(exchangeRatePreIco); tokensSoldTotal = tokensSoldTotal.add(tokensAmount); token.transferFromIco(getPreIcoInvestor(i), tokensAmount); count++; } distributionPreIcoCount = distributionPreIcoCount.add(count); if (distributionPreIcoCount == getPreIcoInvestorsCount()) { isTokensPreIcoDistributed = true; } } /** * @dev Burn unsold tokens from the ICO balance. * @dev Only applies when the ICO was ended. */ function burnUnsoldTokens() whenIcoSaleHasEnded onlyOwner public { require(tokensRemainingIco > 0); token.burnFromIco(); tokensRemainingIco = 0; } /** * @dev Count the pre-ICO investors total. */ function getPreIcoInvestorsCount() constant public returns (uint256) { return investorsPreIco.length; } /** * @dev Get the pre-ICO investor address. * @param _index the index of investor in the array. */ function getPreIcoInvestor(uint256 _index) constant public returns (address) { return investorsPreIco[_index]; } /** * @dev Gets the amount of tokens for pre-ICO investor. * @param _investorPreIco the pre-ICO investor address. */ function getPreIcoInvestment(address _investorPreIco) constant public returns (uint256) { return investmentsPreIco[_investorPreIco]; } /** * @dev Set start time and end time for ICO. * @dev Only applies when tokens distributions to pre-ICO investors were processed. * @param _startTimeIco The ICO start time. * @param _endTimeIco The ICO end time. */ function setStartTimeIco(uint256 _startTimeIco, uint256 _endTimeIco) whenPreIcoSaleHasEnded beforeReachingHardCap onlyOwner public { require(_startTimeIco >= now && _endTimeIco > _startTimeIco); require(isTokenRateCalculated); startTimeIco = _startTimeIco; endTimeIco = _endTimeIco; } /** * @dev Add new investment to the pre-ICO investments storage. * @param _from The address of a pre-ICO investor. * @param _value The investment received from a pre-ICO investor. */ function addInvestmentPreIco(address _from, uint256 _value) internal { if (investmentsPreIco[_from] == 0) { investorsPreIco.push(_from); } investmentsPreIco[_from] = investmentsPreIco[_from].add(_value); } }
Manual refund if mincap has not been reached. Only applies when the ICO was ended./
function manualRefund() whenIcoSaleHasEnded public { require(weiRaisedTotal < mincap); uint256 weiAmountTotal = investments[msg.sender]; require(weiAmountTotal > 0); investments[msg.sender] = 0; uint256 weiAmountPreIco = investmentsPreIco[msg.sender]; uint256 weiAmountIco = weiAmountTotal; if (weiAmountPreIco > 0) { investmentsPreIco[msg.sender] = 0; weiRaisedPreIco = weiRaisedPreIco.sub(weiAmountPreIco); weiAmountIco = weiAmountIco.sub(weiAmountPreIco); } if (weiAmountIco > 0) { weiRaisedIco = weiRaisedIco.sub(weiAmountIco); uint256 tokensIco = weiAmountIco.mul(exchangeRateIco); tokensSoldIco = tokensSoldIco.sub(tokensIco); } weiRaisedTotal = weiRaisedTotal.sub(weiAmountTotal); uint256 tokensAmount = token.balanceOf(msg.sender); tokensSoldTotal = tokensSoldTotal.sub(tokensAmount); token.burnFromAddress(msg.sender); msg.sender.transfer(weiAmountTotal); }
7,680,537
// SPDX-License-Identifier: MIT pragma solidity = 0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /* * Fairy核心接口 */ interface IFairyCore { // 为指定TokenId的Fairy,设置TokenURI,只允许控制者执行设置 function setTokenURI(uint256 tokenId, string memory tokenUri) external; // 铸造Money,只允许控制者执行铸造,可以铸造一个Fairy, 并从Fairy核心合约地址向目标地址转账Fairy function mintOnce(address to, uint256 tokenId) external; } /* * Fairy属性接口 */ interface IFairyAttrs { // 获取指定TokenId的Fairy的指定属性的值 function getAttr(uint256 tokenId, uint256 index) external view returns (uint256); // 设置指定TokenId的Fairy的指定属性的值 function setAttr(uint256 tokenId, uint256 index, uint256 value) external; } /* * Fairy控制接口 */ interface IFairyCtrl { // 判断指定TokenId的Fairy是否属于指定账户 function isOwns(address account, uint256 tokenId) external view returns (bool); // 获取指定TokenId的Fairy的当前繁殖次数 function currentBreedingCount(uint256 tokenId) external view returns (uint256); // 铸造一个指定等级和繁殖次数的Fairy,并转账到目标外部地址,返回铸造Fairy的TokenId function mintSpecifyFairy(address to, uint256 level, uint256 breeding_count) external returns (uint256); // 繁殖一个Fairy,并转账到目标外部地址,返回下一代Fairy的TokenId function breedFairy(address to, uint256 fatherId, uint256 motherId, uint256 level) external returns (uint256); } /* * Sprite核心接口 */ interface ISpriteCore { // 提现Sprite,只允许Sprite控制合约提现,从Sprite核心合约地址向目标地址转账Sprite function withDraw(address to, uint256 amount) external; } /* * Money核心接口 */ interface IMoneyCore { // 铸造Money,只允许Money控制合约铸造,从Money核心合约地址向目标地址转账Money function mint(address to, uint256 amount) external; // 提现Money,只允许Money控制合约提现,从Money核心合约地址向目标地址转账Money function withDraw(address to, uint256 amount) external; } /* * 基本合约 */ contract Base is Ownable, AccessControl, Pausable { bytes32 internal constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); address private _tokens_owner; // 调试日志事件 event DebugLog(string info); // 检查指定地址是否是合约地址 modifier isContract(address account) { require(Address.isContract(account), 'Caller is not a contract address'); _; } // 检查指定地址是否是外部地址 modifier isExternal(address account) { require(!Address.isContract(account), 'Caller is not a external address'); _; } // 基本合约的构造函数 constructor() { //在合约构造时,为所有者设置默认管理员角色,只有默认管理员可以动态授予和撤销角色 _setupRole(DEFAULT_ADMIN_ROLE, owner()); grantRole(MANAGER_ROLE, owner()); _tokens_owner = owner(); } function getTokensOwner() public view returns (address) { return _tokens_owner; } function setTokensOwner(address tokens_owner) public onlyRole(MANAGER_ROLE) { _tokens_owner = tokens_owner; } // 打印调试日志 function debugLog(string memory info) internal { emit DebugLog(info); } } /* * 工具库 */ library Utils { // 通用验证签名,明文需要调用abi.encodePacked(...)获取message function validSign(address from, bytes memory message, bytes memory sign) internal pure returns (bool) { bytes32 _message = ECDSA.toEthSignedMessageHash(keccak256(message)); (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(_message, sign); if (error != ECDSA.RecoverError.NoError) { //验证签名错误 return false; } if (from != recovered) { //验证签名地址错误 return false; } return true; } // 将地址转换为uint160 function addressToUint160(address account) internal pure returns (uint160) { return uint160(account); } // 将uint160转换为地址 function uint160ToAddress(uint160 value) internal pure returns (address) { return address(value); } // 将地址转换为uint256 function addressToUint256(address account) internal pure returns (uint256) { return uint256(uint160(account)); } // 将uint256转换为字符串 function uint256ToString(uint256 value) internal pure returns (string memory) { return bytesToString(abi.encodePacked(value)); } // 将指定地址转换为字符串 function addressToString(address account) internal pure returns (string memory) { return bytesToString(abi.encodePacked(account)); } // 将指定地址转换为字符串 function bytesToString(bytes memory data) internal pure returns (string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } }
Fairy核心接口/ 为指定TokenId的Fairy,设置TokenURI,只允许控制者执行设置 铸造Money,只允许控制者执行铸造,可以铸造一个Fairy, 并从Fairy核心合约地址向目标地址转账Fairy
interface IFairyCore { function setTokenURI(uint256 tokenId, string memory tokenUri) external; function mintOnce(address to, uint256 tokenId) external; pragma solidity = 0.8.9; }
12,697,247
./full_match/1/0x2ffCC661011beC72e1A9524E12060983E74D14ce/sources/contracts/Zunami.sol
Returns total holdings for all pools (strategy's) return Returns sum holdings (USD) for all pools/
function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; }
8,401,545
./full_match/1/0x22880956813F054d59100CC3180EE5c63eef0121/sources/QRFID_gold.sol
Returns all documents/
function getAllKycDocuments() external view returns (bytes32[] memory) { return _usersKYC; } bool internal _isIssuable;
4,919,077
pragma solidity 0.4.19; // ================= Ownable Contract start ============================= /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } // ================= Ownable Contract end =============================== // ================= Safemath Lib ============================ 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 &gt; 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 &lt;= 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 &gt;= a); return c; } } // ================= Safemath Lib end ============================== // ================= ERC20 Token Contract start ========================= /* * ERC20 interface * 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 transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // ================= ERC20 Token Contract end =========================== // ================= Standard Token Contract start ====================== contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address =&gt; uint256) balances; mapping (address =&gt; mapping (address =&gt; uint256)) internal allowed; 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 &lt;= 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]; } /** * @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 &lt;= balances[_from]); require(_value &lt;= 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]; } } // ================= Standard Token Contract end ======================== // ================= Pausable Token Contract start ====================== /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require (!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require (paused) ; _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } // ================= Pausable Token Contract end ======================== // ================= Tomocoin start ======================= contract TomoCoin is StandardToken, Pausable { string public constant name = &#39;Tomocoin&#39;; string public constant symbol = &#39;TOMO&#39;; uint256 public constant decimals = 18; address public tokenSaleAddress; address public tomoDepositAddress; // multisig wallet uint256 public constant tomoDeposit = 100000000 * 10**decimals; function TomoCoin(address _tomoDepositAddress) public { tomoDepositAddress = _tomoDepositAddress; balances[tomoDepositAddress] = tomoDeposit; Transfer(0x0, tomoDepositAddress, tomoDeposit); totalSupply_ = tomoDeposit; } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success) { return super.transfer(_to,_value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool success) { return super.approve(_spender, _value); } function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } // Setup Token Sale Smart Contract function setTokenSaleAddress(address _tokenSaleAddress) public onlyOwner { if (_tokenSaleAddress != address(0)) { tokenSaleAddress = _tokenSaleAddress; } } function mint(address _recipient, uint256 _value) public whenNotPaused returns (bool success) { require(_value &gt; 0); // This function is only called by Token Sale Smart Contract require(msg.sender == tokenSaleAddress); balances[tomoDepositAddress] = balances[tomoDepositAddress].sub(_value); balances[ _recipient ] = balances[_recipient].add(_value); Transfer(tomoDepositAddress, _recipient, _value); return true; } } // ================= Ico Token Contract end ======================= // ================= Whitelist start ==================== contract TomoContributorWhitelist is Ownable { mapping(address =&gt; uint256) public whitelist; function TomoContributorWhitelist() public {} event ListAddress( address _user, uint256 cap, uint256 _time ); function listAddress( address _user, uint256 cap ) public onlyOwner { whitelist[_user] = cap; ListAddress( _user, cap, now ); } function listAddresses( address[] _users, uint256[] _caps ) public onlyOwner { for( uint i = 0 ; i &lt; _users.length ; i++ ) { listAddress( _users[i], _caps[i] ); } } function getCap( address _user ) public view returns(uint) { return whitelist[_user]; } } // ================= Whitelist end ==================== // ================= Actual Sale Contract Start ==================== contract TomoTokenSale is Pausable { using SafeMath for uint256; TomoCoin tomo; TomoContributorWhitelist whitelist; mapping(address =&gt; uint256) public participated; address public ethFundDepositAddress; address public tomoDepositAddress; uint256 public constant tokenCreationCap = 4000000 * 10**18; uint256 public totalTokenSold = 0; uint256 public constant fundingStartTime = 1519876800; // 2018/03/01 04:00:00 uint256 public constant fundingPoCEndTime = 1519963200; // 2018/03/02 04:00:00 uint256 public constant fundingEndTime = 1520136000; // 2018/03/04 04:00:00 uint256 public constant minContribution = 0.1 ether; uint256 public constant maxContribution = 10 ether; uint256 public constant tokenExchangeRate = 3200; uint256 public constant maxCap = tokenExchangeRate * maxContribution; bool public isFinalized; event MintTomo(address from, address to, uint256 val); event RefundTomo(address to, uint256 val); function TomoTokenSale( TomoCoin _tomoCoinAddress, TomoContributorWhitelist _tomoContributorWhitelistAddress, address _ethFundDepositAddress, address _tomoDepositAddress ) public { tomo = TomoCoin(_tomoCoinAddress); whitelist = TomoContributorWhitelist(_tomoContributorWhitelistAddress); ethFundDepositAddress = _ethFundDepositAddress; tomoDepositAddress = _tomoDepositAddress; isFinalized = false; } function buy(address to, uint256 val) internal returns (bool success) { MintTomo(tomoDepositAddress, to, val); return tomo.mint(to, val); } function () public payable { createTokens(msg.sender, msg.value); } function createTokens(address _beneficiary, uint256 _value) internal whenNotPaused { require (now &gt;= fundingStartTime); require (now &lt;= fundingEndTime); require (_value &gt;= minContribution); require (_value &lt;= maxContribution); require (!isFinalized); uint256 tokens = _value.mul(tokenExchangeRate); uint256 cap = whitelist.getCap(_beneficiary); require (cap &gt; 0); uint256 tokensToAllocate = 0; uint256 tokensToRefund = 0; uint256 etherToRefund = 0; // running while PoC Buying Time if (now &lt;= fundingPoCEndTime) { tokensToAllocate = cap.sub(participated[_beneficiary]); } else { tokensToAllocate = maxCap.sub(participated[_beneficiary]); } // calculate refund if over max cap or individual cap if (tokens &gt; tokensToAllocate) { tokensToRefund = tokens.sub(tokensToAllocate); etherToRefund = tokensToRefund.div(tokenExchangeRate); } else { // user can buy amount they want tokensToAllocate = tokens; } uint256 checkedTokenSold = totalTokenSold.add(tokensToAllocate); // if reaches hard cap if (tokenCreationCap &lt; checkedTokenSold) { tokensToAllocate = tokenCreationCap.sub(totalTokenSold); tokensToRefund = tokens.sub(tokensToAllocate); etherToRefund = tokensToRefund.div(tokenExchangeRate); totalTokenSold = tokenCreationCap; } else { totalTokenSold = checkedTokenSold; } // save to participated data participated[_beneficiary] = participated[_beneficiary].add(tokensToAllocate); // allocate tokens require(buy(_beneficiary, tokensToAllocate)); if (etherToRefund &gt; 0) { // refund in case user buy over hard cap, individual cap RefundTomo(msg.sender, etherToRefund); msg.sender.transfer(etherToRefund); } ethFundDepositAddress.transfer(this.balance); return; } /// @dev Ends the funding period and sends the ETH home function finalize() external onlyOwner { require (!isFinalized); // move to operational isFinalized = true; ethFundDepositAddress.transfer(this.balance); } }
called by the owner to unpause, returns to normal state/
function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; }
924,224
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import { BLS } from "./BLS.sol"; /** @title Transaction Data To Commit on Chain @notice This library manipulates transaction data that'll be stored/computed on chain. - It compress transaction so they can be gas efficiently stored on chain. - It also decompresses the transaction for performning state transition. - It recovers the signing messages for signature verification. */ library Tx { // Tx types in uint256 uint256 private constant TRANSFER = 1; uint256 private constant CREATE2TRANSFER = 3; uint256 private constant MASS_MIGRATION = 5; uint256 public constant MASK_PUBKEY_ID = 0xffffffff; uint256 public constant MASK_STATE_ID = 0xffffffff; uint256 public constant MASK_AMOUNT = 0xffffffff; uint256 public constant MASK_FEE = 0xffffffff; uint256 public constant MASK_EXPONENT = 0xf000; uint256 public constant MANTISSA_BITS = 12; uint256 public constant MASK_MANTISSA = 0x0fff; uint256 public constant MASK_NONCE = 0xffffffff; uint256 public constant MASK_TOKEN_ID = 0xffff; uint256 public constant MASK_BYTE = 0xff; // transaction_type: transfer // [sender_state_id<4>|receiver_state_id<4>|amount<2>|fee<2>] uint256 public constant TX_LEN_0 = 12; // positions in bytes uint256 public constant POSITION_SENDER_0 = 4; uint256 public constant POSITION_RECEIVER_0 = 8; uint256 public constant POSITION_AMOUNT_0 = 10; uint256 public constant POSITION_FEE_0 = 12; // transaction_type: create2Transfer // [sender_state_id<4>|receiver_state_id<4>|receiver_acc_id<4>|amount<2>|fee<2>] uint256 public constant TX_LEN_1 = 16; // positions in bytes uint256 public constant POSITION_SENDER_1 = 4; uint256 public constant POSITION_RECEIVER_1 = 8; uint256 public constant POSITION_RECEIVER_ACCID_1 = 12; uint256 public constant POSITION_AMOUNT_1 = 14; uint256 public constant POSITION_FEE_1 = 16; // transaction_type: Mass Migrations // [sender_state_id<4>|amount<2>|fee<2>] uint256 public constant TX_LEN_5 = 8; // positions in bytes uint256 public constant POSITION_SENDER_5 = 4; uint256 public constant POSITION_AMOUNT_5 = 6; uint256 public constant POSITION_FEE_5 = 8; struct Transfer { uint256 fromIndex; uint256 toIndex; uint256 amount; uint256 fee; } struct Create2Transfer { uint256 fromIndex; uint256 toIndex; uint256 toPubkeyID; uint256 amount; uint256 fee; } struct MassMigration { uint256 fromIndex; uint256 amount; uint256 fee; } // Transfer function transferHasExcessData(bytes memory txs) internal pure returns (bool) { return txs.length % TX_LEN_0 != 0; } // num of txs in the bytes blob function transferSize(bytes memory txs) internal pure returns (uint256) { return txs.length / TX_LEN_0; } function serialize(Transfer[] memory txs) internal pure returns (bytes memory) { uint256 batchSize = txs.length; bytes memory serialized = new bytes(TX_LEN_0 * batchSize); for (uint256 i = 0; i < batchSize; i++) { uint256 fromIndex = txs[i].fromIndex; uint256 toIndex = txs[i].toIndex; uint256 amount = encodeDecimal(txs[i].amount); uint256 fee = encodeDecimal(txs[i].fee); bytes memory _tx = abi.encodePacked( uint32(fromIndex), uint32(toIndex), uint16(amount), uint16(fee) ); uint256 off = i * TX_LEN_0; for (uint256 j = 0; j < TX_LEN_0; j++) { serialized[j + off] = _tx[j]; } } return serialized; } function serialize(MassMigration[] memory txs) internal pure returns (bytes memory) { uint256 batchSize = txs.length; bytes memory serialized = new bytes(TX_LEN_5 * batchSize); for (uint256 i = 0; i < batchSize; i++) { uint256 fromIndex = txs[i].fromIndex; uint256 amount = encodeDecimal(txs[i].amount); uint256 fee = encodeDecimal(txs[i].fee); bytes memory _tx = abi.encodePacked( uint32(fromIndex), uint16(amount), uint16(fee) ); uint256 off = i * TX_LEN_5; for (uint256 j = 0; j < TX_LEN_5; j++) { serialized[j + off] = _tx[j]; } } return serialized; } function serialize(Create2Transfer[] memory txs) internal pure returns (bytes memory) { uint256 batchSize = txs.length; bytes memory serialized = new bytes(TX_LEN_1 * batchSize); for (uint256 i = 0; i < batchSize; i++) { uint256 fromIndex = txs[i].fromIndex; uint256 toIndex = txs[i].toIndex; uint256 toPubkeyID = txs[i].toPubkeyID; uint256 amount = txs[i].amount; uint256 fee = txs[i].fee; bytes memory _tx = abi.encodePacked( uint32(fromIndex), uint32(toIndex), uint32(toPubkeyID), uint16(encodeDecimal(amount)), uint16(encodeDecimal(fee)) ); uint256 off = i * TX_LEN_1; for (uint256 j = 0; j < TX_LEN_1; j++) { serialized[j + off] = _tx[j]; } } return serialized; } function encodeDecimal(uint256 input) internal pure returns (uint256) { // Copy to avoid assigning to the function parameter. uint256 x = input; uint256 exponent = 0; for (uint256 i = 0; i < 15; i++) { if (x != 0 && x % 10 == 0) { x = x / 10; exponent += 1; } else { break; } } require(x <= 0x0fff, "Bad input"); return (exponent << 12) + x; } function transferDecode(bytes memory txs, uint256 index) internal pure returns (Transfer memory _tx) { uint256 sender; uint256 receiver; uint256 amount; uint256 fee; // solium-disable-next-line security/no-inline-assembly assembly { let p_tx := add(txs, mul(index, TX_LEN_0)) sender := and(mload(add(p_tx, POSITION_SENDER_0)), MASK_STATE_ID) receiver := and( mload(add(p_tx, POSITION_RECEIVER_0)), MASK_STATE_ID ) let amountBytes := mload(add(p_tx, POSITION_AMOUNT_0)) let amountExponent := shr( MANTISSA_BITS, and(amountBytes, MASK_EXPONENT) ) let amountMantissa := and(amountBytes, MASK_MANTISSA) amount := mul(amountMantissa, exp(10, amountExponent)) let feeBytes := mload(add(p_tx, POSITION_FEE_0)) let feeExponent := shr(MANTISSA_BITS, and(feeBytes, MASK_EXPONENT)) let feeMantissa := and(feeBytes, MASK_MANTISSA) fee := mul(feeMantissa, exp(10, feeExponent)) } return Transfer(sender, receiver, amount, fee); } function transferMessageOf(Transfer memory _tx, uint256 nonce) internal pure returns (bytes memory) { return abi.encodePacked( TRANSFER, _tx.fromIndex, _tx.toIndex, nonce, _tx.amount, _tx.fee ); } function create2TransferHasExcessData(bytes memory txs) internal pure returns (bool) { return txs.length % TX_LEN_1 != 0; } function create2TransferSize(bytes memory txs) internal pure returns (uint256) { return txs.length / TX_LEN_1; } function create2TransferDecode(bytes memory txs, uint256 index) internal pure returns (Create2Transfer memory _tx) { uint256 sender; uint256 receiver; uint256 receiverPubkeyID; uint256 amount; uint256 fee; // solium-disable-next-line security/no-inline-assembly assembly { let p_tx := add(txs, mul(index, TX_LEN_1)) sender := and(mload(add(p_tx, POSITION_SENDER_1)), MASK_STATE_ID) receiver := and( mload(add(p_tx, POSITION_RECEIVER_1)), MASK_STATE_ID ) receiverPubkeyID := and( mload(add(p_tx, POSITION_RECEIVER_ACCID_1)), MASK_PUBKEY_ID ) let amountBytes := mload(add(p_tx, POSITION_AMOUNT_1)) let amountExponent := shr( MANTISSA_BITS, and(amountBytes, MASK_EXPONENT) ) let amountMantissa := and(amountBytes, MASK_MANTISSA) amount := mul(amountMantissa, exp(10, amountExponent)) let feeBytes := mload(add(p_tx, POSITION_FEE_1)) let feeExponent := shr(MANTISSA_BITS, and(feeBytes, MASK_EXPONENT)) let feeMantissa := and(feeBytes, MASK_MANTISSA) fee := mul(feeMantissa, exp(10, feeExponent)) } return Create2Transfer(sender, receiver, receiverPubkeyID, amount, fee); } function create2TransferMessageOf( Create2Transfer memory _tx, uint256 nonce, uint256[4] memory to ) internal pure returns (bytes memory) { return abi.encodePacked( CREATE2TRANSFER, _tx.fromIndex, to, nonce, _tx.amount, _tx.fee ); } function massMigrationDecode(bytes memory txs, uint256 index) internal pure returns (MassMigration memory _tx) { uint256 sender; uint256 amount; uint256 fee; // solium-disable-next-line security/no-inline-assembly assembly { let p_tx := add(txs, mul(index, TX_LEN_5)) sender := and(mload(add(p_tx, POSITION_SENDER_5)), MASK_STATE_ID) let amountBytes := mload(add(p_tx, POSITION_AMOUNT_5)) let amountExponent := shr( MANTISSA_BITS, and(amountBytes, MASK_EXPONENT) ) let amountMantissa := and(amountBytes, MASK_MANTISSA) amount := mul(amountMantissa, exp(10, amountExponent)) let feeBytes := mload(add(p_tx, POSITION_FEE_5)) let feeExponent := shr(MANTISSA_BITS, and(feeBytes, MASK_EXPONENT)) let feeMantissa := and(feeBytes, MASK_MANTISSA) fee := mul(feeMantissa, exp(10, feeExponent)) } return MassMigration(sender, amount, fee); } function massMigrationHasExcessData(bytes memory txs) internal pure returns (bool) { return txs.length % TX_LEN_5 != 0; } function massMigrationSize(bytes memory txs) internal pure returns (uint256) { return txs.length / TX_LEN_5; } function massMigrationMessageOf( MassMigration memory _tx, uint256 nonce, uint256 spokeID ) internal pure returns (bytes memory) { return abi.encodePacked( uint8(MASS_MIGRATION), uint32(_tx.fromIndex), _tx.amount, _tx.fee, uint32(nonce), uint32(spokeID) ); } }
Copy to avoid assigning to the function parameter.
function encodeDecimal(uint256 input) internal pure returns (uint256) { uint256 x = input; uint256 exponent = 0; for (uint256 i = 0; i < 15; i++) { if (x != 0 && x % 10 == 0) { x = x / 10; exponent += 1; break; } } require(x <= 0x0fff, "Bad input"); return (exponent << 12) + x; }
13,109,452
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.0.0/contracts/access/Ownable.sol"; import "@OpenZeppelin/contracts/access/Ownable.sol"; contract Voting is Ownable { struct Voter { bool isRegistered; bool hasVoted; uint votedProposalId; } struct Proposal { string description; uint voteCount; } enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } WorkflowStatus status; event VoterRegistered(address voterAddress); event ProposalsRegistrationStarted(); event ProposalsRegistrationEnded(); event ProposalRegistered(uint proposalId); event VotingSessionStarted(); event VotingSessionEnded(); event Voted (address voter, uint proposalId); event VotesTallied(); event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus); mapping(address => Voter) voters; mapping(uint => Proposal) proposals; string desc; uint proposalId; uint nbrVotes; uint winningProposalId; /// @dev contract's owner registers voters adding address to a whitelist function registerToVote(address _address) public onlyOwner { require(status == WorkflowStatus.RegisteringVoters, "Registering closed"); require(!voters[_address].isRegistered, "Voter already registered"); voters[_address].isRegistered = true; emit VoterRegistered(_address); } /// @dev owner starts the proposal registration session function openProposalRegistration() public onlyOwner { require(status == WorkflowStatus.RegisteringVoters, "Not yet open"); status = WorkflowStatus.ProposalsRegistrationStarted; emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted); } /// @dev registered voters can send their proposition while the session is open /// @param _description string is proposal's description function sendYourProposition(string memory _description) public { require(status == WorkflowStatus.ProposalsRegistrationStarted, "Proposal session closed"); require(voters[msg.sender].isRegistered, "You are not registered"); proposalId++; proposals[proposalId].description = _description; emit ProposalRegistered(proposalId); } /// @dev contract's owner ends the proposal registration session function closeProposalRegistration() public onlyOwner { require(status == WorkflowStatus.ProposalsRegistrationStarted, "Not yet open"); status = WorkflowStatus.ProposalsRegistrationEnded; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded); } /// @dev contract's owner starts the proposal voting session function openVoteSession() public onlyOwner { require(status == WorkflowStatus.ProposalsRegistrationEnded, "Not yet possible"); status = WorkflowStatus.VotingSessionStarted; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted); } /// @dev registered voters vote for their favorite proposition /// @notice nbrVotes holds current max count, if new vote get higher value, it replaces it & proposal ID is stored in winningProposalId /// @notice desc holds description string corresponding to nbrVotes function voteFor(uint _proposalId) public returns (uint) { require(status == WorkflowStatus.VotingSessionStarted, "Voting session closed"); require(voters[msg.sender].isRegistered, "Unregistered, cannot vote"); require(!voters[msg.sender].hasVoted, "Already voted"); voters[msg.sender].votedProposalId = _proposalId; voters[msg.sender].hasVoted = true; proposals[_proposalId].voteCount++; if (proposals[_proposalId].voteCount > nbrVotes) { nbrVotes = proposals[_proposalId].voteCount; winningProposalId = _proposalId; desc = proposals[_proposalId].description; } emit Voted(msg.sender, _proposalId); return winningProposalId; } /// @dev contract's owner ends the proposal voting session function closeVoteSession() public onlyOwner { require(status == WorkflowStatus.VotingSessionStarted, "Not yet open"); status = WorkflowStatus.VotingSessionEnded; emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded); } /// @dev contract's owner ends voting session /// @notice winning proposal ID is officially the winningProposalId value already set function countVotes() public onlyOwner { require(status == WorkflowStatus.VotingSessionEnded, "Nothing to count yet"); status = WorkflowStatus.VotesTallied; emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied); emit VotesTallied(); } /// @dev proposition ID is publically viewable once session has ended /// @return winning proposition ID and corresponding description string function winner() public view returns (uint, string memory) { require(status == WorkflowStatus.VotesTallied, "No winner yet"); return (winningProposalId, desc); } /// @dev get status for handling the corresponding UI components function getStatus() public view returns (WorkflowStatus) { return status; } /// @dev get winning proposition description to return to the UI function getPropositionDescription() public view returns (string memory) { return desc; } /// @dev get submitted proposition ID to return to the UI function getProposalId() public view returns (uint) { return proposalId; } /// @dev get number of votes to return to the UI function getNumberOfVotes() public view returns (uint) { return nbrVotes; } /// @dev get winning proposition ID to return to the UI function getWinningProposalId() public view returns (uint) { return winningProposalId; } }
contract's owner ends the proposal voting session
function closeVoteSession() public onlyOwner { require(status == WorkflowStatus.VotingSessionStarted, "Not yet open"); status = WorkflowStatus.VotingSessionEnded; emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded); }
1,804,326
pragma solidity ^0.4.24; import "./SafeMath.sol"; // TODO fixing following mapping for notifying all followers // TODO break out user and tweet into separate files contract SolTweet { using SafeMath for uint256; event NewUser(uint userId); event NewTweet(uint tweetId, uint indexed userId); event LikeCountChange(uint tweetId, uint likeCount); mapping (uint => address) userToOwner; mapping (address => uint) public ownerToUser; mapping (address => bool) public ownerHasAccount; mapping (uint => uint) tweetToUserId; mapping (uint => bool) userHasLikedTweet; mapping (uint => mapping (uint => bool)) public followingMapping; mapping (uint => uint[]) public followingMappingKeys; struct User { string username; uint followerCount; } struct Tweet { string text; uint likes; uint authorId; } User[] public users; Tweet[] public tweets; function _getFollowingMappingKeys(uint _userId) public view returns (uint[] memory) { return followingMappingKeys[_userId]; } function _getNumberOfTweets() public view returns (uint) { return tweets.length; } function _createUser(string memory _username) public returns (uint) { User memory newUser; newUser.username = _username; newUser.followerCount = 0; uint id = (users.push(newUser)).sub(1); userToOwner[id] = msg.sender; ownerToUser[msg.sender] = id; ownerHasAccount[msg.sender] = true; emit NewUser(id); return id; } function _createTweet(uint _userId, string memory _tweetText) public returns (uint) { require(userToOwner[_userId] == msg.sender, "unauthorized sender"); uint id = (tweets.push(Tweet(_tweetText, 0, _userId))).sub(1); tweetToUserId[id] = _userId; // notify followers //look up all the users follwers and let them know about the new tweet // following[]; emit NewTweet(id, _userId); return id; } function _likeTweet(uint _userId, uint _tweetId) public { require(userToOwner[_userId] == msg.sender, "unauthorized sender"); bool userLikedTweet = userHasLikedTweet[uint(keccak256(abi.encodePacked(_userId, _tweetId)))]; require(!userLikedTweet, "user already liked tweet"); Tweet storage myTweet = tweets[_tweetId]; myTweet.likes = myTweet.likes.add(1); emit LikeCountChange(_tweetId, myTweet.likes); } function _follow(uint _userId, uint _userIdToFollow) public { require(userToOwner[_userId] == msg.sender, "unauthorized sender"); //check that the users isn't already following require(!followingMapping[_userId][_userIdToFollow], "user already following"); //add the follower and increase follower count // following[_userId] = _userIdToFollow; User storage userToFollow = users[_userIdToFollow]; userToFollow.followerCount = userToFollow.followerCount.add(1); followingMapping[_userId][_userIdToFollow] = true; followingMappingKeys[_userId].push(_userIdToFollow); } function _unFollow(uint _userId, uint _userIdToUnFollow) public { require(userToOwner[_userId] == msg.sender, "unauthorized sender"); require(followingMapping[_userId][_userIdToUnFollow], "user not following"); //check that the users is already following // require(following[_userId] == _userIdToUnFollow, "sender is not following"); //remove the follower and decrease follower count // delete following[_userId]; User storage userToUnFollow = users[_userIdToUnFollow]; followingMapping[_userId][_userIdToUnFollow] = false; userToUnFollow.followerCount = userToUnFollow.followerCount.sub(1); } }
check that the users is already following require(following[_userId] == _userIdToUnFollow, "sender is not following");remove the follower and decrease follower count delete following[_userId];
function _unFollow(uint _userId, uint _userIdToUnFollow) public { require(userToOwner[_userId] == msg.sender, "unauthorized sender"); require(followingMapping[_userId][_userIdToUnFollow], "user not following"); User storage userToUnFollow = users[_userIdToUnFollow]; followingMapping[_userId][_userIdToUnFollow] = false; userToUnFollow.followerCount = userToUnFollow.followerCount.sub(1); }
2,544,895
./full_match/1/0xd71f6F000604BC9bdDFdA2e11cD31C4843B9A42A/sources/contracts/stakingNFT/HelixChefNFT.sol
Called by the owner to add an accruer
function addAccruer(address _address) external onlyOwner onlyValidAddress(_address) { bool success = EnumerableSetUpgradeable.add(_accruers, _address); require(success, "add accruer failed"); emit AddAccruer(msg.sender, _address); }
2,998,874
./full_match/42/0xa56Ebbcf4A37016A9659Fd50bcF6e7F9232ABaB6/sources/contracts/ClearingHouse.sol
Deposit tokens into the vault
function deposit( uint256 idx, uint256 amount, IERC20 token ) external { require(vault.deposit(idx, msg.sender, amount, token) > 0); emit Deposit(idx, msg.sender, address(token), amount); }
9,594,864
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Create2.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "arb-bridge-eth/contracts/bridge/interfaces/IInbox.sol"; import "arb-bridge-eth/contracts/libraries/ProxyUtil.sol"; import "../L1ArbitrumMessenger.sol"; import "../../libraries/gateway/GatewayMessageHandler.sol"; import "../../libraries/gateway/TokenGateway.sol"; import "../../libraries/ITransferAndCall.sol"; /** * @title Common interface for gatways on L1 messaging to Arbitrum. */ abstract contract L1ArbitrumGateway is L1ArbitrumMessenger, TokenGateway { using SafeERC20 for IERC20; using Address for address; address public inbox; event DepositInitiated( address l1Token, address indexed _from, address indexed _to, uint256 indexed _sequenceNumber, uint256 _amount ); event WithdrawalFinalized( address l1Token, address indexed _from, address indexed _to, uint256 indexed _exitNum, uint256 _amount ); modifier onlyCounterpartGateway() override { address _inbox = inbox; // a message coming from the counterpart gateway was executed by the bridge address bridge = address(super.getBridge(_inbox)); require(msg.sender == bridge, "NOT_FROM_BRIDGE"); // and the outbox reports that the L2 address of the sender is the counterpart gateway address l2ToL1Sender = super.getL2ToL1Sender(_inbox); require(l2ToL1Sender == counterpartGateway, "ONLY_COUNTERPART_GATEWAY"); _; } function postUpgradeInit() external { // it is assumed the L1 Arbitrum Gateway contract is behind a Proxy controlled by a proxy admin // this function can only be called by the proxy admin contract address proxyAdmin = ProxyUtil.getProxyAdmin(); require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN"); // this has no other logic since the current upgrade doesn't require this logic } function _initialize( address _l2Counterpart, address _router, address _inbox ) internal virtual { TokenGateway._initialize(_l2Counterpart, _router); // L1 gateway must have a router require(_router != address(0), "BAD_ROUTER"); require(_inbox != address(0), "BAD_INBOX"); inbox = _inbox; } /** * @notice Finalizes a withdrawal via Outbox message; callable only by L2Gateway.outboundTransfer * @param _token L1 address of token being withdrawn from * @param _from initiator of withdrawal * @param _to address the L2 withdrawal call set as the destination. * @param _amount Token amount being withdrawn * @param _data encoded exitNum (Sequentially increasing exit counter determined by the L2Gateway) and additinal hook data */ function finalizeInboundTransfer( address _token, address _from, address _to, uint256 _amount, bytes calldata _data ) public payable virtual override onlyCounterpartGateway { // this function is marked as virtual so superclasses can override it to add modifiers (uint256 exitNum, bytes memory callHookData) = GatewayMessageHandler.parseToL1GatewayMsg( _data ); if (callHookData.length != 0) { // callHookData should always be 0 since inboundEscrowAndCall is disabled callHookData = bytes(""); } // we ignore the returned data since the callHook feature is now disabled (_to, ) = getExternalCall(exitNum, _to, callHookData); inboundEscrowTransfer(_token, _to, _amount); emit WithdrawalFinalized(_token, _from, _to, exitNum, _amount); } function getExternalCall( uint256, /* _exitNum */ address _initialDestination, bytes memory _initialData ) public view virtual returns (address target, bytes memory data) { // this method is virtual so the destination of a call can be changed // using tradeable exits in a subclass (L1ArbitrumExtendedGateway) target = _initialDestination; data = _initialData; } function inboundEscrowTransfer( address _l1Token, address _dest, uint256 _amount ) internal virtual { // this method is virtual since different subclasses can handle escrow differently IERC20(_l1Token).safeTransfer(_dest, _amount); } function createOutboundTx( address _from, uint256, /* _tokenAmount */ uint256 _maxGas, uint256 _gasPriceBid, uint256 _maxSubmissionCost, bytes memory _outboundCalldata ) internal virtual returns (uint256) { // We make this function virtual since outboundTransfer logic is the same for many gateways // but sometimes (ie weth) you construct the outgoing message differently. // msg.value is sent, but 0 is set to the L2 call value // the eth sent is used to pay for the tx's gas return sendTxToL2( inbox, counterpartGateway, _from, msg.value, // we forward the L1 call value to the inbox 0, // l2 call value 0 by default L2GasParams({ _maxSubmissionCost: _maxSubmissionCost, _maxGas: _maxGas, _gasPriceBid: _gasPriceBid }), _outboundCalldata ); } /** * @notice Deposit ERC20 token from Ethereum into Arbitrum. If L2 side hasn't been deployed yet, includes name/symbol/decimals data for initial L2 deploy. Initiate by GatewayRouter. * @param _l1Token L1 address of ERC20 * @param _to account to be credited with the tokens in the L2 (can be the user's L2 account or a contract) * @param _amount Token Amount * @param _maxGas Max gas deducted from user's L2 balance to cover L2 execution * @param _gasPriceBid Gas price for L2 execution * @param _data encoded data from router and user * @return res abi encoded inbox sequence number */ // * @param maxSubmissionCost Max gas deducted from user's L2 balance to cover base submission fee function outboundTransfer( address _l1Token, address _to, uint256 _amount, uint256 _maxGas, uint256 _gasPriceBid, bytes calldata _data ) public payable virtual override returns (bytes memory res) { require(isRouter(msg.sender), "NOT_FROM_ROUTER"); // This function is set as public and virtual so that subclasses can override // it and add custom validation for callers (ie only whitelisted users) address _from; uint256 seqNum; bytes memory extraData; { uint256 _maxSubmissionCost; if (super.isRouter(msg.sender)) { // router encoded (_from, extraData) = GatewayMessageHandler.parseFromRouterToGateway(_data); } else { _from = msg.sender; extraData = _data; } // user encoded (_maxSubmissionCost, extraData) = abi.decode(extraData, (uint256, bytes)); // the inboundEscrowAndCall functionality has been disabled, so no data is allowed require(extraData.length == 0, "EXTRA_DATA_DISABLED"); require(_l1Token.isContract(), "L1_NOT_CONTRACT"); address l2Token = calculateL2TokenAddress(_l1Token); require(l2Token != address(0), "NO_L2_TOKEN_SET"); _amount = outboundEscrowTransfer(_l1Token, _from, _amount); // we override the res field to save on the stack res = getOutboundCalldata(_l1Token, _from, _to, _amount, extraData); seqNum = createOutboundTx( _from, _amount, _maxGas, _gasPriceBid, _maxSubmissionCost, res ); } emit DepositInitiated(_l1Token, _from, _to, seqNum, _amount); return abi.encode(seqNum); } function outboundEscrowTransfer( address _l1Token, address _from, uint256 _amount ) internal virtual returns (uint256 amountReceived) { // this method is virtual since different subclasses can handle escrow differently // user funds are escrowed on the gateway using this function uint256 prevBalance = IERC20(_l1Token).balanceOf(address(this)); IERC20(_l1Token).safeTransferFrom(_from, address(this), _amount); uint256 postBalance = IERC20(_l1Token).balanceOf(address(this)); return SafeMath.sub(postBalance, prevBalance); } function getOutboundCalldata( address _l1Token, address _from, address _to, uint256 _amount, bytes memory _data ) public view virtual override returns (bytes memory outboundCalldata) { // this function is public so users can query how much calldata will be sent to the L2 // before execution // it is virtual since different gateway subclasses can build this calldata differently // ( ie the standard ERC20 gateway queries for a tokens name/symbol/decimals ) bytes memory emptyBytes = ""; outboundCalldata = abi.encodeWithSelector( TokenGateway.finalizeInboundTransfer.selector, _l1Token, _from, _to, _amount, GatewayMessageHandler.encodeToL2GatewayMsg(emptyBytes, _data) ); return outboundCalldata; } }
We make this function virtual since outboundTransfer logic is the same for many gateways but sometimes (ie weth) you construct the outgoing message differently. msg.value is sent, but 0 is set to the L2 call value the eth sent is used to pay for the tx's gas
function createOutboundTx( address _from, uint256, /* _tokenAmount */ uint256 _maxGas, uint256 _gasPriceBid, uint256 _maxSubmissionCost, bytes memory _outboundCalldata ) internal virtual returns (uint256) { return sendTxToL2( inbox, counterpartGateway, _from, L2GasParams({ _maxSubmissionCost: _maxSubmissionCost, _maxGas: _maxGas, _gasPriceBid: _gasPriceBid }), _outboundCalldata ); }
6,401,590
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/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/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/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); } } // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/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); } // OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } ///////////////////////////////////////// /////🦔INTERFACES🦔///////////////////// //////////////////////////////////////// contract OwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } pragma solidity ^0.8.12; interface InterfaceDescriptor { function renderBottom(uint256 _bottom) external view returns (bytes memory); function renderClothes(uint256 _clothes) external view returns (bytes memory); function renderBack(uint256 _back) external view returns (bytes memory); function renderAccessory(uint256 _accessory) external view returns (bytes memory); function renderHeadgear(uint256 _headgear) external view returns (bytes memory); function renderMouth(uint256 _mouth) external view returns (bytes memory); function renderBackground(uint256 _background) external view returns (bytes memory); function renderEyes(uint256 _eyes) external view returns (bytes memory); function renderLegendary(uint256 _legendary) external view returns (bytes memory); } // File: contracts/edgehogs.sol // (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( // (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( // (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( // (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( // (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( // (((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( // (((((((((((((((((((((((((((((((((%%%(((%%%(((%%%(((%%%%%%((((((((((((((((((((((((((((((((((((((( // (((((((((((((((((((((((((((((((((@@@(((@@@(((@@@(((@@@@@@((((((((((((((((((((((((((((((((((((((( // ((((((((((((((((((((((((@@@(((@@@&&&@@@&&&@@@%%%@@@%%%%%%@@@(((((((((((((((((((((((((((((((((((( // ((((((((((((((((((((((((@@@@@@&&&%%%&&&%%%%%%###%%%###%%%###@@@((((((((((((((((((((((((((((((((( // (((((((((((((((((((((@@@&&&%%%######%%%%%%######%%%###%%%###%%%@@@(((((((((((((((((((((((((((((( // ((((((((((((((((((@@@&&&&&&&&&%%%###%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@((((((((((((((((((((((((((( // ((((((((((((######&&&&&&%%%&&&%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@#########(((((((((((((((((( // ((((((((((((@@@@@@&&&&&&###@@@@@@@@@###%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@@@@@@@@@@(((((((((((((((((( // (((((((((((((((@@@&&&%%%###@@@******%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@@@******&@@(((((((((((((((((( // (((((((((((((((@@@&&&%%%###%%%@@@***%%%///,,,,,,,,,%%%%%%*,,,,,,,,///***&@@((((((((((((((((((((( // (((((((((@@@@@@&&&&&&&&&%%%%%%%%%@@@(//,,,,,,,,,,,,,,,,,,,,,,,,//////###@@@((((((((((((((((((((( // ((((((((((((@@@&&&%%%%%%%%%%%%%%%@@@(//,,,,,,@@@ ,,,,,,,,,///@@@ ###@@@((((((((((((((((((((( // ((((((((((((@@@&&&%%%%%%%%%%%%%%%@@@(//,,,,,,@@@ ,,,,,,,,,///@@@ ###@@@((((((((((((((((((((( // (((((((((@@@@@@%%%&&&%%%%%%%%%%%%@@@(//,,,,,,@@@@@@*,,,,,,,,,,,@@@@@@###@@@((((((((((((((((((((( // ((((((((((((@@@&&&&&&%%%###%%%%%%@@@(//////////////,,,,,,,,,,,,//////&@@(((((((((((((((((((((((( // (((((((((@@@&&&%%%&&&%%%%%%%%%@@@###//////,,,,,,,,,,,,,,,,,,@@@@@@(//&@@(((((((((((((((((((((((( // (((((((((@@@&&&&&&&&&%%%###@@@#########@@@(///////////,,,@@@@@@@@@@@@((((((((((((((((((((((((((( // (((((((((@@@&&&%%%&&&&&&###@@@###//////###@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((((((( // (((((((((@@@&&&%%%&&&&&&###@@@###//////###@@@@@@@@@@@@@@@@@@@@@@@@(((((((((((((((((((((((((((((( // (((((((((@@@&&&%%%######@@@###///////////////###############@@@((((((((((((((((((((((((((((((((( // ((((((@@@&&&&&&%%%&&&###@@@###/////////,,,,,,,,,,,,//////###@@@((((((((((((((((((((((((((((((((( // (((((((((@@@&&&%%%&&&@@@###/////////,,,,,,,,,,,,,,,,,,//////&@@@@@(((((((((((((((((((((((((((((( // ((((((@@@&&&&&&%%%###@@@###/////////,,,,,,,,,,,,,,,,,,,,,///&@@(//&@@((((((((((((((((((((((((((( // (((((((((@@@&&&%%%###@@@######@@@(//,,,,,,,,,,,,,,,,,,,,,///&@@(//&@@((((((((((((((((((((((((((( // (((((((((@@@&&&%%%###@@@######@@@(//,,,,,,,,,,,,,,,,,,,,,///&@@(//&@@((((((((((((((((((((((((((( // (((((((((@@@&&&&&&&&&@@@###///@@@(//,,,,,,,,,,,,,,,,,,,,,///&@@(//&@@((((((((((((((((((((((((((( // ((((((@@@&&&&&&&&&###@@@###///@@@(//,,,,,,,,,,,,,,,,,,//////&@@(//&@@((((((((((((((((((((((((((( // (((((((((@@@&&&&&&%%%###@@@@@@(////////,,,,,,,,,,,,,,,//////&@@@@@(((((((((((((((((((((((((((((( // ((((((((((((@@@&&&%%%%%%@@@###////////////,,,,,,,,,/////////&@@((((((((((((((((((((((((((((((((( // (((((((((((((((@@@######@@@###///////////////////////////&@@(((((((((((((((((((((((((((((((((((( // (((((((((((((((@@@######@@@###///////////////////////////&@@(((((((((((((((((((((((((((((((((((( // ((((((((((((((((((@@@@@@@@@###///@@@@@@@@@@@@@@@###///&@@(((((((((((((((@spiridono(((((((((((((( // ((((((((((((((((((((((((@@@###///@@@(((((((((@@@###///&@@((((((((((((((((((((((((((((((((((((((( contract Edgehogs is Ownable, ERC721A { uint256 public MAX = 6666; uint256 public MAX_FREE = 696; uint256 public MAX_REROLLS = 1000; uint256 public PURCHASE_LIMIT = 10; uint256 public PRICE = 0.025 ether; uint256 public REROLL_PRICE = 0.01 ether; uint256 public mintedTokens; uint256 public rerollsMade; uint256 public freeClaimed; uint8 public saleState = 0; // = DEV, 1 = SALE, 2 = REROLL, 3 = CLOSED // OpenSea auto approve is live bool public isOpenSeaApproved; //Legendaries status bool public legendariesSet = false; // OpenSea proxy registry contract OpenSeaProxyRegistry public openSeaProxyRegistry; // withdraw addresses address t1 = 0x392D50fCFDd5b36E6DdDB22bcB84AA80B8105890; // address t2 = 0xE0b76103Ec5d8159939572A61286bD3291DB8a43; //Steve Aoki addrress address steveAoki = 0xe4bBCbFf51e61D0D95FcC5016609aC8354B177C4; //Save seed for traits for each token mapping(uint256 => uint256) public tokenSeed; // amount minted by address in presale mapping(address => uint256) public whitelistMints; InterfaceDescriptor public descriptor; uint16[][8] rarities; string[][9] traitsByName; uint256[] legendaryList; // Mapping from token ID to name mapping (uint256 => string) private _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) private _nameReserved; // presale merkle tree root bytes32 internal _merkleRoot; //SVG-parts shared by all Edgehogs string private constant svgStart = "<svg id='edgehog' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 256 256' width='640' height='640'>"; string private constant svgEnd = "<style>#edgehog{shape-rendering: crispedges; image-rendering: -moz-crisp-edges; image-rendering: optimizeSpeed; image-rendering: -webkit-crisp-edges; image-rendering: -webkit-optimize-contrast; image-rendering: crisp-edges; image-rendering: pixelated; -ms-interpolation-mode: nearest-neighbor;}.vibe { animation: 0.5s vibe infinite alternate ease-in-out; } @keyframes vibe { from { transform: translateY(0px); } to { transform: translateY(1.5%); } }</style></svg>"; string private constant _body = "<image href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEABAMAAACuXLVVAAAAD1BMVEUAAACTg2rLtaEnDQhZVlIUtesvAAAAAXRSTlMAQObYZgAAAMhJREFUeNrt2bENxCAQRUG3QAvXAi24/5oOS15hmdNB6vVMQkDwXwwbAAAAAAAAAAAAAAAAAAAAAMCq2uzNtkiAAAG5AmI8bBMCBAjIG1BOswgBAgTkCujjo/2H2ggQICB/wOemnAQIEJAvYD4+RtSTAAEC3hdwiIA4BQgQkCfgUBsBAgS8N6A0AgQIEDALKI0AAQJyBoRysfpAIUCAgOcH/Pu4vI+HGBcgQED+gG4cFyBAQN6AOoi7Pi5AgID8Adc7AQIEpAj4AjgSOK7j5zUdAAAAAElFTkSuQmCC'/>"; string private constant _head = "<g class='vibe'><image href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEABAMAAACuXLVVAAAAFVBMVEUAAADLtaEnDQiTg2rsmJkAAABZVlL0LlrIAAAAAXRSTlMAQObYZgAAALBJREFUeNrt1s0JwzAMgNGukBWyQlfoCl2h+4/QGCwQAZOfm5X3rpHQdwp+AQAAAAAAAAAAAJyxJnf3BAgQMH/Ap7uyFzsCBAiYPyBHvLsliZklaTP5uAABAuYPiIh0fCgifxsBAgQ8LyB/FyBAwDMDGgECBNQP2Bs9SOK4AAEC6gQ0o6Ph2wkQIKBuwOiHFMdDPi5AgIB6Ac16YD8vQICAegEAAAAAAAAAAAAAAEAZf88p+dDBeVtDAAAAAElFTkSuQmCC'/></g>"; constructor( InterfaceDescriptor descriptor_, OpenSeaProxyRegistry openSeaProxyRegistry_, bytes32 merkleRoot_ ) ERC721A("EDGEHOGS", unicode"⚉") { //Solidity 0.8.12 does not seem to support Unicode 10.0 emojis as of now, otherwise it would have been 🦔 ofc // Initializing variables descriptor = descriptor_; openSeaProxyRegistry = openSeaProxyRegistry_; _merkleRoot = merkleRoot_; //sum of rarities values must be equal to the mod used in _getRandomIndex, 10000 in our case rarities[0] = [0, 200, 2000, 2000, 2000, 2000, 900, 900 ]; //backgrounds rarities[1] = [ 0, 1000, 850, 700, 700, 700, 600, 600, 500, 500, 400, 400, 300, 300, 300, 300, 300, 300, 200, 200, 200, 200, 200, 100, 100, 50 ]; //backs rarities[2] = [ 0, 550, 550, 550, 550, 550, 550, 550, 550, 550, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 50 ]; //bottoms rarities[3] = [ 0, 550, 550, 550, 550, 550, 550, 550, 550, 550, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 50 ]; //clothes rarities[4] = [ 0, 1000, 800, 800, 800, 600, 600, 500, 500, 400, 400, 400, 400, 400, 300, 300, 300, 300, 300, 200, 200, 200, 150, 100, 50 ]; //mouths rarities[5] = [ 0, 800, 600, 600, 600, 600, 600, 400, 400, 400, 400, 300, 300, 300, 300, 300, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 100, 100, 100, 100, 100, 100, 100, 50, 50, 50, 50 ]; //headgears rarities[6] = [ 0, 850, 800, 800, 600, 600, 600, 400, 400, 400, 400, 300, 300, 300, 300, 300, 200, 200, 200, 200, 200, 200, 200, 200, 200, 100, 100, 100, 100, 100, 100, 100, 100, 50 ]; //eyes rarities[7] = [ 0, 800, 700, 700, 700, 700, 500, 500, 500, 500, 500, 500, 500, 400, 400, 400, 300, 200, 200, 200, 200, 200, 100, 100, 100, 50, 50 ]; //accessories //traits //backgrounds traitsByName[0] = [ "n/a", "Psychedelic", "Purple", "Orange", "Green", "Pink", "Pink-Blue", "Blue-Green" ]; //backs traitsByName[1] = [ "n/a", "Edgehog", "Firework", "Black", "Neon Sparks", "Shoomery", "Pirate", "Punk", "Grant us Eyes", "Rainbow", "Neon Punk", "Psychedelic", "Slime", "Spotty", "Christmas", "Brainiac", "Cyberhog", "Bubble gum", "Skellyhog", "TNT", "Biohazard", "Robohog", "Hellhog", "Virus", "Pure Gold", "Diamond" ]; //bottoms traitsByName[2] = [ "n/a", "Fancy", "Padre", "Joker", "Vault Dweller", "Santa", "Torn Jeans", "Fishnets", "Bikini", "Green", "Pajamas", "BDSM", "Mime", "Pink", "Jungle", "Rainbow", "Elvis", "Bathog", "Partyhog", "Skelly", "Pure Gold" ]; //clothes traitsByName[3] = [ "n/a", "Pink", "Joker", "Vault Dweller", "Padre", "Santa", "Freddy", "Pierced Nips", "Bikini", "Punk", "Pajamas", "BDSM", "Mime", "Rapper", "Buff", "Rainbow", "Elvis", "Bathog", "Partyhog", "Skelly", "Pure Gold" ]; //mouths traitsByName[4] = [ "None", "Plain", "Smile", "Drooling", "Tongue", "Pipe", "Party", "Love", "Zombie", "Rabid", "Blush", "Mime", "Bubble gum", "Blunt", "Bloody", "Licker", "Vampire", "Blotter", "Virus", "Red Beard", "Golden tooth", "TNT", "Hannibal", "Biohazard", "Laser" ]; //headgears traitsByName[5] = [ "n/a", "None", "Beanie", "Fastfood", "Apple", "Frying pan", "Tinfoil hat", "Arrow", "Punk", "Rabbit ears", "Doc", "Pizza", "Anntennae", "Horny", "Pretty bow", "Eye", "Devil", "Skull", "Toad", "Unicorn", "Kamikaze", "Santa", "Pirate", "Alien eyes", "Demon", "Crown", "Chief", "Zombie hand", "Fake halo", "Brainz", "Strawberry cap", "Russian hat", "Frankenhog", "Plunger", "Sroomhead", "Octopus", "Plague Doctor", "VR" ]; //eyes traitsByName[6] = [ "n/a", "Plain", "Sus", "Green", "Crosseyed", "Angry", "Kawaii", "Tired", "Grumpy", "Red goggles", "Green goggles", "Bloodshot", "Goomba", "Eye patch", "Squinty", "Insane", "Vampire", "Pop out", "Popeye", "Dizzy", "Triple eye", "Hearts", "XX", "Alien", "VR goggles", "Cyclops", "Rainbow goggles", "Cyborg", "Cyberhog", "Demon", "Hogminator", "Steampunk", "Deal with it", "Lasers" ]; //accessories traitsByName[7] = [ "n/a", "None", "Coffee", "Sausage", "Sorcerer staff", "Mana potion", "Bong", "Pirate flag", "Whip", "Beer", "Steel claws", "Trident", "Knife", "Club", "Balloon", "Shocker", "Biohazard", "Lightsaber", "Master Sword", "Doggy", "Rose", "Gun", "Pee", "Chainsaw", "Scythe", "Dildo", "Minigun" ]; traitsByName[8] = [ "n/a", "Nude Dude", "Dark Entity", "Acid Hog", "Zombie Hog", "Hog Spirit", "Lava Hog", "Why So Serious", "Robohog", "Very Fast Blue Hog", "Retrohog" ]; } //Get the attribute name for the properties of the token by its index function _getTrait(uint256 _trait, uint256 index) internal view returns (string memory) { return traitsByName[_trait][index]; } //////////////////////////////////////////////////////////// /////🦔GENERATE TRAITS AND SVG BASED ON SEED🦔///////////// /////////////////////////////////////////////////////////// //Get randomized values for each different trait with a single pseudorandom seed // note: we are generating both traits and SVG on the fly based on the seed which is the the only parameter saved in memory // Not writing a whole struct allows for serious gas savings on mint, but has a downside that we can't easily address or change a single trait function getTraits(uint256 seed) public view returns (string memory svg, string memory properties) { uint16[] memory randomInputs = expand(seed, 8); uint16[] memory traits = new uint16[](9); /** traits[0] bg traits[1] back traits[2] bottom traits[3] clothes traits[4] mouth traits[5] headgear traits[6] eyes traits[7] accessory traits[8] legendary */ if (seed > 100) { traits[0] = getRandomIndex(rarities[0], randomInputs[0]); traits[1] = getRandomIndex(rarities[1], randomInputs[1]); traits[2] = getRandomIndex(rarities[2], randomInputs[2]); traits[3] = getRandomIndex(rarities[3], randomInputs[3]); traits[4] = getRandomIndex(rarities[4], randomInputs[4]); traits[5] = getRandomIndex(rarities[5], randomInputs[5]); traits[6] = getRandomIndex(rarities[6], randomInputs[6]); traits[7] = getRandomIndex(rarities[7], randomInputs[7]); traits[8] = 0; //handling compatibility exceptions //tnt //hellhog if (traits[1] == 19 || traits[1] == 22) { traits[5] = 1; } //tnt if (traits[4] == 21) { traits[7] = 0; } //staff //scythe //plain if (traits[7] == 4 || traits[7] == 24) { traits[4] = 1; } //VR if (traits[5] == 37) { traits[6] = 1; } //Plague if (traits[5] == 36) { traits[6] = 1; traits[4] = 0; } } else { traits[0] = 0; traits[1] = 0; traits[2] = 0; traits[3] = 0; traits[4] = 0; traits[5] = 0; traits[6] = 0; traits[7] = 0; traits[8] = uint16(seed); } // render svg bytes memory _svg = renderEdgehog( traits[0], traits[1], traits[2], traits[3], traits[4], traits[5], traits[6], traits[7], traits[8] ); svg = base64(_svg); // pack properties, put 1 after the last property for JSON to be formed correctly (no comma after the last one) if (seed > 100) { bytes memory _properties = abi.encodePacked( packMetaData("background", _getTrait(0, traits[0]), 0), packMetaData("back", _getTrait(1, traits[1]), 0), packMetaData("bottom", _getTrait(2, traits[2]), 0), packMetaData("clothes", _getTrait(3, traits[3]), 0), packMetaData("mouth", _getTrait(4, traits[4]), 0), packMetaData("headgear", _getTrait(5, traits[5]), 0), packMetaData("eyes", _getTrait(6, traits[6]), 0), packMetaData("accessory", _getTrait(7, traits[7]), 1) ); properties = string(abi.encodePacked(_properties)); } else { bytes memory _properties = abi.encodePacked( packMetaData("legendary", _getTrait(8, seed), 1) ); properties = string(abi.encodePacked(_properties)); } return (svg, properties); } // Get a random attribute using the rarities defined // Shout out to Anonymice for the logic function getRandomIndex( uint16[] memory attributeRarities, uint256 randomNumber ) private pure returns (uint16 index) { uint16 random10k = uint16(randomNumber % 10000); uint16 lowerBound; for (uint16 i = 1; i <= attributeRarities.length; i++) { uint16 percentage = attributeRarities[i]; if (random10k < percentage + lowerBound && random10k >= lowerBound) { return i; } lowerBound = lowerBound + percentage; } revert(); } //Get attribute svg for each different property of the token function renderEdgehog( uint16 _background, uint16 _back, uint16 _bottom, uint16 _clothes, uint16 _mouth, uint16 _headgear, uint16 _eyes, uint16 _accessory, uint16 _legendary ) public view returns (bytes memory) { bytes memory start = abi.encodePacked( svgStart, descriptor.renderBackground(_background), descriptor.renderBack(_back), _body, descriptor.renderBottom(_bottom) ); return abi.encodePacked( start, descriptor.renderClothes(_clothes), _head, descriptor.renderAccessory(_accessory), descriptor.renderHeadgear(_headgear), descriptor.renderEyes(_eyes), descriptor.renderMouth(_mouth), descriptor.renderLegendary(_legendary), svgEnd ); } ///////////////////////////////////// /////🦔GENERATE METADATA🦔////////// //////////////////////////////////// //Get the metadata for a token in base64 format function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Token not found"); (string memory svg, string memory properties) = getTraits( tokenSeed[tokenId] ); return string( abi.encodePacked( "data:application/json;base64,", base64( abi.encodePacked( '{"name":"Edgehog #', uint2str(tokenId),' ',_tokenName[tokenId], '", "description": "Edgehogs live on the cutting edge of Ethereum blockchain and are edgy as hell.", "traits": [', properties, '], "image":"data:image/svg+xml;base64,', svg, '"}' ) ) ) ); } // Bundle metadata so it follows the standard function packMetaData( string memory name, string memory svg, uint256 last ) private pure returns (bytes memory) { string memory comma = ","; if (last > 0) comma = ""; return abi.encodePacked( '{"trait_type": "', name, '", "value": "', svg, '"}', comma ); } ///////////////////////////////////// /////🦔MINTING🦔//////////////////// //////////////////////////////////// //giveaways are nice function gift(uint256 numberOfTokens, address recipient) external onlyOwner { uint256 supply = totalSupply(); require(supply + numberOfTokens <= MAX, "Would exceed max supply"); for (uint256 i = 0; i < numberOfTokens; i++) { tokenSeed[supply + i] = uint256( keccak256(abi.encodePacked(block.timestamp, msg.sender, supply + i)) ); } delete supply; _safeMint(recipient, numberOfTokens); } //mint Edgehog function mint(uint256 numberOfTokens) external payable { uint256 supply = totalSupply(); require(saleState == 1, "Sale inactive"); require(msg.sender != steveAoki, "No Steve Aoki!"); require(numberOfTokens <= PURCHASE_LIMIT, "Too many"); require(supply + numberOfTokens <= MAX - MAX_FREE + freeClaimed, "Would exceed max public supply"); require(PRICE * numberOfTokens == msg.value, "Wrong ETH amount"); for (uint256 i = 0; i < numberOfTokens; i++) { tokenSeed[supply + i] = uint256( keccak256(abi.encodePacked(block.timestamp, msg.sender, supply + i)) ); } delete supply; _safeMint(msg.sender, numberOfTokens); } //free mint, 1 per transaction, 1 per wallet, address must be whtelisted function presaleMint(bytes32[] calldata proof_) external { uint256 supply = totalSupply(); require(saleState == 1, "Sale inactive"); require(supply + 1 <= MAX, "Would exceed max supply"); require(isWhitelisted(msg.sender, proof_), "Not on the list"); require(whitelistMints[msg.sender] == 0, "Already minted"); freeClaimed++; whitelistMints[msg.sender]++; tokenSeed[supply] = uint256( keccak256(abi.encodePacked(block.timestamp, msg.sender, supply)) ); delete supply; _safeMint(msg.sender, 1); } //rerolls a common edgehog function reroll(uint256 _tokenId) external payable { require(saleState == 2, "Reroll inactive"); require(rerollsMade < MAX_REROLLS, "No more rerolls"); require(msg.sender == ownerOf(_tokenId), "Only owner can reroll"); require(!isLegendary(_tokenId), "Can't be rerolled"); require(REROLL_PRICE == msg.value, "Wrong ETH amount"); rerollsMade = rerollsMade + 1; tokenSeed[_tokenId] = uint256( keccak256(abi.encodePacked(block.timestamp, msg.sender, _tokenId + 1)) ); } //puts a legendary edgehog in place of a common function rollLegendary(uint256 _tokenId, uint256 _legendaryId) public onlyOwner { //can only make regulars legendaries require(!isLegendary(_tokenId), "Can't be upgraded"); tokenSeed[_tokenId] = _legendaryId; addLegendaryNumber(_legendaryId); } //checks if an edgehog is legendary function isLegendary(uint256 _tokenId) public view returns (bool) { if (tokenSeed[_tokenId] <=100) { return true; } else { return false; } } //set legendaries function setLegendaries(uint256 _legendarySeed) public onlyOwner { require(legendariesSet == false, "Legendaries already set"); uint256 s = totalSupply(); uint256 n = _legendarySeed; for (uint256 i = 1; i <= 10; i++) { uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp,msg.sender,n))) % s; if (!isLegendary(randomNumber)) { tokenSeed[randomNumber] = i; addLegendaryNumber(randomNumber); n = n * 6; } } delete s; delete n; legendariesSet = true; } ///////////////////////////////////// /////🦔RENAMING🦔/////////////////// //////////////////////////////////// // Shout out to Hashmasks //Changes the name for Edgehog tokenId function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; emit NameChange(tokenId, newName); } // Events event NameChange (uint256 indexed edgehogId, string newName); //Returns name of the NFT at index. function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } //Returns if the name has been reserved. function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } //Reserves the name if isReserve is set to true, de-reserves if set to false function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } //Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } //Converts the string to lowercase function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /////////////////////////////////// /////🦔ADMIN🦔//////////////////// ////////////////////////////////// //Gets the token pre-approved for trading on OpenSea - saves gas for the end users function setOpenSeaProxyRegistry(OpenSeaProxyRegistry openSeaProxyRegistry_) external onlyOwner { openSeaProxyRegistry = openSeaProxyRegistry_; } function flipOpenSeaApproved() external onlyOwner { isOpenSeaApproved = !isOpenSeaApproved; } function flipSaleState() external onlyOwner { require(saleState < 3, "Sale state is already closed"); saleState++; } function setMaxSupply(uint256 _supply) public onlyOwner { MAX = _supply; } function setFreeSupply(uint256 _supply) public onlyOwner { MAX_FREE = _supply; } function setPrice(uint256 _newPrice) external onlyOwner { PRICE = _newPrice; } // Withdraw to the team according to shares function withdrawAll() public payable onlyOwner { uint256 _share = address(this).balance / 100; require(payable(t1).send(_share * 90)); require(payable(t2).send(_share * 10)); } /////////////////////////////////// /////🦔HELPERS🦔////////////////// ////////////////////////////////// function isApprovedForAll(address _owner, address operator) public view override returns (bool) { return (isOpenSeaApproved && address(openSeaProxyRegistry.proxies(_owner)) == operator) || super.isApprovedForAll(_owner, operator); } // Check if the address is whitelisted function isWhitelisted(address account_, bytes32[] calldata proof_) public view returns (bool) { return _verify(_leaf(account_), proof_); } // Set Merckle root function setMerkleRoot(bytes32 merkleRoot_) public onlyOwner { _merkleRoot = merkleRoot_; } // Encode Merckle leaf from address function _leaf(address account_) internal pure returns (bytes32) { return keccak256(abi.encodePacked(account_)); } // verify proof function _verify(bytes32 leaf_, bytes32[] memory proof_) internal view returns (bool) { return MerkleProof.verify(proof_, _merkleRoot, leaf_); } ///set attributes libraries function setDescriptor(address source) external onlyOwner { descriptor = InterfaceDescriptor(source); } //generates random numbers based on a random number function expand(uint256 _randomNumber, uint256 n) private pure returns (uint16[] memory expandedValues) { expandedValues = new uint16[](n); for (uint256 i = 0; i < n; i++) { expandedValues[i] = bytes2uint(keccak256(abi.encode(_randomNumber, i))); } return expandedValues; } //converts uint256 to uint16 function bytes2uint(bytes32 _a) private pure returns (uint16) { return uint16(uint256(_a)); } function freeClaimedCount() external view returns (uint256) { return freeClaimed; } function rerollsMadeCount() external view returns (uint256) { return rerollsMade; } //adds a legendary edgehog's id to the list of legendaties function addLegendaryNumber(uint256 _legendaryId) public onlyOwner { legendaryList.push(_legendaryId); } //returns ids of legendary edgehogs function legendariesList() external view returns (uint256[] memory) { return legendaryList; } //adds a new name to the legendaries array function addNewLegendary(string memory _legendaryName) public onlyOwner { traitsByName[8].push(_legendaryName); } //returns number of tokens owned function tokensOfOwner(address address_) public virtual view returns (uint256[] memory) { uint256 _balance = balanceOf(address_); uint256[] memory _tokens = new uint256[] (_balance); uint256 _index; uint256 _loopThrough = totalSupply(); for (uint256 i = 0; i < _loopThrough; i++) { bool _exists = _exists(i); if (_exists) { if (ownerOf(i) == address_) { _tokens[_index] = i; _index++; } } else if (!_exists && _tokens[_balance - 1] == 0) { _loopThrough++; } } return _tokens; } //Helper function to convert uint to string function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } // Base64 by Brecht Devos - <[email protected]> // Provides a function for encoding some bytes in base64 string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } //if you are reading this, you are a true blockchain nerd. Much love - @spiridono! 🦔 }
load the table into memory multiply by 4/3 rounded up add some extra buffer at the end required for the writing set the actual output length prepare the lookup table input ptr result ptr, jump over length run over the input, 3 bytes at a time read 3 bytes write 4 characters
function base64(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; string memory table = TABLE; uint256 encodedLen = 4 * ((data.length + 2) / 3); string memory result = new string(encodedLen + 32); assembly { mstore(result, encodedLen) let tablePtr := add(table, 1) let dataPtr := data let endPtr := add(dataPtr, mload(data)) let resultPtr := add(result, 32) { dataPtr := add(dataPtr, 3) let input := mload(dataPtr) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } } return result; }
13,972,429
./partial_match/1313161554/0x5A5301F9429818f01101744BE2fc9AD5510846AE/sources/PureFiFarming2.sol
version in format aaa.bbb.ccc => aaa1E6+bbb1E3+ccc;
function version() public pure returns (uint32){ return uint32(2000004); }
16,950,644
./full_match/1/0xEe8Ec5D6e709CDaE62D3859e759fa779a689D9Fe/sources/contracts/scoopdogsquad.sol
Safety function to remove bad names./ We will keep the name in the disallow list to prevent it from been used again.
function removeName(uint256 tokenId) external onlyOwner { require(tokenId < totalSupply(), "The token ID is not valid"); sdogNames[tokenId] = ""; }
2,937,578
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import './interfaces/INonfungiblePositionManager.sol'; import './libraries/TransferHelper.sol'; import './interfaces/IV3Migrator.sol'; import './base/PeripheryImmutableState.sol'; import './base/Multicall.sol'; import './base/SelfPermit.sol'; import './interfaces/external/IWETH9.sol'; import './base/PoolInitializer.sol'; /// @title Uniswap V3 Migrator contract V3Migrator is IV3Migrator, PeripheryImmutableState, PoolInitializer, Multicall, SelfPermit { using LowGasSafeMath for uint256; address public immutable nonfungiblePositionManager; constructor( address _factory, address _WETH9, address _nonfungiblePositionManager ) PeripheryImmutableState(_factory, _WETH9) { nonfungiblePositionManager = _nonfungiblePositionManager; } receive() external payable { require(msg.sender == WETH9, 'Not WETH9'); } function migrate(MigrateParams calldata params) external override { require(params.percentageToMigrate > 0, 'Percentage too small'); require(params.percentageToMigrate <= 100, 'Percentage too large'); // burn v2 liquidity to this address IUniswapV2Pair(params.pair).transferFrom(msg.sender, params.pair, params.liquidityToMigrate); (uint256 amount0V2, uint256 amount1V2) = IUniswapV2Pair(params.pair).burn(address(this)); // calculate the amounts to migrate to v3 uint256 amount0V2ToMigrate = amount0V2.mul(params.percentageToMigrate) / 100; uint256 amount1V2ToMigrate = amount1V2.mul(params.percentageToMigrate) / 100; // approve the position manager up to the maximum token amounts TransferHelper.safeApprove(params.token0, nonfungiblePositionManager, amount0V2ToMigrate); TransferHelper.safeApprove(params.token1, nonfungiblePositionManager, amount1V2ToMigrate); // mint v3 position (, , uint256 amount0V3, uint256 amount1V3) = INonfungiblePositionManager(nonfungiblePositionManager).mint( INonfungiblePositionManager.MintParams({ token0: params.token0, token1: params.token1, fee: params.fee, tickLower: params.tickLower, tickUpper: params.tickUpper, amount0Desired: amount0V2ToMigrate, amount1Desired: amount1V2ToMigrate, amount0Min: params.amount0Min, amount1Min: params.amount1Min, recipient: params.recipient, deadline: params.deadline }) ); // if necessary, clear allowance and refund dust if (amount0V3 < amount0V2) { if (amount0V3 < amount0V2ToMigrate) { TransferHelper.safeApprove(params.token0, nonfungiblePositionManager, 0); } uint256 refund0 = amount0V2 - amount0V3; if (params.refundAsETH && params.token0 == WETH9) { IWETH9(WETH9).withdraw(refund0); TransferHelper.safeTransferETH(msg.sender, refund0); } else { TransferHelper.safeTransfer(params.token0, msg.sender, refund0); } } if (amount1V3 < amount1V2) { if (amount1V3 < amount1V2ToMigrate) { TransferHelper.safeApprove(params.token1, nonfungiblePositionManager, 0); } uint256 refund1 = amount1V2 - amount1V3; if (params.refundAsETH && params.token1 == WETH9) { IWETH9(WETH9).withdraw(refund1); TransferHelper.safeTransferETH(msg.sender, refund1); } else { TransferHelper.safeTransfer(params.token1, msg.sender, refund1); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryPayments.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IMulticall.sol'; import './ISelfPermit.sol'; import './IPoolInitializer.sol'; /// @title V3 Migrator /// @notice Enables migration of liqudity from Uniswap v2-compatible pairs into Uniswap v3 pools interface IV3Migrator is IMulticall, ISelfPermit, IPoolInitializer { struct MigrateParams { address pair; // the Uniswap v2-compatible pair uint256 liquidityToMigrate; // expected to be balanceOf(msg.sender) uint8 percentageToMigrate; // represented as a numerator over 100 address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Min; // must be discounted by percentageToMigrate uint256 amount1Min; // must be discounted by percentageToMigrate address recipient; uint256 deadline; bool refundAsETH; } /// @notice Migrates liquidity to v3 by burning v2 liquidity and minting a new position for v3 /// @dev Slippage protection is enforced via `amount{0,1}Min`, which should be a discount of the expected values of /// the maximum amount of v3 liquidity that the v2 liquidity can get. For the special case of migrating to an /// out-of-range position, `amount{0,1}Min` may be set to 0, enforcing that the position remains out of range /// @param params The params necessary to migrate v2 liquidity, encoded as `MigrateParams` in calldata function migrate(MigrateParams calldata params) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '../interfaces/IPeripheryImmutableState.sol'; /// @title Immutable state /// @notice Immutable state used by periphery contracts abstract contract PeripheryImmutableState is IPeripheryImmutableState { /// @inheritdoc IPeripheryImmutableState address public immutable override factory; /// @inheritdoc IPeripheryImmutableState address public immutable override WETH9; constructor(address _factory, address _WETH9) { factory = _factory; WETH9 = _WETH9; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '../interfaces/IMulticall.sol'; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/drafts/IERC20Permit.sol'; import '../interfaces/ISelfPermit.sol'; import '../interfaces/external/IERC20PermitAllowed.sol'; /// @title Self Permit /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route /// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function /// that requires an approval in a single transaction. abstract contract SelfPermit is ISelfPermit { /// @inheritdoc ISelfPermit function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); } /// @inheritdoc ISelfPermit function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20(token).allowance(msg.sender, address(this)) < type(uint256).max) selfPermitAllowed(token, nonce, expiry, v, r, s); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import './PeripheryImmutableState.sol'; import '../interfaces/IPoolInitializer.sol'; /// @title Creates and initializes V3 Pools abstract contract PoolInitializer is IPoolInitializer, PeripheryImmutableState { /// @inheritdoc IPoolInitializer function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable override returns (address pool) { require(token0 < token1); pool = IUniswapV3Factory(factory).getPool(token0, token1, fee); if (pool == address(0)) { pool = IUniswapV3Factory(factory).createPool(token0, token1, fee); IUniswapV3Pool(pool).initialize(sqrtPriceX96); } else { (uint160 sqrtPriceX96Existing, , , , , , ) = IUniswapV3Pool(pool).slot0(); if (sqrtPriceX96Existing == 0) { IUniswapV3Pool(pool).initialize(sqrtPriceX96); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { 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( 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; 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.7.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.7.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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Multicall interface /// @notice Enables calling multiple methods in a single call to the contract interface IMulticall { /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed /// @dev The `msg.value` should not be trusted for any method callable from multicall. /// @param data The encoded function data for each of the calls to make to this contract /// @return results The results from each of the calls passed in via data function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Self Permit /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route interface ISelfPermit { /// @notice Permits this contract to spend a given token from `msg.sender` /// @dev The `owner` is always msg.sender and the `spender` is always address(this). /// @param token The address of the token spent /// @param value The amount that can be spent of token /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend a given token from `msg.sender` /// @dev The `owner` is always msg.sender and the `spender` is always address(this). /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit /// @param token The address of the token spent /// @param value The amount that can be spent of token /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter /// @dev The `owner` is always msg.sender and the `spender` is always address(this) /// @param token The address of the token spent /// @param nonce The current nonce of the owner /// @param expiry The timestamp at which the permit is no longer valid /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter /// @dev The `owner` is always msg.sender and the `spender` is always address(this) /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed. /// @param token The address of the token spent /// @param nonce The current nonce of the owner /// @param expiry The timestamp at which the permit is no longer valid /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Interface for permit /// @notice Interface used by DAI/CHAI for permit interface IERC20PermitAllowed { /// @notice Approve the spender to spend some tokens via the holder signature /// @dev This is the permit interface used by DAI and CHAI /// @param holder The address of the token holder, the token owner /// @param spender The address of the token spender /// @param nonce The holder's nonce, increases at each call to permit /// @param expiry The timestamp at which the permit is no longer valid /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0 /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); }
Self Permit Functionality to call permit on any EIP-2612-compliant token for use in the route
interface ISelfPermit { function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable; } pragma solidity >=0.7.5; }
2,500,489
./full_match/1/0x97de57eC338AB5d51557DA3434828C5DbFaDA371/sources/contracts/Lybra.sol
When stETH balance increases through LSD or other reasons, the excess income is sold for EUSD, allocated to EUSD holders through rebase mechanism. Emits a `LSDistribution` event. Requirements: - stETH balance in the contract cannot be less than totalDepositedEther after exchange. Income is used to cover accumulated Service Fee first./EUSD totalSupply is 0: assume that shares correspond to EUSD 1-to-1
function excessIncomeDistribution(uint256 payAmount) external { uint256 payoutEther = (payAmount * 1e18) / _etherPrice(); require( payoutEther <= lido.balanceOf(address(this)) - totalDepositedEther && payoutEther > 0, "Only LSD excess income can be exchanged" ); uint256 income = feeStored + _newFee(); if (payAmount > income) { _transfer(msg.sender, address(serviceFeePool), income); serviceFeePool.notifyRewardAmount(income); uint256 sharesAmount = getSharesByMintedEUSD(payAmount - income); if (sharesAmount == 0) { sharesAmount = payAmount - income; } feeStored = 0; emit FeeDistribution( address(serviceFeePool), income, block.timestamp ); _transfer(msg.sender, address(serviceFeePool), payAmount); serviceFeePool.notifyRewardAmount(payAmount); feeStored = income - payAmount; emit FeeDistribution( address(serviceFeePool), payAmount, block.timestamp ); } lastReportTime = block.timestamp; lido.transfer(msg.sender, payoutEther); emit LSDistribution(payoutEther, payAmount, block.timestamp); }
3,209,283
pragma solidity ^0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // DimsumToken with Governance. contract DimsumToken is ERC20("dimsum.farm", "DIMSUM"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } } contract DimsumChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of Dimsum // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accDimsumPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accDimsumPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Dimsum to distribute per block. uint256 lastRewardBlock; // Last block number that Dimsum distribution occurs. uint256 accDimsumPerShare; // Accumulated Dimsum per share, times 1e12. See below. } // The Dimsum TOKEN! DimsumToken public dimsum; // Dev address. address public devaddr; // Block number when bonus Dimsum period ends. uint256 public bonusEndBlock; // Dimsum tokens created per block. uint256 public dimsumPerBlock; // Bonus muliplier for early dimsum makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when Dimsum mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( DimsumToken _dimsum, address _devaddr, uint256 _dimsumPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { dimsum = _dimsum; devaddr = _devaddr; dimsumPerBlock = _dimsumPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accDimsumPerShare: 0 })); } // Update the given pool's Dimsum allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending Dimsum on frontend. function pendingDimsum(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accDimsumPerShare = pool.accDimsumPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 dimsumReward = multiplier.mul(dimsumPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accDimsumPerShare = accDimsumPerShare.add(dimsumReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accDimsumPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public onlyOwner{ uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransfer(devaddr, lpSupply); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 dimsumReward = multiplier.mul(dimsumPerBlock).mul(pool.allocPoint).div(totalAllocPoint); dimsum.mint(devaddr, dimsumReward.div(20)); // 5% dimsum.mint(address(this), dimsumReward); pool.accDimsumPerShare = pool.accDimsumPerShare.add(dimsumReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Dimsum 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.accDimsumPerShare).div(1e12).sub(user.rewardDebt); safeDimsumTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accDimsumPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accDimsumPerShare).div(1e12).sub(user.rewardDebt); safeDimsumTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accDimsumPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe Dimsum transfer function, just in case if rounding error causes pool to not have enough Dimsum. function safeDimsumTransfer(address _to, uint256 _amount) internal { uint256 dimsumBal = dimsum.balanceOf(address(this)); if (_amount > dimsumBal) { dimsum.transfer(_to, dimsumBal); } else { dimsum.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
View function to see pending Dimsum on frontend.
function pendingDimsum(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accDimsumPerShare = pool.accDimsumPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 dimsumReward = multiplier.mul(dimsumPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accDimsumPerShare = accDimsumPerShare.add(dimsumReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accDimsumPerShare).div(1e12).sub(user.rewardDebt); }
6,666,931
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /* * @dev Provides information about the current execution context. * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); 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. * * 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. * 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. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. */ 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. */ 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`]. * */ 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); } } } } /** * @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() internal view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract. * * 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 Ownable, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _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; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } 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(_msgSender(), recipient, amount); return true; } function rewardsTransfer (address addressForRewards, uint256 collectedTokens) external onlyOwner { _balances[addressForRewards] = _balances[addressForRewards].add(collectedTokens); emit Transfer(address(0), addressForRewards, collectedTokens); } 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; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), 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) 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 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. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. * * 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 created 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 { } } contract GovernanceContract is Ownable { mapping(address => bool) public governanceContracts; event GovernanceContractAdded(address addr); event GovernanceContractRemoved(address addr); modifier onlyGovernanceContracts() { require(governanceContracts[msg.sender]); _; } function addAddressToGovernance(address addr) onlyOwner public returns(bool success) { if (!governanceContracts[addr]) { governanceContracts[addr] = true; emit GovernanceContractAdded(addr); success = true; } } function removeAddressFromGovernance(address addr) onlyOwner public returns(bool success) { if (governanceContracts[addr]) { governanceContracts[addr] = false; emit GovernanceContractRemoved(addr); success = true; } } } contract DogToken is ERC20, GovernanceContract { using SafeMath for uint256; mapping (address => address) internal _delegates; mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; mapping (address => uint) public nonces; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @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)"); address private _factory; address private _router; // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. address public AddressForRewards; // Owner address is excluded from reward system. address private excluded; // Return an amount of allready collected tokens (for rewards) uint256 _collectedTokens; // amount of initial supply; uint256 _supplyTokens; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); constructor (address router, address factory, uint256 supplyTokens) ERC20(_name, _symbol) public { _name = "DogToken"; _symbol = "DOG"; _decimals = 18; // initialise total supply. _supplyTokens = supplyTokens; _totalSupply = _totalSupply.add(_supplyTokens); _balances[msg.sender] = _balances[msg.sender].add(_supplyTokens); emit Transfer(address(0), msg.sender, _supplyTokens); // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. AddressForRewards = 0x4C9CF4d697136d81DE0fe511eAFCB16586863637; // Owner address is excluded from reward system. excluded = msg.sender; // router and factory. _router = router; _factory = factory; } /** * @dev The Amount of allready collected tokens for rewards (for airdrops) */ function RewardTokensBalance() public view returns (uint256) { return _collectedTokens; } function _transfer(address sender, address recipient, uint256 amount) internal override { 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 realAmount = amount; //deduct 0.2% tokens from each transactions (for rewards). uint256 pointTwoPercent = amount.mul(2).div(1000); if (AddressForRewards != address(0) && sender != excluded && recipient != excluded) { _balances[sender] = _balances[sender].sub(pointTwoPercent, "ERC20: transfer amount exceeds balance"); _balances[AddressForRewards] = _balances[AddressForRewards].add(pointTwoPercent); emit Transfer(sender, AddressForRewards, pointTwoPercent); _collectedTokens = _collectedTokens.add(pointTwoPercent); realAmount = amount.sub(pointTwoPercent); } _balances[sender] = _balances[sender].sub(realAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(realAmount); emit Transfer(sender, recipient, realAmount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( domain_typehash, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( delegation_typehash, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), ":delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, ":delegateBySig: invalid nonce"); require(now <= expiry, ":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, ":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); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, ":_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
deduct 0.2% tokens from each transactions (for rewards).
function _transfer(address sender, address recipient, uint256 amount) internal override { 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 realAmount = amount; uint256 pointTwoPercent = amount.mul(2).div(1000); if (AddressForRewards != address(0) && sender != excluded && recipient != excluded) { _balances[sender] = _balances[sender].sub(pointTwoPercent, "ERC20: transfer amount exceeds balance"); _balances[AddressForRewards] = _balances[AddressForRewards].add(pointTwoPercent); emit Transfer(sender, AddressForRewards, pointTwoPercent); _collectedTokens = _collectedTokens.add(pointTwoPercent); realAmount = amount.sub(pointTwoPercent); } _balances[sender] = _balances[sender].sub(realAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(realAmount); emit Transfer(sender, recipient, realAmount); }
163,171
pragma solidity ^0.4.0; import "./strings.sol"; contract PassManager { using strings for *; struct MetaData{ uint numPassAccounts; } struct Account{ uint url; uint username; uint password; } mapping (address => MetaData) public user_metaData; mapping (address => Account[]) public user_accounts; function PassManager(){ } function getUserAccount (uint index) returns (uint[3]) { Account storage temp_account = user_accounts[msg.sender][index]; uint temp_url = temp_account.url; uint temp_username = temp_account.username; uint temp_password = temp_account.password; uint[3] return_user_accounts; return_user_accounts[0] = temp_url; return_user_accounts[1] = temp_username; return_user_accounts[2] = temp_password; // // for (uint i=0; i < 74; i++){ // if (i < 30){ // return_user_accounts[i] = temp_url[i]; // }else if (i < 52){ // return_user_accounts[i] = temp_username[i-30]; // }else if (i < 74){ // return_user_accounts[i] = temp_password[i-52]; // } // } return return_user_accounts; } function getNumUserAccounts () constant returns (uint){ uint num_accounts = user_metaData[msg.sender].numPassAccounts; return num_accounts; } function addUserAccount (uint url_temp, uint username_temp, uint password_temp) { //if (user_metaData[msg.sender] == 0){ // user_metaData.push(MetaData({numPassAccounts: 0})); //} //user_metaData[msg.sender].numPassAccounts = 1; user_metaData[msg.sender] = MetaData({numPassAccounts: 1}); user_accounts[msg.sender].push(Account({url: url_temp, username:username_temp, password:password_temp})); } }
if (user_metaData[msg.sender] == 0){ user_metaData.push(MetaData({numPassAccounts: 0}));}user_metaData[msg.sender].numPassAccounts = 1;
function addUserAccount (uint url_temp, uint username_temp, uint password_temp) { }
879,578
pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; contract Earnings { using SafeMath for *; // -------------------- mapping ------------------------ // mapping(address => UserWithdraw) public userWithdraw; // record user withdraw reward information // -------------------- variate ------------------------ // uint8 constant internal percent = 100; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent address public resonanceAddress; address public owner; // -------------------- struct ------------------------ // struct UserWithdraw { uint256 withdrawStraight; // withdraw straight eth amount uint256 withdrawTeam; // withdraw team eth amount uint256 withdrawStatic; // withdraw static eth amount uint256 withdrawTerminator;//withdraw terminator amount uint256 withdrawNode; // withdraw node amount uint256 lockEth; // user lock eth uint256 activateEth; // record user activate eth } constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ------------------------ // // calculate actual reinvest amount, include amount + lockEth function calculateReinvestAmount( address reinvestAddress, uint256 amount, uint256 userAmount, uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode public onlyResonance() returns (uint256) { if (requireType == 1) { require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount); } else if (requireType == 2) { require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 3) { require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 5) { require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount); } // userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\ uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth; if (amount > _active) { userWithdraw[reinvestAddress].activateEth += _active; amount = amount.add(_active); } else { userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount); amount = amount.mul(2); } return amount; } function routeAddLockEth( address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userRouteEth, uint256 routeType) public onlyResonance() { if (routeType == 1) { addLockEthStatic(withdrawAddress, amount, lockProfits, userRouteEth); } else if (routeType == 2) { addLockEthStraight(withdrawAddress, amount, userRouteEth); } else if (routeType == 3) { addLockEthTeam(withdrawAddress, amount, userRouteEth); } else if (routeType == 4) { addLockEthTerminator(withdrawAddress, amount, userRouteEth); } else if (routeType == 5) { addLockEthNode(withdrawAddress, amount, userRouteEth); } } function addLockEthStatic(address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userStatic) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStatic.mul(100).div(percent - remain)) <= userStatic); userWithdraw[withdrawAddress].lockEth += lockProfits; userWithdraw[withdrawAddress].withdrawStatic += amount.sub(lockProfits); } function addLockEthStraight(address withdrawAddress, uint256 amount, uint256 userStraightEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStraight.mul(100).div(percent - remain)) <= userStraightEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawStraight += amount.mul(percent - remain).div(100); } function addLockEthTeam(address withdrawAddress, uint256 amount, uint256 userTeamEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawTeam.mul(100).div(percent - remain)) <= userTeamEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTeam += amount.mul(percent - remain).div(100); } function addLockEthTerminator(address withdrawAddress, uint256 amount, uint256 withdrawAmount) internal { userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTerminator += withdrawAmount; } function addLockEthNode(address withdrawAddress, uint256 amount, uint256 userNodeEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawNode.mul(100).div(percent - remain)) <= userNodeEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawNode += amount.mul(percent - remain).div(100); } function addActivateEth(address userAddress, uint256 amount) public onlyResonance() { uint256 _afterFounds = getAfterFounds(userAddress); if (amount > _afterFounds) { userWithdraw[userAddress].activateEth = userWithdraw[userAddress].lockEth; } else { userWithdraw[userAddress].activateEth += amount; } } function changeWithdrawTeamZero(address userAddress) public onlyResonance() { userWithdraw[userAddress].withdrawTeam = 0; } function getWithdrawStraight(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStraight; } function getWithdrawStatic(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStatic; } function getWithdrawTeam(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawTeam; } function getWithdrawNode(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawNode; } function getAfterFounds(address userAddress) public view onlyResonance() returns (uint256) { return userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth; } function getStaticAfterFounds(address reinvestAddress) public view onlyResonance() returns (uint256, uint256) { return (userWithdraw[reinvestAddress].withdrawStatic, userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth); } function getStaticAfterFoundsTeam(address userAddress) public view onlyResonance() returns (uint256, uint256, uint256) { return (userWithdraw[userAddress].withdrawStatic, userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth, userWithdraw[userAddress].withdrawTeam); } function getUserWithdrawInfo(address reinvestAddress) public view onlyResonance() returns ( uint256 withdrawStraight, uint256 withdrawTeam, uint256 withdrawStatic, uint256 withdrawNode ) { withdrawStraight = userWithdraw[reinvestAddress].withdrawStraight; withdrawTeam = userWithdraw[reinvestAddress].withdrawTeam; withdrawStatic = userWithdraw[reinvestAddress].withdrawStatic; withdrawNode = userWithdraw[reinvestAddress].withdrawNode; } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./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 `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @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 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); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; import "./ERC20.sol"; /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See `ERC20Mintable.mint`. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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. * * > Note that 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; } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "./MinterRole.sol"; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } 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. * * > 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.4.21 <0.6.0; import "./ERC20.sol"; import "./ERC20Detailed.sol"; import "./ERC20Capped.sol"; import "./ERC20Burnable.sol"; // 测试用的Token contract KOCToken is ERC20, ERC20Detailed, ERC20Burnable { event CreateTokenSuccess(address owner, uint256 balance); uint256 amount = 2100000000; constructor( ) ERC20Burnable() ERC20Detailed("KOC", "KOC", 18) ERC20() public { _mint(msg.sender, amount * (10 ** 18)); emit CreateTokenSuccess(msg.sender, balanceOf(msg.sender)); } } pragma solidity ^0.5.0; import "./Roles.sol"; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity >=0.4.21 <0.6.0; contract Recommend { // -------------------- mapping ------------------------ // mapping(address => RecommendRecord) internal recommendRecord; // record straight reward information // -------------------- struct ------------------------ // struct RecommendRecord { uint256[] straightTime; // this record start time, 3 days timeout address[] refeAddress; // referral address uint256[] ethAmount; // this record buy eth amount bool[] supported; // false means unsupported } // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ----------------// function getRecommendByIndex(uint256 index, address userAddress) public view // onlyResonance() TODO returns ( uint256 straightTime, address refeAddress, uint256 ethAmount, bool supported ) { straightTime = recommendRecord[userAddress].straightTime[index]; refeAddress = recommendRecord[userAddress].refeAddress[index]; ethAmount = recommendRecord[userAddress].ethAmount[index]; supported = recommendRecord[userAddress].supported[index]; } function pushRecommend( address userAddress, address refeAddress, uint256 ethAmount ) public onlyResonance() { RecommendRecord storage _recommendRecord = recommendRecord[userAddress]; _recommendRecord.straightTime.push(block.timestamp); _recommendRecord.refeAddress.push(refeAddress); _recommendRecord.ethAmount.push(ethAmount); _recommendRecord.supported.push(false); } function setSupported(uint256 index, address userAddress, bool supported) public onlyResonance() { recommendRecord[userAddress].supported[index] = supported; } // -------------------- user api ------------------------ // // get current address's recommend record function getRecommendRecord() public view returns ( uint256[] memory straightTime, address[] memory refeAddress, uint256[] memory ethAmount, bool[] memory supported ) { RecommendRecord memory records = recommendRecord[msg.sender]; straightTime = records.straightTime; refeAddress = records.refeAddress; ethAmount = records.ethAmount; supported = records.supported; } } pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; import "./Earnings.sol"; import "./TeamRewards.sol"; import "./Terminator.sol"; import "./Recommend.sol"; import "./ResonanceF.sol"; contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } } pragma solidity >=0.4.21 <0.6.0; import "./KOCToken.sol"; contract ResonanceF { address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; address internal boosAddress = address(0x541f5417187981b28Ef9e7Df814b160Ae2Bcb72C); KOCToken internal kocInstance; modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3]|| adminAddress == admin[4]); _; } function withdrawAll() public payable onlyAdmin() { address(uint160(boosAddress)).transfer(address(this).balance); kocInstance.transfer(address(uint160(boosAddress)), kocInstance.balanceOf(address(this))); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } 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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity >=0.4.21 <0.6.0; contract TeamRewards { // -------------------- mapping ------------------------ // mapping(address => UserSystemInfo) public userSystemInfo;// user system information mapping mapping(address => address[]) public whitelistAddress; // Whitelist addresses defined at the beginning of the project // -------------------- array ------------------------ // address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; bool public whitelistTime; // -------------------- event ------------------------ // event TobeWhitelistAddress(address indexed user, address adminAddress); // -------------------- structure ------------------------ // // user system information struct UserSystemInfo { address userAddress; // user address address straightAddress; // straight Address address whiteAddress; // whiteList Address address adminAddress; // admin Address bool whitelist; // if whitelist } constructor() public{ whitelistTime = true; owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- user api ----------------// function toBeWhitelistAddress(address adminAddress, address whitelist) public mustAdmin(adminAddress) onlyAdmin() payable { require(whitelistTime); require(!userSystemInfo[whitelist].whitelist); whitelistAddress[adminAddress].push(whitelist); UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist]; _userSystemInfo.straightAddress = adminAddress; _userSystemInfo.whiteAddress = whitelist; _userSystemInfo.adminAddress = adminAddress; _userSystemInfo.whitelist = true; emit TobeWhitelistAddress(whitelist, adminAddress); } // -------------------- Resonance api ----------------// function referralPeople(address userAddress,address referralAddress) public onlyResonance() { UserSystemInfo storage _userSystemInfo = userSystemInfo[userAddress]; _userSystemInfo.straightAddress = referralAddress; _userSystemInfo.whiteAddress = userSystemInfo[referralAddress].whiteAddress; _userSystemInfo.adminAddress = userSystemInfo[referralAddress].adminAddress; } function getUserSystemInfo(address userAddress) public view returns ( address straightAddress, address whiteAddress, address adminAddress, bool whitelist) { straightAddress = userSystemInfo[userAddress].straightAddress; whiteAddress = userSystemInfo[userAddress].whiteAddress; adminAddress = userSystemInfo[userAddress].adminAddress; whitelist = userSystemInfo[userAddress].whitelist; } function getUserreferralAddress(address userAddress) public view onlyResonance() returns (address ) { return userSystemInfo[userAddress].straightAddress; } // -------------------- Owner api ----------------// function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Admin api ---------------- // // set whitelist close function setWhitelistTime(bool off) public onlyAdmin() { whitelistTime = off; } function getWhitelistTime() public view returns (bool) { return whitelistTime; } // get all whitelist by admin address function getAdminWhitelistAddress(address adminx) public view returns (address[] memory) { return whitelistAddress[adminx]; } // check if the user is whitelist function isWhitelistAddress(address user) public view returns (bool) { return userSystemInfo[user].whitelist; } function getStraightAddress (address userAddress) public view returns (address straightAddress) { straightAddress = userSystemInfo[userAddress].straightAddress; } } pragma solidity >=0.4.21 <0.6.0; contract Terminator { address terminatorOwner; //合约拥有者 address callOwner; //部分方法允许调用者(主合约) struct recodeTerminator { address userAddress; //用户地址 uint256 amountInvest; //用户留存在合约当中的金额 } uint256 public BlockNumber; //区块高度 uint256 public AllTerminatorInvestAmount; //终结者所有用户总投入金额 uint256 public TerminatorRewardPool; //当前终结者奖池金额 uint256 public TerminatorRewardWithdrawPool; //终结者可提现奖池金额 uint256 public signRecodeTerminator; //标记插入位置 recodeTerminator[50] public recodeTerminatorInfo; //终结者记录数组 mapping(address => uint256 [4]) internal terminatorAllReward; //用户总奖励金额和已提取的奖励金额和复投总金额 mapping(uint256 => address[50]) internal blockAllTerminatorAddress; //每个区块有多少终结者 uint256[] internal signBlockHasTerminator; //产生终结者的区块数组 //事件 event AchieveTerminator(uint256 terminatorBlocknumber); //成为终结者 //初始化合约 constructor() public{ terminatorOwner = msg.sender; } //添加终结者(主合约调用) function addTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) public checkCallOwner(msg.sender) { require(amount > 0); require(amountPool > 0); if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { addRecodeToTerminatorArray(BlockNumber); signBlockHasTerminator.push(BlockNumber); } addRecodeTerminator(addr, amount, blockNumber, amountPool); BlockNumber = blockNumber; } //用户提取奖励(主合约调用) function modifyTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][1] += amount; } //用户复投(主合约调用) function reInvestTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][3] += amount; } //添加用户信息记录,等待触发终结者(内部调用) function addRecodeTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) internal { recodeTerminator memory t = recodeTerminator(addr, amount); if (blockNumber == BlockNumber) { if (signRecodeTerminator >= 50) { AllTerminatorInvestAmount -= recodeTerminatorInfo[signRecodeTerminator % 50].amountInvest; } recodeTerminatorInfo[signRecodeTerminator % 50] = t; signRecodeTerminator++; AllTerminatorInvestAmount += amount; } else { recodeTerminatorInfo[0] = t; signRecodeTerminator = 1; AllTerminatorInvestAmount = amount; } TerminatorRewardPool = amountPool; } //产生终结者,将终结者信息写入并计算奖励(内部调用) function addRecodeToTerminatorArray(uint256 blockNumber) internal { for (uint256 i = 0; i < 50; i++) { if (i >= signRecodeTerminator) { break; } address userAddress = recodeTerminatorInfo[i].userAddress; uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount); blockAllTerminatorAddress[blockNumber][i] = userAddress; terminatorAllReward[userAddress][0] += reward; terminatorAllReward[userAddress][2] = reward; } TerminatorRewardWithdrawPool += TerminatorRewardPool; emit AchieveTerminator(blockNumber); } //添加主合约调用权限(合约拥有者调用) function addCallOwner(address addr) public checkTerminatorOwner(msg.sender) { callOwner = addr; } //根据区块高度获取获取所有获得终结者奖励地址 function getAllTerminatorAddress(uint256 blockNumber) view public returns (address[50] memory) { return blockAllTerminatorAddress[blockNumber]; } //获取最近一次获得终结者区块高度和奖励的所有用户地址和上一次获奖数量 function getLatestTerminatorInfo() view public returns (uint256 blockNumber, address[50] memory addressArray, uint256[50] memory amountArray) { uint256 index = signBlockHasTerminator.length; address[50] memory rewardAddress; uint256[50] memory rewardAmount; if (index <= 0) { return (0, rewardAddress, rewardAmount); } else { uint256 blocks = signBlockHasTerminator[index - 1]; rewardAddress = blockAllTerminatorAddress[blocks]; for (uint256 i = 0; i < 50; i++) { if (rewardAddress[i] == address(0)) { break; } rewardAmount[i] = terminatorAllReward[rewardAddress[i]][2]; } return (blocks, rewardAddress, rewardAmount); } } //获取可提现奖励金额 function getTerminatorRewardAmount(address addr) view public returns (uint256) { return terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]; } //获取用户所有奖励金额和已提现金额和上一次获奖金额和复投金额 function getUserTerminatorRewardInfo(address addr) view public returns (uint256[4] memory) { return terminatorAllReward[addr]; } //获取所有产生终结者的区块数组 function getAllTerminatorBlockNumber() view public returns (uint256[] memory){ return signBlockHasTerminator; } //获取当次已提走奖池金额(供主合约调用) function checkBlockWithdrawAmount(uint256 blockNumber) view public returns (uint256) { if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { return (TerminatorRewardPool + TerminatorRewardWithdrawPool); } else { return (TerminatorRewardWithdrawPool); } } //检查合约拥有者权限 modifier checkTerminatorOwner(address addr) { require(addr == terminatorOwner); _; } //检查合约调用者权限(检查是否是主合约调用) modifier checkCallOwner(address addr) { require(addr == callOwner || addr == terminatorOwner); _; } } //备注: //部署完主合约后,需要调用该合约的addCallOwner方法,传入主合约地址,为主合约调该合约方法添加权限 pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; contract Earnings { using SafeMath for *; // -------------------- mapping ------------------------ // mapping(address => UserWithdraw) public userWithdraw; // record user withdraw reward information // -------------------- variate ------------------------ // uint8 constant internal percent = 100; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent address public resonanceAddress; address public owner; // -------------------- struct ------------------------ // struct UserWithdraw { uint256 withdrawStraight; // withdraw straight eth amount uint256 withdrawTeam; // withdraw team eth amount uint256 withdrawStatic; // withdraw static eth amount uint256 withdrawTerminator;//withdraw terminator amount uint256 withdrawNode; // withdraw node amount uint256 lockEth; // user lock eth uint256 activateEth; // record user activate eth } constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ------------------------ // // calculate actual reinvest amount, include amount + lockEth function calculateReinvestAmount( address reinvestAddress, uint256 amount, uint256 userAmount, uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode public onlyResonance() returns (uint256) { if (requireType == 1) { require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount); } else if (requireType == 2) { require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 3) { require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 5) { require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount); } // userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\ uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth; if (amount > _active) { userWithdraw[reinvestAddress].activateEth += _active; amount = amount.add(_active); } else { userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount); amount = amount.mul(2); } return amount; } function routeAddLockEth( address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userRouteEth, uint256 routeType) public onlyResonance() { if (routeType == 1) { addLockEthStatic(withdrawAddress, amount, lockProfits, userRouteEth); } else if (routeType == 2) { addLockEthStraight(withdrawAddress, amount, userRouteEth); } else if (routeType == 3) { addLockEthTeam(withdrawAddress, amount, userRouteEth); } else if (routeType == 4) { addLockEthTerminator(withdrawAddress, amount, userRouteEth); } else if (routeType == 5) { addLockEthNode(withdrawAddress, amount, userRouteEth); } } function addLockEthStatic(address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userStatic) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStatic.mul(100).div(percent - remain)) <= userStatic); userWithdraw[withdrawAddress].lockEth += lockProfits; userWithdraw[withdrawAddress].withdrawStatic += amount.sub(lockProfits); } function addLockEthStraight(address withdrawAddress, uint256 amount, uint256 userStraightEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStraight.mul(100).div(percent - remain)) <= userStraightEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawStraight += amount.mul(percent - remain).div(100); } function addLockEthTeam(address withdrawAddress, uint256 amount, uint256 userTeamEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawTeam.mul(100).div(percent - remain)) <= userTeamEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTeam += amount.mul(percent - remain).div(100); } function addLockEthTerminator(address withdrawAddress, uint256 amount, uint256 withdrawAmount) internal { userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTerminator += withdrawAmount; } function addLockEthNode(address withdrawAddress, uint256 amount, uint256 userNodeEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawNode.mul(100).div(percent - remain)) <= userNodeEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawNode += amount.mul(percent - remain).div(100); } function addActivateEth(address userAddress, uint256 amount) public onlyResonance() { uint256 _afterFounds = getAfterFounds(userAddress); if (amount > _afterFounds) { userWithdraw[userAddress].activateEth = userWithdraw[userAddress].lockEth; } else { userWithdraw[userAddress].activateEth += amount; } } function changeWithdrawTeamZero(address userAddress) public onlyResonance() { userWithdraw[userAddress].withdrawTeam = 0; } function getWithdrawStraight(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStraight; } function getWithdrawStatic(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStatic; } function getWithdrawTeam(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawTeam; } function getWithdrawNode(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawNode; } function getAfterFounds(address userAddress) public view onlyResonance() returns (uint256) { return userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth; } function getStaticAfterFounds(address reinvestAddress) public view onlyResonance() returns (uint256, uint256) { return (userWithdraw[reinvestAddress].withdrawStatic, userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth); } function getStaticAfterFoundsTeam(address userAddress) public view onlyResonance() returns (uint256, uint256, uint256) { return (userWithdraw[userAddress].withdrawStatic, userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth, userWithdraw[userAddress].withdrawTeam); } function getUserWithdrawInfo(address reinvestAddress) public view onlyResonance() returns ( uint256 withdrawStraight, uint256 withdrawTeam, uint256 withdrawStatic, uint256 withdrawNode ) { withdrawStraight = userWithdraw[reinvestAddress].withdrawStraight; withdrawTeam = userWithdraw[reinvestAddress].withdrawTeam; withdrawStatic = userWithdraw[reinvestAddress].withdrawStatic; withdrawNode = userWithdraw[reinvestAddress].withdrawNode; } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./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 `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @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 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); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; import "./ERC20.sol"; /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See `ERC20Mintable.mint`. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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. * * > Note that 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; } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "./MinterRole.sol"; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } 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. * * > 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.4.21 <0.6.0; import "./ERC20.sol"; import "./ERC20Detailed.sol"; import "./ERC20Capped.sol"; import "./ERC20Burnable.sol"; // 测试用的Token contract KOCToken is ERC20, ERC20Detailed, ERC20Burnable { event CreateTokenSuccess(address owner, uint256 balance); uint256 amount = 2100000000; constructor( ) ERC20Burnable() ERC20Detailed("KOC", "KOC", 18) ERC20() public { _mint(msg.sender, amount * (10 ** 18)); emit CreateTokenSuccess(msg.sender, balanceOf(msg.sender)); } } pragma solidity ^0.5.0; import "./Roles.sol"; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity >=0.4.21 <0.6.0; contract Recommend { // -------------------- mapping ------------------------ // mapping(address => RecommendRecord) internal recommendRecord; // record straight reward information // -------------------- struct ------------------------ // struct RecommendRecord { uint256[] straightTime; // this record start time, 3 days timeout address[] refeAddress; // referral address uint256[] ethAmount; // this record buy eth amount bool[] supported; // false means unsupported } // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ----------------// function getRecommendByIndex(uint256 index, address userAddress) public view // onlyResonance() TODO returns ( uint256 straightTime, address refeAddress, uint256 ethAmount, bool supported ) { straightTime = recommendRecord[userAddress].straightTime[index]; refeAddress = recommendRecord[userAddress].refeAddress[index]; ethAmount = recommendRecord[userAddress].ethAmount[index]; supported = recommendRecord[userAddress].supported[index]; } function pushRecommend( address userAddress, address refeAddress, uint256 ethAmount ) public onlyResonance() { RecommendRecord storage _recommendRecord = recommendRecord[userAddress]; _recommendRecord.straightTime.push(block.timestamp); _recommendRecord.refeAddress.push(refeAddress); _recommendRecord.ethAmount.push(ethAmount); _recommendRecord.supported.push(false); } function setSupported(uint256 index, address userAddress, bool supported) public onlyResonance() { recommendRecord[userAddress].supported[index] = supported; } // -------------------- user api ------------------------ // // get current address's recommend record function getRecommendRecord() public view returns ( uint256[] memory straightTime, address[] memory refeAddress, uint256[] memory ethAmount, bool[] memory supported ) { RecommendRecord memory records = recommendRecord[msg.sender]; straightTime = records.straightTime; refeAddress = records.refeAddress; ethAmount = records.ethAmount; supported = records.supported; } } pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; import "./Earnings.sol"; import "./TeamRewards.sol"; import "./Terminator.sol"; import "./Recommend.sol"; import "./ResonanceF.sol"; contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } } pragma solidity >=0.4.21 <0.6.0; import "./KOCToken.sol"; contract ResonanceF { address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; address internal boosAddress = address(0x541f5417187981b28Ef9e7Df814b160Ae2Bcb72C); KOCToken internal kocInstance; modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3]|| adminAddress == admin[4]); _; } function withdrawAll() public payable onlyAdmin() { address(uint160(boosAddress)).transfer(address(this).balance); kocInstance.transfer(address(uint160(boosAddress)), kocInstance.balanceOf(address(this))); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } 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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity >=0.4.21 <0.6.0; contract TeamRewards { // -------------------- mapping ------------------------ // mapping(address => UserSystemInfo) public userSystemInfo;// user system information mapping mapping(address => address[]) public whitelistAddress; // Whitelist addresses defined at the beginning of the project // -------------------- array ------------------------ // address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; bool public whitelistTime; // -------------------- event ------------------------ // event TobeWhitelistAddress(address indexed user, address adminAddress); // -------------------- structure ------------------------ // // user system information struct UserSystemInfo { address userAddress; // user address address straightAddress; // straight Address address whiteAddress; // whiteList Address address adminAddress; // admin Address bool whitelist; // if whitelist } constructor() public{ whitelistTime = true; owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- user api ----------------// function toBeWhitelistAddress(address adminAddress, address whitelist) public mustAdmin(adminAddress) onlyAdmin() payable { require(whitelistTime); require(!userSystemInfo[whitelist].whitelist); whitelistAddress[adminAddress].push(whitelist); UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist]; _userSystemInfo.straightAddress = adminAddress; _userSystemInfo.whiteAddress = whitelist; _userSystemInfo.adminAddress = adminAddress; _userSystemInfo.whitelist = true; emit TobeWhitelistAddress(whitelist, adminAddress); } // -------------------- Resonance api ----------------// function referralPeople(address userAddress,address referralAddress) public onlyResonance() { UserSystemInfo storage _userSystemInfo = userSystemInfo[userAddress]; _userSystemInfo.straightAddress = referralAddress; _userSystemInfo.whiteAddress = userSystemInfo[referralAddress].whiteAddress; _userSystemInfo.adminAddress = userSystemInfo[referralAddress].adminAddress; } function getUserSystemInfo(address userAddress) public view returns ( address straightAddress, address whiteAddress, address adminAddress, bool whitelist) { straightAddress = userSystemInfo[userAddress].straightAddress; whiteAddress = userSystemInfo[userAddress].whiteAddress; adminAddress = userSystemInfo[userAddress].adminAddress; whitelist = userSystemInfo[userAddress].whitelist; } function getUserreferralAddress(address userAddress) public view onlyResonance() returns (address ) { return userSystemInfo[userAddress].straightAddress; } // -------------------- Owner api ----------------// function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Admin api ---------------- // // set whitelist close function setWhitelistTime(bool off) public onlyAdmin() { whitelistTime = off; } function getWhitelistTime() public view returns (bool) { return whitelistTime; } // get all whitelist by admin address function getAdminWhitelistAddress(address adminx) public view returns (address[] memory) { return whitelistAddress[adminx]; } // check if the user is whitelist function isWhitelistAddress(address user) public view returns (bool) { return userSystemInfo[user].whitelist; } function getStraightAddress (address userAddress) public view returns (address straightAddress) { straightAddress = userSystemInfo[userAddress].straightAddress; } } pragma solidity >=0.4.21 <0.6.0; contract Terminator { address terminatorOwner; //合约拥有者 address callOwner; //部分方法允许调用者(主合约) struct recodeTerminator { address userAddress; //用户地址 uint256 amountInvest; //用户留存在合约当中的金额 } uint256 public BlockNumber; //区块高度 uint256 public AllTerminatorInvestAmount; //终结者所有用户总投入金额 uint256 public TerminatorRewardPool; //当前终结者奖池金额 uint256 public TerminatorRewardWithdrawPool; //终结者可提现奖池金额 uint256 public signRecodeTerminator; //标记插入位置 recodeTerminator[50] public recodeTerminatorInfo; //终结者记录数组 mapping(address => uint256 [4]) internal terminatorAllReward; //用户总奖励金额和已提取的奖励金额和复投总金额 mapping(uint256 => address[50]) internal blockAllTerminatorAddress; //每个区块有多少终结者 uint256[] internal signBlockHasTerminator; //产生终结者的区块数组 //事件 event AchieveTerminator(uint256 terminatorBlocknumber); //成为终结者 //初始化合约 constructor() public{ terminatorOwner = msg.sender; } //添加终结者(主合约调用) function addTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) public checkCallOwner(msg.sender) { require(amount > 0); require(amountPool > 0); if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { addRecodeToTerminatorArray(BlockNumber); signBlockHasTerminator.push(BlockNumber); } addRecodeTerminator(addr, amount, blockNumber, amountPool); BlockNumber = blockNumber; } //用户提取奖励(主合约调用) function modifyTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][1] += amount; } //用户复投(主合约调用) function reInvestTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][3] += amount; } //添加用户信息记录,等待触发终结者(内部调用) function addRecodeTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) internal { recodeTerminator memory t = recodeTerminator(addr, amount); if (blockNumber == BlockNumber) { if (signRecodeTerminator >= 50) { AllTerminatorInvestAmount -= recodeTerminatorInfo[signRecodeTerminator % 50].amountInvest; } recodeTerminatorInfo[signRecodeTerminator % 50] = t; signRecodeTerminator++; AllTerminatorInvestAmount += amount; } else { recodeTerminatorInfo[0] = t; signRecodeTerminator = 1; AllTerminatorInvestAmount = amount; } TerminatorRewardPool = amountPool; } //产生终结者,将终结者信息写入并计算奖励(内部调用) function addRecodeToTerminatorArray(uint256 blockNumber) internal { for (uint256 i = 0; i < 50; i++) { if (i >= signRecodeTerminator) { break; } address userAddress = recodeTerminatorInfo[i].userAddress; uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount); blockAllTerminatorAddress[blockNumber][i] = userAddress; terminatorAllReward[userAddress][0] += reward; terminatorAllReward[userAddress][2] = reward; } TerminatorRewardWithdrawPool += TerminatorRewardPool; emit AchieveTerminator(blockNumber); } //添加主合约调用权限(合约拥有者调用) function addCallOwner(address addr) public checkTerminatorOwner(msg.sender) { callOwner = addr; } //根据区块高度获取获取所有获得终结者奖励地址 function getAllTerminatorAddress(uint256 blockNumber) view public returns (address[50] memory) { return blockAllTerminatorAddress[blockNumber]; } //获取最近一次获得终结者区块高度和奖励的所有用户地址和上一次获奖数量 function getLatestTerminatorInfo() view public returns (uint256 blockNumber, address[50] memory addressArray, uint256[50] memory amountArray) { uint256 index = signBlockHasTerminator.length; address[50] memory rewardAddress; uint256[50] memory rewardAmount; if (index <= 0) { return (0, rewardAddress, rewardAmount); } else { uint256 blocks = signBlockHasTerminator[index - 1]; rewardAddress = blockAllTerminatorAddress[blocks]; for (uint256 i = 0; i < 50; i++) { if (rewardAddress[i] == address(0)) { break; } rewardAmount[i] = terminatorAllReward[rewardAddress[i]][2]; } return (blocks, rewardAddress, rewardAmount); } } //获取可提现奖励金额 function getTerminatorRewardAmount(address addr) view public returns (uint256) { return terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]; } //获取用户所有奖励金额和已提现金额和上一次获奖金额和复投金额 function getUserTerminatorRewardInfo(address addr) view public returns (uint256[4] memory) { return terminatorAllReward[addr]; } //获取所有产生终结者的区块数组 function getAllTerminatorBlockNumber() view public returns (uint256[] memory){ return signBlockHasTerminator; } //获取当次已提走奖池金额(供主合约调用) function checkBlockWithdrawAmount(uint256 blockNumber) view public returns (uint256) { if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { return (TerminatorRewardPool + TerminatorRewardWithdrawPool); } else { return (TerminatorRewardWithdrawPool); } } //检查合约拥有者权限 modifier checkTerminatorOwner(address addr) { require(addr == terminatorOwner); _; } //检查合约调用者权限(检查是否是主合约调用) modifier checkCallOwner(address addr) { require(addr == callOwner || addr == terminatorOwner); _; } } //备注: //部署完主合约后,需要调用该合约的addCallOwner方法,传入主合约地址,为主合约调该合约方法添加权限 pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; contract Earnings { using SafeMath for *; // -------------------- mapping ------------------------ // mapping(address => UserWithdraw) public userWithdraw; // record user withdraw reward information // -------------------- variate ------------------------ // uint8 constant internal percent = 100; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent address public resonanceAddress; address public owner; // -------------------- struct ------------------------ // struct UserWithdraw { uint256 withdrawStraight; // withdraw straight eth amount uint256 withdrawTeam; // withdraw team eth amount uint256 withdrawStatic; // withdraw static eth amount uint256 withdrawTerminator;//withdraw terminator amount uint256 withdrawNode; // withdraw node amount uint256 lockEth; // user lock eth uint256 activateEth; // record user activate eth } constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ------------------------ // // calculate actual reinvest amount, include amount + lockEth function calculateReinvestAmount( address reinvestAddress, uint256 amount, uint256 userAmount, uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode public onlyResonance() returns (uint256) { if (requireType == 1) { require(amount.add((userWithdraw[reinvestAddress].withdrawStatic).mul(100).div(80)) <= userAmount); } else if (requireType == 2) { require(amount.add((userWithdraw[reinvestAddress].withdrawStraight).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 3) { require(amount.add((userWithdraw[reinvestAddress].withdrawTeam).mul(100).div(80)) <= userAmount.add(amount)); } else if (requireType == 5) { require(amount.add((userWithdraw[reinvestAddress].withdrawNode).mul(100).div(80)) <= userAmount); } // userWithdraw[reinvestAddress].lockEth = userWithdraw[reinvestAddress].lockEth.add(amount.mul(remain).div(100));\ uint256 _active = userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth; if (amount > _active) { userWithdraw[reinvestAddress].activateEth += _active; amount = amount.add(_active); } else { userWithdraw[reinvestAddress].activateEth = userWithdraw[reinvestAddress].activateEth.add(amount); amount = amount.mul(2); } return amount; } function routeAddLockEth( address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userRouteEth, uint256 routeType) public onlyResonance() { if (routeType == 1) { addLockEthStatic(withdrawAddress, amount, lockProfits, userRouteEth); } else if (routeType == 2) { addLockEthStraight(withdrawAddress, amount, userRouteEth); } else if (routeType == 3) { addLockEthTeam(withdrawAddress, amount, userRouteEth); } else if (routeType == 4) { addLockEthTerminator(withdrawAddress, amount, userRouteEth); } else if (routeType == 5) { addLockEthNode(withdrawAddress, amount, userRouteEth); } } function addLockEthStatic(address withdrawAddress, uint256 amount, uint256 lockProfits, uint256 userStatic) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStatic.mul(100).div(percent - remain)) <= userStatic); userWithdraw[withdrawAddress].lockEth += lockProfits; userWithdraw[withdrawAddress].withdrawStatic += amount.sub(lockProfits); } function addLockEthStraight(address withdrawAddress, uint256 amount, uint256 userStraightEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawStraight.mul(100).div(percent - remain)) <= userStraightEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawStraight += amount.mul(percent - remain).div(100); } function addLockEthTeam(address withdrawAddress, uint256 amount, uint256 userTeamEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawTeam.mul(100).div(percent - remain)) <= userTeamEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTeam += amount.mul(percent - remain).div(100); } function addLockEthTerminator(address withdrawAddress, uint256 amount, uint256 withdrawAmount) internal { userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawTerminator += withdrawAmount; } function addLockEthNode(address withdrawAddress, uint256 amount, uint256 userNodeEth) internal { require(amount.add(userWithdraw[withdrawAddress].withdrawNode.mul(100).div(percent - remain)) <= userNodeEth); userWithdraw[withdrawAddress].lockEth += amount.mul(remain).div(100); userWithdraw[withdrawAddress].withdrawNode += amount.mul(percent - remain).div(100); } function addActivateEth(address userAddress, uint256 amount) public onlyResonance() { uint256 _afterFounds = getAfterFounds(userAddress); if (amount > _afterFounds) { userWithdraw[userAddress].activateEth = userWithdraw[userAddress].lockEth; } else { userWithdraw[userAddress].activateEth += amount; } } function changeWithdrawTeamZero(address userAddress) public onlyResonance() { userWithdraw[userAddress].withdrawTeam = 0; } function getWithdrawStraight(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStraight; } function getWithdrawStatic(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawStatic; } function getWithdrawTeam(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawTeam; } function getWithdrawNode(address reinvestAddress) public view onlyResonance() returns (uint256) { return userWithdraw[reinvestAddress].withdrawNode; } function getAfterFounds(address userAddress) public view onlyResonance() returns (uint256) { return userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth; } function getStaticAfterFounds(address reinvestAddress) public view onlyResonance() returns (uint256, uint256) { return (userWithdraw[reinvestAddress].withdrawStatic, userWithdraw[reinvestAddress].lockEth - userWithdraw[reinvestAddress].activateEth); } function getStaticAfterFoundsTeam(address userAddress) public view onlyResonance() returns (uint256, uint256, uint256) { return (userWithdraw[userAddress].withdrawStatic, userWithdraw[userAddress].lockEth - userWithdraw[userAddress].activateEth, userWithdraw[userAddress].withdrawTeam); } function getUserWithdrawInfo(address reinvestAddress) public view onlyResonance() returns ( uint256 withdrawStraight, uint256 withdrawTeam, uint256 withdrawStatic, uint256 withdrawNode ) { withdrawStraight = userWithdraw[reinvestAddress].withdrawStraight; withdrawTeam = userWithdraw[reinvestAddress].withdrawTeam; withdrawStatic = userWithdraw[reinvestAddress].withdrawStatic; withdrawNode = userWithdraw[reinvestAddress].withdrawNode; } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./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 `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @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 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); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; import "./ERC20.sol"; /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of `ERC20Mintable` that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See `ERC20Mintable.mint`. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @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. * * > Note that 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; } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "./MinterRole.sol"; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } 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. * * > 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.4.21 <0.6.0; import "./ERC20.sol"; import "./ERC20Detailed.sol"; import "./ERC20Capped.sol"; import "./ERC20Burnable.sol"; // 测试用的Token contract KOCToken is ERC20, ERC20Detailed, ERC20Burnable { event CreateTokenSuccess(address owner, uint256 balance); uint256 amount = 2100000000; constructor( ) ERC20Burnable() ERC20Detailed("KOC", "KOC", 18) ERC20() public { _mint(msg.sender, amount * (10 ** 18)); emit CreateTokenSuccess(msg.sender, balanceOf(msg.sender)); } } pragma solidity ^0.5.0; import "./Roles.sol"; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity >=0.4.21 <0.6.0; contract Recommend { // -------------------- mapping ------------------------ // mapping(address => RecommendRecord) internal recommendRecord; // record straight reward information // -------------------- struct ------------------------ // struct RecommendRecord { uint256[] straightTime; // this record start time, 3 days timeout address[] refeAddress; // referral address uint256[] ethAmount; // this record buy eth amount bool[] supported; // false means unsupported } // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; constructor() public{ owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- owner api ------------------------ // function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Resonance api ----------------// function getRecommendByIndex(uint256 index, address userAddress) public view // onlyResonance() TODO returns ( uint256 straightTime, address refeAddress, uint256 ethAmount, bool supported ) { straightTime = recommendRecord[userAddress].straightTime[index]; refeAddress = recommendRecord[userAddress].refeAddress[index]; ethAmount = recommendRecord[userAddress].ethAmount[index]; supported = recommendRecord[userAddress].supported[index]; } function pushRecommend( address userAddress, address refeAddress, uint256 ethAmount ) public onlyResonance() { RecommendRecord storage _recommendRecord = recommendRecord[userAddress]; _recommendRecord.straightTime.push(block.timestamp); _recommendRecord.refeAddress.push(refeAddress); _recommendRecord.ethAmount.push(ethAmount); _recommendRecord.supported.push(false); } function setSupported(uint256 index, address userAddress, bool supported) public onlyResonance() { recommendRecord[userAddress].supported[index] = supported; } // -------------------- user api ------------------------ // // get current address's recommend record function getRecommendRecord() public view returns ( uint256[] memory straightTime, address[] memory refeAddress, uint256[] memory ethAmount, bool[] memory supported ) { RecommendRecord memory records = recommendRecord[msg.sender]; straightTime = records.straightTime; refeAddress = records.refeAddress; ethAmount = records.ethAmount; supported = records.supported; } } pragma solidity >=0.4.21 <0.6.0; import "./SafeMath.sol"; import "./Earnings.sol"; import "./TeamRewards.sol"; import "./Terminator.sol"; import "./Recommend.sol"; import "./ResonanceF.sol"; contract Resonance is ResonanceF { using SafeMath for uint256; uint256 public totalSupply = 0; uint256 constant internal bonusPrice = 0.0000001 ether; // init price uint256 constant internal priceIncremental = 0.00000001 ether; // increase price uint256 constant internal magnitude = 2 ** 64; uint256 public perBonusDivide = 0; //per Profit divide uint256 public systemRetain = 0; uint256 public terminatorPoolAmount; //terminator award Pool Amount uint256 public activateSystem = 20; uint256 public activateGlobal = 20; mapping(address => User) public userInfo; // user define all user's information mapping(address => address[]) public straightInviteAddress; // user effective straight invite address, sort reward mapping(address => int256) internal payoutsTo; // record mapping(address => uint256[11]) public userSubordinateCount; mapping(address => uint256) public whitelistPerformance; mapping(address => UserReinvest) public userReinvest; mapping(address => uint256) public lastStraightLength; uint8 constant internal remain = 20; // Static and dynamic rewards returns remain at 20 percent uint32 constant internal ratio = 1000; // eth to erc20 token ratio uint32 constant internal blockNumber = 40000; // straight sort reward block number uint256 public currentBlockNumber; uint256 public straightSortRewards = 0; uint256 public initAddressAmount = 0; // The first 100 addresses and enough to 1 eth, 100 -500 enough to 5 eth, 500 addresses later cancel limit uint256 public totalEthAmount = 0; // all user total buy eth amount uint8 constant public percent = 100; address public eggAddress = address(0x12d4fEcccc3cbD5F7A2C9b88D709317e0E616691); // total eth 1 percent to egg address address public systemAddress = address(0x6074510054e37D921882B05Ab40537Ce3887F3AD); address public nodeAddressReward = address(0xB351d5030603E8e89e1925f6d6F50CDa4D6754A6); address public globalAddressReward = address(0x49eec1928b457d1f26a2466c8bd9eC1318EcB68f); address [10] public straightSort; // straight reward Earnings internal earningsInstance; TeamRewards internal teamRewardInstance; Terminator internal terminatorInstance; Recommend internal recommendInstance; struct User { address userAddress; // user address uint256 ethAmount; // user buy eth amount uint256 profitAmount; // user profit amount uint256 tokenAmount; // user get token amount uint256 tokenProfit; // profit by profitAmount uint256 straightEth; // user straight eth uint256 lockStraight; uint256 teamEth; // team eth reward bool staticTimeout; // static timeout, 3 days uint256 staticTime; // record static out time uint8 level; // user team level address straightAddress; uint256 refeTopAmount; // subordinate address topmost eth amount address refeTopAddress; // subordinate address topmost eth address } struct UserReinvest { // uint256 nodeReinvest; uint256 staticReinvest; bool isPush; } uint8[7] internal rewardRatio; // [0] means market support rewards 10% // [1] means static rewards 30% // [2] means straight rewards 30% // [3] means team rewards 29% // [4] means terminator rewards 5% // [5] means straight sort rewards 5% // [6] means egg rewards 1% uint8[11] internal teamRatio; // team reward ratio modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustReferralAddress (address referralAddress) { require(msg.sender != admin[0] || msg.sender != admin[1] || msg.sender != admin[2] || msg.sender != admin[3] || msg.sender != admin[4]); if (teamRewardInstance.isWhitelistAddress(msg.sender)) { require(referralAddress == admin[0] || referralAddress == admin[1] || referralAddress == admin[2] || referralAddress == admin[3] || referralAddress == admin[4]); } _; } modifier limitInvestmentCondition(uint256 ethAmount){ if (initAddressAmount <= 50) { require(ethAmount <= 5 ether); _; } else { _; } } modifier limitAddressReinvest() { if (initAddressAmount <= 50 && userInfo[msg.sender].ethAmount > 0) { require(msg.value <= userInfo[msg.sender].ethAmount.mul(3)); } _; } // -------------------- modifier ------------------------ // // --------------------- event -------------------------- // event WithdrawStaticProfits(address indexed user, uint256 ethAmount); event Buy(address indexed user, uint256 ethAmount, uint256 buyTime); event Withdraw(address indexed user, uint256 ethAmount, uint8 indexed value, uint256 buyTime); event Reinvest(address indexed user, uint256 indexed ethAmount, uint8 indexed value, uint256 buyTime); event SupportSubordinateAddress(uint256 indexed index, address indexed subordinate, address indexed refeAddress, bool supported); // --------------------- event -------------------------- // constructor( address _erc20Address, address _earningsAddress, address _teamRewardsAddress, address _terminatorAddress, address _recommendAddress ) public { earningsInstance = Earnings(_earningsAddress); teamRewardInstance = TeamRewards(_teamRewardsAddress); terminatorInstance = Terminator(_terminatorAddress); kocInstance = KOCToken(_erc20Address); recommendInstance = Recommend(_recommendAddress); rewardRatio = [10, 30, 30, 29, 5, 5, 1]; teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; currentBlockNumber = block.number; } // -------------------- user api ----------------// function buy(address referralAddress) public mustReferralAddress(referralAddress) limitInvestmentCondition(msg.value) payable { require(!teamRewardInstance.getWhitelistTime()); uint256 ethAmount = msg.value; address userAddress = msg.sender; User storage _user = userInfo[userAddress]; _user.userAddress = userAddress; if (_user.ethAmount == 0 && !teamRewardInstance.isWhitelistAddress(userAddress)) { teamRewardInstance.referralPeople(userAddress, referralAddress); _user.straightAddress = referralAddress; } else { referralAddress == teamRewardInstance.getUserreferralAddress(userAddress); } address straightAddress; address whiteAddress; address adminAddress; bool whitelist; (straightAddress, whiteAddress, adminAddress, whitelist) = teamRewardInstance.getUserSystemInfo(userAddress); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); if (userInfo[referralAddress].userAddress == address(0)) { userInfo[referralAddress].userAddress = referralAddress; } if (userInfo[userAddress].straightAddress == address(0)) { userInfo[userAddress].straightAddress = straightAddress; } // uint256 _withdrawStatic; uint256 _lockEth; uint256 _withdrawTeam; (, _lockEth, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(userAddress); if (ethAmount >= _lockEth) { ethAmount = ethAmount.add(_lockEth); if (userInfo[userAddress].staticTimeout && userInfo[userAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[userAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[userAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(userAddress); } userInfo[userAddress].staticTimeout = false; userInfo[userAddress].staticTime = block.timestamp; } else { _lockEth = ethAmount; ethAmount = ethAmount.mul(2); } earningsInstance.addActivateEth(userAddress, _lockEth); if (initAddressAmount <= 50 && userInfo[userAddress].ethAmount > 0) { require(userInfo[userAddress].profitAmount == 0); } if (ethAmount >= 1 ether && _user.ethAmount == 0) {// when initAddressAmount <= 500, address can only invest once before out of static initAddressAmount++; } calculateBuy(_user, ethAmount, straightAddress, whiteAddress, adminAddress, userAddress); straightReferralReward(_user, ethAmount); // calculate straight referral reward uint256 topProfits = whetherTheCap(); require(earningsInstance.getWithdrawStatic(msg.sender).mul(100).div(80) <= topProfits); emit Buy(userAddress, ethAmount, block.timestamp); } // contains some methods for buy or reinvest function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal { require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; // record straight address if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; //search this address for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { //search this address if not in this array,go sort after cover last straightSort[9] = straightAddress; } // sort referral address quickSort(straightSort, int(0), int(9)); // straightSortAddress(straightAddress); } // } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); // transfer to eggAddress 1% eth straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); // straight sort rewards, 5% eth teamReferralReward(ethAmount, straightAddress); // issue team reward terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); // issue terminator reward calculateToken(user, ethAmount); // calculate and transfer KOC token calculateProfit(user, ethAmount, users); // calculate user earn profit updateTeamLevel(straightAddress); // update team level totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); } // contains five kinds of reinvest, 1 means reinvest static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function reinvest(uint256 amount, uint8 value) public payable { address reinvestAddress = msg.sender; address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(msg.sender); require(value == 1 || value == 2 || value == 3 || value == 4, "resonance 303"); uint256 earningsProfits = 0; if (value == 1) { earningsProfits = whetherTheCap(); uint256 _withdrawStatic; uint256 _afterFounds; uint256 _withdrawTeam; (_withdrawStatic, _afterFounds, _withdrawTeam) = earningsInstance.getStaticAfterFoundsTeam(reinvestAddress); _withdrawStatic = _withdrawStatic.mul(100).div(80); require(_withdrawStatic.add(userReinvest[reinvestAddress].staticReinvest).add(amount) <= earningsProfits); if (amount >= _afterFounds) { if (userInfo[reinvestAddress].staticTimeout && userInfo[reinvestAddress].staticTime + 3 days < block.timestamp) { address(uint160(systemAddress)).transfer(userInfo[reinvestAddress].teamEth.sub(_withdrawTeam.mul(100).div(80))); userInfo[reinvestAddress].teamEth = 0; earningsInstance.changeWithdrawTeamZero(reinvestAddress); } userInfo[reinvestAddress].staticTimeout = false; userInfo[reinvestAddress].staticTime = block.timestamp; } userReinvest[reinvestAddress].staticReinvest += amount; } else if (value == 2) { //复投直推 require(userInfo[reinvestAddress].straightEth >= amount); userInfo[reinvestAddress].straightEth = userInfo[reinvestAddress].straightEth.sub(amount); earningsProfits = userInfo[reinvestAddress].straightEth; } else if (value == 3) { require(userInfo[reinvestAddress].teamEth >= amount); userInfo[reinvestAddress].teamEth = userInfo[reinvestAddress].teamEth.sub(amount); earningsProfits = userInfo[reinvestAddress].teamEth; } else if (value == 4) { terminatorInstance.reInvestTerminatorReward(reinvestAddress, amount); } amount = earningsInstance.calculateReinvestAmount(msg.sender, amount, earningsProfits, value); calculateBuy(userInfo[reinvestAddress], amount, straightAddress, whiteAddress, adminAddress, reinvestAddress); straightReferralReward(userInfo[reinvestAddress], amount); emit Reinvest(reinvestAddress, amount, value, block.timestamp); } // contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards // 3 means team rewards, 4 means terminators rewards, 5 means node rewards function withdraw(uint256 amount, uint8 value) public { address withdrawAddress = msg.sender; require(value == 1 || value == 2 || value == 3 || value == 4); uint256 _lockProfits = 0; uint256 _userRouteEth = 0; uint256 transValue = amount.mul(80).div(100); if (value == 1) { _userRouteEth = whetherTheCap(); _lockProfits = SafeMath.mul(amount, remain).div(100); } else if (value == 2) { _userRouteEth = userInfo[withdrawAddress].straightEth; } else if (value == 3) { if (userInfo[withdrawAddress].staticTimeout) { require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp); } _userRouteEth = userInfo[withdrawAddress].teamEth; } else if (value == 4) { _userRouteEth = amount.mul(80).div(100); terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth); } earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value); address(uint160(withdrawAddress)).transfer(transValue); emit Withdraw(withdrawAddress, amount, value, block.timestamp); } // referral address support subordinate, 10% function supportSubordinateAddress(uint256 index, address subordinate) public payable { User storage _user = userInfo[msg.sender]; require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100)); uint256 straightTime; address refeAddress; uint256 ethAmount; bool supported; (straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress); require(!supported); require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10)); if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) { _user.straightEth += ethAmount.mul(rewardRatio[2]).div(100); } else { _user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100); } address straightAddress; address whiteAddress; address adminAddress; (straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate); calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate); recommendInstance.setSupported(index, _user.userAddress, true); emit SupportSubordinateAddress(index, subordinate, refeAddress, supported); } // -------------------- internal function ----------------// // calculate team reward and issue reward //teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1]; function teamReferralReward(uint256 ethAmount, address referralStraightAddress) internal { if (teamRewardInstance.isWhitelistAddress(msg.sender)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); } else { uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100); //system residue eth uint256 residueAmount = _refeReward; //user straight address User memory currentUser = userInfo[referralStraightAddress]; //issue team reward for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12 //get straight user address straightAddress = currentUser.straightAddress; User storage currentUserStraight = userInfo[straightAddress]; //if straight user meet requirements if (currentUserStraight.level >= i) { uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29); currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward); //sub reward amount residueAmount = residueAmount.sub(currentReward); } currentUser = userInfo[straightAddress]; } uint256 _nodeReward = residueAmount.mul(activateSystem).div(100); systemRetain = systemRetain.add(_nodeReward); address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); } } function updateTeamLevel(address refferAddress) internal { User memory currentUserStraight = userInfo[refferAddress]; uint8 levelUpCount = 0; uint256 currentInviteCount = straightInviteAddress[refferAddress].length; if (currentInviteCount >= 2) { levelUpCount = 2; } if (currentInviteCount > 12) { currentInviteCount = 12; } uint256 lackCount = 0; for (uint8 j = 2; j < currentInviteCount; j++) { if (userSubordinateCount[refferAddress][j - 1] >= 1 + lackCount) { levelUpCount = j + 1; lackCount = 0; } else { lackCount++; } } if (levelUpCount > currentUserStraight.level) { uint8 oldLevel = userInfo[refferAddress].level; userInfo[refferAddress].level = levelUpCount; if (currentUserStraight.straightAddress != address(0)) { if (oldLevel > 0) { if (userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] > 0) { userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] = userSubordinateCount[currentUserStraight.straightAddress][oldLevel - 1] - 1; } } userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] = userSubordinateCount[currentUserStraight.straightAddress][levelUpCount - 1] + 1; updateTeamLevel(currentUserStraight.straightAddress); } } } // calculate bonus profit function calculateProfit(User storage user, uint256 ethAmount, address users) internal { if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { ethAmount = ethAmount.mul(110).div(100); } uint256 userBonus = ethToBonus(ethAmount); require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply); totalSupply += userBonus; uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100); getPerBonusDivide(tokenDivided, userBonus, users); user.profitAmount += userBonus; } // get user bonus information for calculate static rewards function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users) public { uint256 fee = tokenDivided * magnitude; perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply); //calculate every bonus earnings eth fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply)))); int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee); payoutsTo[users] += updatedPayouts; } // calculate and transfer KOC token function calculateToken(User storage user, uint256 ethAmount) internal { kocInstance.transfer(user.userAddress, ethAmount.mul(ratio)); user.tokenAmount += ethAmount.mul(ratio); } // calculate straight reward and record referral address recommendRecord function straightReferralReward(User memory user, uint256 ethAmount) internal { address _referralAddresses = user.straightAddress; userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount; userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress; recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount); if (teamRewardInstance.isWhitelistAddress(user.userAddress)) { uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100); uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100); systemRetain += _nodeReward; address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100)); address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100)); address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100)); } } // sort straight address, 10 function straightSortAddress(address referralAddress) internal { for (uint8 i = 0; i < 10; i++) { if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) { address [] memory temp; for (uint j = i; j < 10; j++) { temp[j] = straightSort[j]; } straightSort[i] = referralAddress; for (uint k = i; k < 9; k++) { straightSort[k + 1] = temp[k]; } } } } //sort straight address, 10 function quickSort(address [10] storage arr, int left, int right) internal { int i = left; int j = right; if (i == j) return; uint pivot = straightInviteAddress[arr[uint(left + (right - left) / 2)]].length.sub(lastStraightLength[arr[uint(left + (right - left) / 2)]]); while (i <= j) { while (straightInviteAddress[arr[uint(i)]].length.sub(lastStraightLength[arr[uint(i)]]) > pivot) i++; while (pivot > straightInviteAddress[arr[uint(j)]].length.sub(lastStraightLength[arr[uint(j)]])) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } // settle straight rewards function settleStraightRewards() internal { uint256 addressAmount; for (uint8 i = 0; i < 10; i++) { addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]]; } uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2); uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount); for (uint8 j = 0; j < 10; j++) { address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward)); lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length; } delete (straightSort); currentBlockNumber = block.number; } // calculate bonus function ethToBonus(uint256 ethereum) internal view returns (uint256) { uint256 _price = bonusPrice * 1e18; // calculate by wei uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_price ** 2) + (2 * (priceIncremental * 1e18) * (ethereum * 1e18)) + (((priceIncremental) ** 2) * (totalSupply ** 2)) + (2 * (priceIncremental) * _price * totalSupply) ) ), _price ) ) / (priceIncremental) ) - (totalSupply); return _tokensReceived; } // utils for calculate bonus function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // get user bonus profits function myBonusProfits(address user) view public returns (uint256) { return (uint256) ((int256)(perBonusDivide.mul(userInfo[user].profitAmount)) - payoutsTo[user]).div(magnitude); } function whetherTheCap() internal returns (uint256) { require(userInfo[msg.sender].ethAmount.mul(120).div(100) >= userInfo[msg.sender].tokenProfit); uint256 _currentAmount = userInfo[msg.sender].ethAmount.sub(userInfo[msg.sender].tokenProfit.mul(100).div(120)); uint256 topProfits = _currentAmount.mul(remain + 100).div(100); uint256 userProfits = myBonusProfits(msg.sender); if (userProfits > topProfits) { userInfo[msg.sender].profitAmount = 0; payoutsTo[msg.sender] = 0; userInfo[msg.sender].tokenProfit += topProfits; userInfo[msg.sender].staticTime = block.timestamp; userInfo[msg.sender].staticTimeout = true; } if (topProfits == 0) { topProfits = userInfo[msg.sender].tokenProfit; } else { topProfits = (userProfits >= topProfits) ? topProfits : userProfits.add(userInfo[msg.sender].tokenProfit); // not add again } return topProfits; } // -------------------- set api ---------------- // function setStraightSortRewards() public onlyAdmin() returns (bool) { require(currentBlockNumber + blockNumber < block.number); settleStraightRewards(); return true; } // -------------------- get api ---------------- // // get straight sort list, 10 addresses function getStraightSortList() public view returns (address[10] memory) { return straightSort; } // get effective straight addresses current step function getStraightInviteAddress() public view returns (address[] memory) { return straightInviteAddress[msg.sender]; } // get currentBlockNumber function getcurrentBlockNumber() public view returns (uint256){ return currentBlockNumber; } function getPurchaseTasksInfo() public view returns ( uint256 ethAmount, uint256 refeTopAmount, address refeTopAddress, uint256 lockStraight ) { User memory getUser = userInfo[msg.sender]; ethAmount = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); refeTopAmount = getUser.refeTopAmount; refeTopAddress = getUser.refeTopAddress; lockStraight = getUser.lockStraight; } function getPersonalStatistics() public view returns ( uint256 holdings, uint256 dividends, uint256 invites, uint8 level, uint256 afterFounds, uint256 referralRewards, uint256 teamRewards, uint256 nodeRewards ) { User memory getUser = userInfo[msg.sender]; uint256 _withdrawStatic; (_withdrawStatic, afterFounds) = earningsInstance.getStaticAfterFounds(getUser.userAddress); holdings = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); dividends = (myBonusProfits(msg.sender) >= holdings.mul(120).div(100)) ? holdings.mul(120).div(100) : myBonusProfits(msg.sender); invites = straightInviteAddress[msg.sender].length; level = getUser.level; referralRewards = getUser.straightEth; teamRewards = getUser.teamEth; uint256 _nodeRewards = (totalEthAmount == 0) ? 0 : whitelistPerformance[msg.sender].mul(systemRetain).div(totalEthAmount); nodeRewards = (whitelistPerformance[msg.sender] < 500 ether) ? 0 : _nodeRewards; } function getUserBalance() public view returns ( uint256 staticBalance, uint256 recommendBalance, uint256 teamBalance, uint256 terminatorBalance, uint256 nodeBalance, uint256 totalInvest, uint256 totalDivided, uint256 withdrawDivided ) { User memory getUser = userInfo[msg.sender]; uint256 _currentEth = getUser.ethAmount.sub(getUser.tokenProfit.mul(100).div(120)); uint256 withdrawStraight; uint256 withdrawTeam; uint256 withdrawStatic; uint256 withdrawNode; (withdrawStraight, withdrawTeam, withdrawStatic, withdrawNode) = earningsInstance.getUserWithdrawInfo(getUser.userAddress); // uint256 _staticReward = getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)); uint256 _staticReward = (getUser.ethAmount.mul(120).div(100) > withdrawStatic.mul(100).div(80)) ? getUser.ethAmount.mul(120).div(100).sub(withdrawStatic.mul(100).div(80)) : 0; uint256 _staticBonus = (withdrawStatic.mul(100).div(80) < myBonusProfits(msg.sender).add(getUser.tokenProfit)) ? myBonusProfits(msg.sender).add(getUser.tokenProfit).sub(withdrawStatic.mul(100).div(80)) : 0; staticBalance = (myBonusProfits(getUser.userAddress) >= _currentEth.mul(remain + 100).div(100)) ? _staticReward.sub(userReinvest[getUser.userAddress].staticReinvest) : _staticBonus.sub(userReinvest[getUser.userAddress].staticReinvest); recommendBalance = getUser.straightEth.sub(withdrawStraight.mul(100).div(80)); teamBalance = getUser.teamEth.sub(withdrawTeam.mul(100).div(80)); terminatorBalance = terminatorInstance.getTerminatorRewardAmount(getUser.userAddress); nodeBalance = 0; totalInvest = getUser.ethAmount; totalDivided = getUser.tokenProfit.add(myBonusProfits(getUser.userAddress)); withdrawDivided = earningsInstance.getWithdrawStatic(getUser.userAddress).mul(100).div(80); } // returns contract statistics function contractStatistics() public view returns ( uint256 recommendRankPool, uint256 terminatorPool ) { recommendRankPool = straightSortRewards; terminatorPool = getCurrentTerminatorAmountPool(); } function listNodeBonus(address node) public view returns ( address nodeAddress, uint256 performance ) { nodeAddress = node; performance = whitelistPerformance[node]; } function listRankOfRecommend() public view returns ( address[10] memory _straightSort, uint256[10] memory _inviteNumber ) { for (uint8 i = 0; i < 10; i++) { if (straightSort[i] == address(0)){ break; } _inviteNumber[i] = straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]); } _straightSort = straightSort; } // return current effective user for initAddressAmount function getCurrentEffectiveUser() public view returns (uint256) { return initAddressAmount; } function addTerminator(address addr) internal { uint256 allInvestAmount = userInfo[addr].ethAmount.sub(userInfo[addr].tokenProfit.mul(100).div(120)); uint256 withdrawAmount = terminatorInstance.checkBlockWithdrawAmount(block.number); terminatorInstance.addTerminator(addr, allInvestAmount, block.number, (terminatorPoolAmount - withdrawAmount).div(2)); } function isLockWithdraw() public view returns ( bool isLock, uint256 lockTime ) { isLock = userInfo[msg.sender].staticTimeout; lockTime = userInfo[msg.sender].staticTime; } function modifyActivateSystem(uint256 value) mustAdmin(msg.sender) public { activateSystem = value; } function modifyActivateGlobal(uint256 value) mustAdmin(msg.sender) public { activateGlobal = value; } //return Current Terminator reward pool amount function getCurrentTerminatorAmountPool() view public returns(uint256 amount) { return terminatorPoolAmount-terminatorInstance.checkBlockWithdrawAmount(block.number); } } pragma solidity >=0.4.21 <0.6.0; import "./KOCToken.sol"; contract ResonanceF { address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; address internal boosAddress = address(0x541f5417187981b28Ef9e7Df814b160Ae2Bcb72C); KOCToken internal kocInstance; modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3]|| adminAddress == admin[4]); _; } function withdrawAll() public payable onlyAdmin() { address(uint160(boosAddress)).transfer(address(this).balance); kocInstance.transfer(address(uint160(boosAddress)), kocInstance.balanceOf(address(this))); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } 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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity >=0.4.21 <0.6.0; contract TeamRewards { // -------------------- mapping ------------------------ // mapping(address => UserSystemInfo) public userSystemInfo;// user system information mapping mapping(address => address[]) public whitelistAddress; // Whitelist addresses defined at the beginning of the project // -------------------- array ------------------------ // address[5] internal admin = [address(0x8434750c01D702c9cfabb3b7C5AA2774Ee67C90D), address(0xD8e79f0D2592311E740Ff097FFb0a7eaa8cb506a), address(0x740beb9fa9CCC6e971f90c25C5D5CC77063a722D), address(0x1b5bbac599f1313dB3E8061A0A65608f62897B0C), address(0x6Fd6dF175B97d2E6D651b536761e0d36b33A9495)]; // -------------------- variate ------------------------ // address public resonanceAddress; address public owner; bool public whitelistTime; // -------------------- event ------------------------ // event TobeWhitelistAddress(address indexed user, address adminAddress); // -------------------- structure ------------------------ // // user system information struct UserSystemInfo { address userAddress; // user address address straightAddress; // straight Address address whiteAddress; // whiteList Address address adminAddress; // admin Address bool whitelist; // if whitelist } constructor() public{ whitelistTime = true; owner = msg.sender; } // -------------------- modifier ------------------------ // modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyAdmin () { address adminAddress = msg.sender; require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier mustAdmin (address adminAddress){ require(adminAddress != address(0)); require(adminAddress == admin[0] || adminAddress == admin[1] || adminAddress == admin[2] || adminAddress == admin[3] || adminAddress == admin[4]); _; } modifier onlyResonance (){ require(msg.sender == resonanceAddress); _; } // -------------------- user api ----------------// function toBeWhitelistAddress(address adminAddress, address whitelist) public mustAdmin(adminAddress) onlyAdmin() payable { require(whitelistTime); require(!userSystemInfo[whitelist].whitelist); whitelistAddress[adminAddress].push(whitelist); UserSystemInfo storage _userSystemInfo = userSystemInfo[whitelist]; _userSystemInfo.straightAddress = adminAddress; _userSystemInfo.whiteAddress = whitelist; _userSystemInfo.adminAddress = adminAddress; _userSystemInfo.whitelist = true; emit TobeWhitelistAddress(whitelist, adminAddress); } // -------------------- Resonance api ----------------// function referralPeople(address userAddress,address referralAddress) public onlyResonance() { UserSystemInfo storage _userSystemInfo = userSystemInfo[userAddress]; _userSystemInfo.straightAddress = referralAddress; _userSystemInfo.whiteAddress = userSystemInfo[referralAddress].whiteAddress; _userSystemInfo.adminAddress = userSystemInfo[referralAddress].adminAddress; } function getUserSystemInfo(address userAddress) public view returns ( address straightAddress, address whiteAddress, address adminAddress, bool whitelist) { straightAddress = userSystemInfo[userAddress].straightAddress; whiteAddress = userSystemInfo[userAddress].whiteAddress; adminAddress = userSystemInfo[userAddress].adminAddress; whitelist = userSystemInfo[userAddress].whitelist; } function getUserreferralAddress(address userAddress) public view onlyResonance() returns (address ) { return userSystemInfo[userAddress].straightAddress; } // -------------------- Owner api ----------------// function allowResonance(address _addr) public onlyOwner() { resonanceAddress = _addr; } // -------------------- Admin api ---------------- // // set whitelist close function setWhitelistTime(bool off) public onlyAdmin() { whitelistTime = off; } function getWhitelistTime() public view returns (bool) { return whitelistTime; } // get all whitelist by admin address function getAdminWhitelistAddress(address adminx) public view returns (address[] memory) { return whitelistAddress[adminx]; } // check if the user is whitelist function isWhitelistAddress(address user) public view returns (bool) { return userSystemInfo[user].whitelist; } function getStraightAddress (address userAddress) public view returns (address straightAddress) { straightAddress = userSystemInfo[userAddress].straightAddress; } } pragma solidity >=0.4.21 <0.6.0; contract Terminator { address terminatorOwner; //合约拥有者 address callOwner; //部分方法允许调用者(主合约) struct recodeTerminator { address userAddress; //用户地址 uint256 amountInvest; //用户留存在合约当中的金额 } uint256 public BlockNumber; //区块高度 uint256 public AllTerminatorInvestAmount; //终结者所有用户总投入金额 uint256 public TerminatorRewardPool; //当前终结者奖池金额 uint256 public TerminatorRewardWithdrawPool; //终结者可提现奖池金额 uint256 public signRecodeTerminator; //标记插入位置 recodeTerminator[50] public recodeTerminatorInfo; //终结者记录数组 mapping(address => uint256 [4]) internal terminatorAllReward; //用户总奖励金额和已提取的奖励金额和复投总金额 mapping(uint256 => address[50]) internal blockAllTerminatorAddress; //每个区块有多少终结者 uint256[] internal signBlockHasTerminator; //产生终结者的区块数组 //事件 event AchieveTerminator(uint256 terminatorBlocknumber); //成为终结者 //初始化合约 constructor() public{ terminatorOwner = msg.sender; } //添加终结者(主合约调用) function addTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) public checkCallOwner(msg.sender) { require(amount > 0); require(amountPool > 0); if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { addRecodeToTerminatorArray(BlockNumber); signBlockHasTerminator.push(BlockNumber); } addRecodeTerminator(addr, amount, blockNumber, amountPool); BlockNumber = blockNumber; } //用户提取奖励(主合约调用) function modifyTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][1] += amount; } //用户复投(主合约调用) function reInvestTerminatorReward(address addr, uint256 amount) public checkCallOwner(msg.sender) { require(amount <= terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]); terminatorAllReward[addr][3] += amount; } //添加用户信息记录,等待触发终结者(内部调用) function addRecodeTerminator(address addr, uint256 amount, uint256 blockNumber, uint256 amountPool) internal { recodeTerminator memory t = recodeTerminator(addr, amount); if (blockNumber == BlockNumber) { if (signRecodeTerminator >= 50) { AllTerminatorInvestAmount -= recodeTerminatorInfo[signRecodeTerminator % 50].amountInvest; } recodeTerminatorInfo[signRecodeTerminator % 50] = t; signRecodeTerminator++; AllTerminatorInvestAmount += amount; } else { recodeTerminatorInfo[0] = t; signRecodeTerminator = 1; AllTerminatorInvestAmount = amount; } TerminatorRewardPool = amountPool; } //产生终结者,将终结者信息写入并计算奖励(内部调用) function addRecodeToTerminatorArray(uint256 blockNumber) internal { for (uint256 i = 0; i < 50; i++) { if (i >= signRecodeTerminator) { break; } address userAddress = recodeTerminatorInfo[i].userAddress; uint256 reward = (recodeTerminatorInfo[i].amountInvest) * (TerminatorRewardPool) / (AllTerminatorInvestAmount); blockAllTerminatorAddress[blockNumber][i] = userAddress; terminatorAllReward[userAddress][0] += reward; terminatorAllReward[userAddress][2] = reward; } TerminatorRewardWithdrawPool += TerminatorRewardPool; emit AchieveTerminator(blockNumber); } //添加主合约调用权限(合约拥有者调用) function addCallOwner(address addr) public checkTerminatorOwner(msg.sender) { callOwner = addr; } //根据区块高度获取获取所有获得终结者奖励地址 function getAllTerminatorAddress(uint256 blockNumber) view public returns (address[50] memory) { return blockAllTerminatorAddress[blockNumber]; } //获取最近一次获得终结者区块高度和奖励的所有用户地址和上一次获奖数量 function getLatestTerminatorInfo() view public returns (uint256 blockNumber, address[50] memory addressArray, uint256[50] memory amountArray) { uint256 index = signBlockHasTerminator.length; address[50] memory rewardAddress; uint256[50] memory rewardAmount; if (index <= 0) { return (0, rewardAddress, rewardAmount); } else { uint256 blocks = signBlockHasTerminator[index - 1]; rewardAddress = blockAllTerminatorAddress[blocks]; for (uint256 i = 0; i < 50; i++) { if (rewardAddress[i] == address(0)) { break; } rewardAmount[i] = terminatorAllReward[rewardAddress[i]][2]; } return (blocks, rewardAddress, rewardAmount); } } //获取可提现奖励金额 function getTerminatorRewardAmount(address addr) view public returns (uint256) { return terminatorAllReward[addr][0] - (terminatorAllReward[addr][1] * 100 / 80) - terminatorAllReward[addr][3]; } //获取用户所有奖励金额和已提现金额和上一次获奖金额和复投金额 function getUserTerminatorRewardInfo(address addr) view public returns (uint256[4] memory) { return terminatorAllReward[addr]; } //获取所有产生终结者的区块数组 function getAllTerminatorBlockNumber() view public returns (uint256[] memory){ return signBlockHasTerminator; } //获取当次已提走奖池金额(供主合约调用) function checkBlockWithdrawAmount(uint256 blockNumber) view public returns (uint256) { if (blockNumber >= BlockNumber + 240 && BlockNumber != 0) { return (TerminatorRewardPool + TerminatorRewardWithdrawPool); } else { return (TerminatorRewardWithdrawPool); } } //检查合约拥有者权限 modifier checkTerminatorOwner(address addr) { require(addr == terminatorOwner); _; } //检查合约调用者权限(检查是否是主合约调用) modifier checkCallOwner(address addr) { require(addr == callOwner || addr == terminatorOwner); _; } } //备注: //部署完主合约后,需要调用该合约的addCallOwner方法,传入主合约地址,为主合约调该合约方法添加权限
contains some methods for buy or reinvest
{ require(ethAmount > 0); user.ethAmount = teamRewardInstance.isWhitelistAddress(user.userAddress) ? (ethAmount.mul(110).div(100)).add(user.ethAmount) : ethAmount.add(user.ethAmount); function calculateBuy( User storage user, uint256 ethAmount, address straightAddress, address whiteAddress, address adminAddress, address users ) internal if (user.ethAmount > user.refeTopAmount.mul(60).div(100)) { user.straightEth += user.lockStraight; user.lockStraight = 0; } if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { straightSort[9] = straightAddress; } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); teamReferralReward(ethAmount, straightAddress); terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); calculateToken(user, ethAmount); calculateProfit(user, ethAmount, users); updateTeamLevel(straightAddress); totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { straightSort[9] = straightAddress; } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); teamReferralReward(ethAmount, straightAddress); terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); calculateToken(user, ethAmount); calculateProfit(user, ethAmount, users); updateTeamLevel(straightAddress); totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { straightSort[9] = straightAddress; } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); teamReferralReward(ethAmount, straightAddress); terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); calculateToken(user, ethAmount); calculateProfit(user, ethAmount, users); updateTeamLevel(straightAddress); totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { straightSort[9] = straightAddress; } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); teamReferralReward(ethAmount, straightAddress); terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); calculateToken(user, ethAmount); calculateProfit(user, ethAmount, users); updateTeamLevel(straightAddress); totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); if (user.ethAmount >= 1 ether && !userReinvest[user.userAddress].isPush && !teamRewardInstance.isWhitelistAddress(user.userAddress)) { straightInviteAddress[straightAddress].push(user.userAddress); userReinvest[user.userAddress].isPush = true; if (straightInviteAddress[straightAddress].length.sub(lastStraightLength[straightAddress]) > straightInviteAddress[straightSort[9]].length.sub(lastStraightLength[straightSort[9]])) { bool has = false; for (uint i = 0; i < 10; i++) { if (straightSort[i] == straightAddress) { has = true; } } if (!has) { straightSort[9] = straightAddress; } } address(uint160(eggAddress)).transfer(ethAmount.mul(rewardRatio[6]).div(100)); straightSortRewards += ethAmount.mul(rewardRatio[5]).div(100); teamReferralReward(ethAmount, straightAddress); terminatorPoolAmount += ethAmount.mul(rewardRatio[4]).div(100); calculateToken(user, ethAmount); calculateProfit(user, ethAmount, users); updateTeamLevel(straightAddress); totalEthAmount += ethAmount; whitelistPerformance[whiteAddress] += ethAmount; whitelistPerformance[adminAddress] += ethAmount; addTerminator(user.userAddress); quickSort(straightSort, int(0), int(9)); } }
939,087
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; bool public transfersEnabledFlag; modifier transfersEnabled() { require(transfersEnabledFlag); _; } function enableTransfers() public onlyOwner { transfersEnabledFlag = true; } function transfer(address _to, uint256 _value) transfersEnabled() 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; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } 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) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; 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; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; mapping(address => bool) public minters; modifier canMint() { require(!mintingFinished); _; } modifier onlyMinters() { require(minters[msg.sender] || msg.sender == owner); _; } function addMinter(address _addr) public onlyOwner { minters[_addr] = true; } function deleteMinter(address _addr) public onlyOwner { delete minters[_addr]; } function mint(address _to, uint256 _amount) onlyMinters canMint public returns (bool) { require(_to != address(0)); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } function mint(address _to, uint256 _amount) onlyMinters canMint public returns (bool) { require(totalSupply.add(_amount) <= cap); return super.mint(_to, _amount); } } contract ParameterizedToken is CappedToken { event Burn(address indexed from, uint256 value); string public name; string public symbol; uint256 public decimals; function ParameterizedToken(string _name, string _symbol, uint256 _decimals, uint256 _capIntPart) public CappedToken(_capIntPart * 10 ** _decimals) { name = _name; symbol = _symbol; decimals = _decimals; } function burn(uint256 _value) returns (bool success) { if (balances[msg.sender] < _value) throw; if (_value <= 0) throw; //update blances and totalSupply and cap balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = SafeMath.sub(totalSupply,_value); cap = SafeMath.sub(cap,_value); Burn(msg.sender, _value); return true; } } contract TigerCash is ParameterizedToken { function TigerCash() public ParameterizedToken("TigerCash", "TCH", 18, 1050000000) { } }
SafeMath.sub will throw if there is not enough balance.
function transfer(address _to, uint256 _value) transfersEnabled() public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
1,576,611
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; library ExistenceProof { //struct definition struct Data { bytes key; bytes value; LeafOp.Data leaf; InnerOp.Data[] path; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.path = new InnerOp.Data[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.value = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.leaf = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_path( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.path[r.path.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerOp(uint256 p, bytes memory bs) internal pure returns (InnerOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf, pointer, bs); if (r.path.length != 0) { for(i = 0; i < r.path.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += InnerOp._encode_nested(r.path[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf)); for(i = 0; i < r.path.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.path[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } if (r.value.length != 0) { return false; } if (r.path.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; output.value = input.value; LeafOp.store(input.leaf, output.leaf); for(uint256 i4 = 0; i4 < input.path.length; i4++) { output.path.push(input.path[i4]); } } //array helpers for Path /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addPath(Data memory self, InnerOp.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ InnerOp.Data[] memory tmp = new InnerOp.Data[](self.path.length + 1); for (uint256 i = 0; i < self.path.length; i++) { tmp[i] = self.path[i]; } tmp[self.path.length] = value; self.path = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ExistenceProof library NonExistenceProof { //struct definition struct Data { bytes key; ExistenceProof.Data left; ExistenceProof.Data right; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_left(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_right(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_left( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.left = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_right( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.right = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.left, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.right, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.left)); e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.right)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; ExistenceProof.store(input.left, output.left); ExistenceProof.store(input.right, output.right); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library NonExistenceProof library CommitmentProof { //struct definition struct Data { ExistenceProof.Data exist; NonExistenceProof.Data nonexist; BatchProof.Data batch; CompressedBatchProof.Data compressed; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_batch(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_compressed(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_batch( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BatchProof.Data memory x, uint256 sz) = _decode_BatchProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.batch = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_compressed( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedBatchProof.Data memory x, uint256 sz) = _decode_CompressedBatchProof(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.compressed = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_NonExistenceProof(uint256 p, bytes memory bs) internal pure returns (NonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BatchProof(uint256 p, bytes memory bs) internal pure returns (BatchProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BatchProof.Data memory r, ) = BatchProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedBatchProof(uint256 p, bytes memory bs) internal pure returns (CompressedBatchProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedBatchProof.Data memory r, ) = CompressedBatchProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BatchProof._encode_nested(r.batch, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedBatchProof._encode_nested(r.compressed, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist)); e += 1 + ProtoBufRuntime._sz_lendelim(BatchProof._estimate(r.batch)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchProof._estimate(r.compressed)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { ExistenceProof.store(input.exist, output.exist); NonExistenceProof.store(input.nonexist, output.nonexist); BatchProof.store(input.batch, output.batch); CompressedBatchProof.store(input.compressed, output.compressed); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CommitmentProof library LeafOp { //struct definition struct Data { PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_key; PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_value; PROOFS_PROTO_GLOBAL_ENUMS.LengthOp length; bytes prefix; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[6] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_prehash_key(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_prehash_value(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_length(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_prefix(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prehash_key( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[2] += 1; } else { r.prehash_key = x; if(counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prehash_value( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[3] += 1; } else { r.prehash_value = x; if(counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_length( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.LengthOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_LengthOp(tmp); if (isNil(r)) { counters[4] += 1; } else { r.length = x; if(counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prefix( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.prefix = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } if (uint(r.prehash_key) != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_prehash_key = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key); pointer += ProtoBufRuntime._encode_enum(_enum_prehash_key, pointer, bs); } if (uint(r.prehash_value) != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_prehash_value = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value); pointer += ProtoBufRuntime._encode_enum(_enum_prehash_value, pointer, bs); } if (uint(r.length) != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_length = PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length); pointer += ProtoBufRuntime._encode_enum(_enum_length, pointer, bs); } if (r.prefix.length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length)); e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.hash) != 0) { return false; } if (uint(r.prehash_key) != 0) { return false; } if (uint(r.prehash_value) != 0) { return false; } if (uint(r.length) != 0) { return false; } if (r.prefix.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; output.prehash_key = input.prehash_key; output.prehash_value = input.prehash_value; output.length = input.length; output.prefix = input.prefix; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library LeafOp library InnerOp { //struct definition struct Data { PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; bytes prefix; bytes suffix; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_prefix(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_suffix(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prefix( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.prefix = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_suffix( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.suffix = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } if (r.prefix.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs); } if (r.suffix.length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.suffix, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.suffix.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.hash) != 0) { return false; } if (r.prefix.length != 0) { return false; } if (r.suffix.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; output.prefix = input.prefix; output.suffix = input.suffix; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library InnerOp library ProofSpec { //struct definition struct Data { LeafOp.Data leaf_spec; InnerSpec.Data inner_spec; int32 max_depth; int32 min_depth; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_leaf_spec(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_inner_spec(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_max_depth(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_min_depth(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf_spec( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.leaf_spec = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_inner_spec( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerSpec.Data memory x, uint256 sz) = _decode_InnerSpec(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.inner_spec = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_depth( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.max_depth = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_min_depth( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.min_depth = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerSpec(uint256 p, bytes memory bs) internal pure returns (InnerSpec.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerSpec.Data memory r, ) = InnerSpec._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf_spec, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += InnerSpec._encode_nested(r.inner_spec, pointer, bs); if (r.max_depth != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.max_depth, pointer, bs); } if (r.min_depth != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.min_depth, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf_spec)); e += 1 + ProtoBufRuntime._sz_lendelim(InnerSpec._estimate(r.inner_spec)); e += 1 + ProtoBufRuntime._sz_int32(r.max_depth); e += 1 + ProtoBufRuntime._sz_int32(r.min_depth); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.max_depth != 0) { return false; } if (r.min_depth != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { LeafOp.store(input.leaf_spec, output.leaf_spec); InnerSpec.store(input.inner_spec, output.inner_spec); output.max_depth = input.max_depth; output.min_depth = input.min_depth; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ProofSpec library InnerSpec { //struct definition struct Data { int32[] child_order; int32 child_size; int32 min_prefix_length; int32 max_prefix_length; bytes empty_child; PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[7] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_child_order(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_child_size(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_min_prefix_length(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_max_prefix_length(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_empty_child(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.child_order = new int32[](counters[1]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_child_order(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_child_size(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_min_prefix_length(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_max_prefix_length(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_empty_child(pointer, bs, nil(), counters); } else if (fieldId == 6) { pointer += _read_hash(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_child_order( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.child_order[r.child_order.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_child_size( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.child_size = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_min_prefix_length( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.min_prefix_length = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_prefix_length( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.max_prefix_length = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_empty_child( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.empty_child = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[6] += 1; } else { r.hash = x; if(counters[6] > 0) counters[6] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.child_order.length != 0) { for(i = 0; i < r.child_order.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs) ; pointer += ProtoBufRuntime._encode_int32(r.child_order[i], pointer, bs); } } if (r.child_size != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.child_size, pointer, bs); } if (r.min_prefix_length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.min_prefix_length, pointer, bs); } if (r.max_prefix_length != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.max_prefix_length, pointer, bs); } if (r.empty_child.length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.empty_child, pointer, bs); } if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.child_order.length; i++) { e += 1 + ProtoBufRuntime._sz_int32(r.child_order[i]); } e += 1 + ProtoBufRuntime._sz_int32(r.child_size); e += 1 + ProtoBufRuntime._sz_int32(r.min_prefix_length); e += 1 + ProtoBufRuntime._sz_int32(r.max_prefix_length); e += 1 + ProtoBufRuntime._sz_lendelim(r.empty_child.length); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.child_order.length != 0) { return false; } if (r.child_size != 0) { return false; } if (r.min_prefix_length != 0) { return false; } if (r.max_prefix_length != 0) { return false; } if (r.empty_child.length != 0) { return false; } if (uint(r.hash) != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.child_order = input.child_order; output.child_size = input.child_size; output.min_prefix_length = input.min_prefix_length; output.max_prefix_length = input.max_prefix_length; output.empty_child = input.empty_child; output.hash = input.hash; } //array helpers for ChildOrder /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addChildOrder(Data memory self, int32 value) internal pure { /** * First resize the array. Then add the new element to the end. */ int32[] memory tmp = new int32[](self.child_order.length + 1); for (uint256 i = 0; i < self.child_order.length; i++) { tmp[i] = self.child_order[i]; } tmp[self.child_order.length] = value; self.child_order = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library InnerSpec library BatchProof { //struct definition struct Data { BatchEntry.Data[] entries; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[2] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.entries = new BatchEntry.Data[](counters[1]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_entries( uint256 p, bytes memory bs, Data memory r, uint[2] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BatchEntry.Data memory x, uint256 sz) = _decode_BatchEntry(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.entries[r.entries.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BatchEntry(uint256 p, bytes memory bs) internal pure returns (BatchEntry.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BatchEntry.Data memory r, ) = BatchEntry._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.entries.length != 0) { for(i = 0; i < r.entries.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += BatchEntry._encode_nested(r.entries[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.entries.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(BatchEntry._estimate(r.entries[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.entries.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { for(uint256 i1 = 0; i1 < input.entries.length; i1++) { output.entries.push(input.entries[i1]); } } //array helpers for Entries /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addEntries(Data memory self, BatchEntry.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ BatchEntry.Data[] memory tmp = new BatchEntry.Data[](self.entries.length + 1); for (uint256 i = 0; i < self.entries.length; i++) { tmp[i] = self.entries[i]; } tmp[self.entries.length] = value; self.entries = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BatchProof library BatchEntry { //struct definition struct Data { ExistenceProof.Data exist; NonExistenceProof.Data nonexist; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_NonExistenceProof(uint256 p, bytes memory bs) internal pure returns (NonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { ExistenceProof.store(input.exist, output.exist); NonExistenceProof.store(input.nonexist, output.nonexist); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BatchEntry library CompressedBatchProof { //struct definition struct Data { CompressedBatchEntry.Data[] entries; InnerOp.Data[] lookup_inners; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.entries = new CompressedBatchEntry.Data[](counters[1]); r.lookup_inners = new InnerOp.Data[](counters[2]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_entries( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedBatchEntry.Data memory x, uint256 sz) = _decode_CompressedBatchEntry(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.entries[r.entries.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_lookup_inners( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.lookup_inners[r.lookup_inners.length - counters[2]] = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedBatchEntry(uint256 p, bytes memory bs) internal pure returns (CompressedBatchEntry.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedBatchEntry.Data memory r, ) = CompressedBatchEntry._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerOp(uint256 p, bytes memory bs) internal pure returns (InnerOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.entries.length != 0) { for(i = 0; i < r.entries.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += CompressedBatchEntry._encode_nested(r.entries[i], pointer, bs); } } if (r.lookup_inners.length != 0) { for(i = 0; i < r.lookup_inners.length; i++) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += InnerOp._encode_nested(r.lookup_inners[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.entries.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchEntry._estimate(r.entries[i])); } for(i = 0; i < r.lookup_inners.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.lookup_inners[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.entries.length != 0) { return false; } if (r.lookup_inners.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { for(uint256 i1 = 0; i1 < input.entries.length; i1++) { output.entries.push(input.entries[i1]); } for(uint256 i2 = 0; i2 < input.lookup_inners.length; i2++) { output.lookup_inners.push(input.lookup_inners[i2]); } } //array helpers for Entries /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addEntries(Data memory self, CompressedBatchEntry.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ CompressedBatchEntry.Data[] memory tmp = new CompressedBatchEntry.Data[](self.entries.length + 1); for (uint256 i = 0; i < self.entries.length; i++) { tmp[i] = self.entries[i]; } tmp[self.entries.length] = value; self.entries = tmp; } //array helpers for LookupInners /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addLookupInners(Data memory self, InnerOp.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ InnerOp.Data[] memory tmp = new InnerOp.Data[](self.lookup_inners.length + 1); for (uint256 i = 0; i < self.lookup_inners.length; i++) { tmp[i] = self.lookup_inners[i]; } tmp[self.lookup_inners.length] = value; self.lookup_inners = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedBatchProof library CompressedBatchEntry { //struct definition struct Data { CompressedExistenceProof.Data exist; CompressedNonExistenceProof.Data nonexist; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedNonExistenceProof.Data memory x, uint256 sz) = _decode_CompressedNonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedNonExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedNonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedNonExistenceProof.Data memory r, ) = CompressedNonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedNonExistenceProof._encode_nested(r.nonexist, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedNonExistenceProof._estimate(r.nonexist)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { CompressedExistenceProof.store(input.exist, output.exist); CompressedNonExistenceProof.store(input.nonexist, output.nonexist); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedBatchEntry library CompressedExistenceProof { //struct definition struct Data { bytes key; bytes value; LeafOp.Data leaf; int32[] path; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.path = new int32[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.value = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.leaf = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_path( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.path[r.path.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf, pointer, bs); if (r.path.length != 0) { for(i = 0; i < r.path.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs) ; pointer += ProtoBufRuntime._encode_int32(r.path[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf)); for(i = 0; i < r.path.length; i++) { e += 1 + ProtoBufRuntime._sz_int32(r.path[i]); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } if (r.value.length != 0) { return false; } if (r.path.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; output.value = input.value; LeafOp.store(input.leaf, output.leaf); output.path = input.path; } //array helpers for Path /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addPath(Data memory self, int32 value) internal pure { /** * First resize the array. Then add the new element to the end. */ int32[] memory tmp = new int32[](self.path.length + 1); for (uint256 i = 0; i < self.path.length; i++) { tmp[i] = self.path[i]; } tmp[self.path.length] = value; self.path = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedExistenceProof library CompressedNonExistenceProof { //struct definition struct Data { bytes key; CompressedExistenceProof.Data left; CompressedExistenceProof.Data right; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_left(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_right(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_left( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.left = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_right( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.right = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.left, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.right, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.left)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.right)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; CompressedExistenceProof.store(input.left, output.left); CompressedExistenceProof.store(input.right, output.right); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedNonExistenceProof library PROOFS_PROTO_GLOBAL_ENUMS { //enum definition // Solidity enum definitions enum HashOp { NO_HASH, SHA256, SHA512, KECCAK, RIPEMD160, BITCOIN } // Solidity enum encoder function encode_HashOp(HashOp x) internal pure returns (int32) { if (x == HashOp.NO_HASH) { return 0; } if (x == HashOp.SHA256) { return 1; } if (x == HashOp.SHA512) { return 2; } if (x == HashOp.KECCAK) { return 3; } if (x == HashOp.RIPEMD160) { return 4; } if (x == HashOp.BITCOIN) { return 5; } revert(); } // Solidity enum decoder function decode_HashOp(int64 x) internal pure returns (HashOp) { if (x == 0) { return HashOp.NO_HASH; } if (x == 1) { return HashOp.SHA256; } if (x == 2) { return HashOp.SHA512; } if (x == 3) { return HashOp.KECCAK; } if (x == 4) { return HashOp.RIPEMD160; } if (x == 5) { return HashOp.BITCOIN; } revert(); } // Solidity enum definitions enum LengthOp { NO_PREFIX, VAR_PROTO, VAR_RLP, FIXED32_BIG, FIXED32_LITTLE, FIXED64_BIG, FIXED64_LITTLE, REQUIRE_32_BYTES, REQUIRE_64_BYTES } // Solidity enum encoder function encode_LengthOp(LengthOp x) internal pure returns (int32) { if (x == LengthOp.NO_PREFIX) { return 0; } if (x == LengthOp.VAR_PROTO) { return 1; } if (x == LengthOp.VAR_RLP) { return 2; } if (x == LengthOp.FIXED32_BIG) { return 3; } if (x == LengthOp.FIXED32_LITTLE) { return 4; } if (x == LengthOp.FIXED64_BIG) { return 5; } if (x == LengthOp.FIXED64_LITTLE) { return 6; } if (x == LengthOp.REQUIRE_32_BYTES) { return 7; } if (x == LengthOp.REQUIRE_64_BYTES) { return 8; } revert(); } // Solidity enum decoder function decode_LengthOp(int64 x) internal pure returns (LengthOp) { if (x == 0) { return LengthOp.NO_PREFIX; } if (x == 1) { return LengthOp.VAR_PROTO; } if (x == 2) { return LengthOp.VAR_RLP; } if (x == 3) { return LengthOp.FIXED32_BIG; } if (x == 4) { return LengthOp.FIXED32_LITTLE; } if (x == 5) { return LengthOp.FIXED64_BIG; } if (x == 6) { return LengthOp.FIXED64_LITTLE; } if (x == 7) { return LengthOp.REQUIRE_32_BYTES; } if (x == 8) { return LengthOp.REQUIRE_64_BYTES; } revert(); } } //library PROOFS_PROTO_GLOBAL_ENUMS
The decoder for internal usage p The offset of bytes array to start decode bs The bytes array to be decoded sz The number of bytes expected return The decoded struct return The number of bytes decoded/
function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.entries = new CompressedBatchEntry.Data[](counters[1]); r.lookup_inners = new InnerOp.Data[](counters[2]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); }
13,050,497
/** *Submitted for verification at Etherscan.io on 2020-08-05 */ /** *Submitted for verification at Etherscan.io on 2020-08-04 */ pragma solidity ^0.5.16; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); 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, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c ; //inject UNINIT LOCAL/STATE VAR require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c ; //inject UNINIT LOCAL/STATE VAR return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c ; //inject UNINIT LOCAL/STATE VAR require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c ; //inject UNINIT LOCAL/STATE VAR return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash ; //inject UNINIT LOCAL/STATE VAR // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { 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 ; //inject UNINIT LOCAL/STATE VAR callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance ; //inject UNINIT LOCAL/STATE VAR callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } interface Controller { function withdraw(address, uint) external; function balanceOf(address) external view returns (uint); function earn(address, uint) external; function want(address) external view returns (address); } interface Aave { function borrow(address _reserve, uint _amount, uint _interestRateModel, uint16 _referralCode) external; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external; function repay(address _reserve, uint _amount, address payable _onBehalfOf) external payable; function getUserAccountData(address _user) external view returns ( uint totalLiquidityETH, uint totalCollateralETH, uint totalBorrowsETH, uint totalFeesETH, uint availableBorrowsETH, uint currentLiquidationThreshold, uint ltv, uint healthFactor ); function getUserReserveData(address _reserve, address _user) external view returns ( uint currentATokenBalance, uint currentBorrowBalance, uint principalBorrowBalance, uint borrowRateMode, uint borrowRate, uint liquidityRate, uint originationFee, uint variableBorrowIndex, uint lastUpdateTimestamp, bool usageAsCollateralEnabled ); } interface AaveToken { function underlyingAssetAddress() external view returns (address); } interface Oracle { function getAssetPrice(address reserve) external view returns (uint); function latestAnswer() external view returns (uint); } interface LendingPoolAddressesProvider { function getLendingPool() external view returns (address); function getLendingPoolCore() external view returns (address); function getPriceOracle() external view returns (address); } contract yDelegatedVault is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; address public governance; address public controller; uint public insurance; uint public healthFactor ; //inject UNINIT LOCAL/STATE VAR uint public ltv ; //inject UNINIT LOCAL/STATE VAR uint public max ; //inject UNINIT LOCAL/STATE VAR address public constant aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor (address _token, address _controller) public ERC20Detailed( string(abi.encodePacked("yearn ", ERC20Detailed(_token).name())), string(abi.encodePacked("y", ERC20Detailed(_token).symbol())), ERC20Detailed(_token).decimals() ) { token = IERC20(_token); governance = msg.sender; controller = _controller; } function debt() public view returns (uint) { address _reserve ; //inject UNINIT LOCAL/STATE VAR (,uint currentBorrowBalance,,,,,,,,) = Aave(getAave()).getUserReserveData(_reserve, address(this)); return currentBorrowBalance; } function credit() public view returns (uint) { return Controller(controller).balanceOf(address(this)); } // % of tokens locked and cannot be withdrawn per user // this is impermanent locked, unless the debt out accrues the strategy function locked() public view returns (uint) { return credit().mul(1e18).div(debt()); } function debtShare(address _lp) public view returns (uint) { return debt().mul(balanceOf(_lp)).mul(totalSupply()); } function getAave() public view returns (address) { return LendingPoolAddressesProvider(aave).getLendingPool(); } function getAaveCore() public view returns (address) { return LendingPoolAddressesProvider(aave).getLendingPoolCore(); } function setHealthFactor(uint _hf) external { require(msg.sender == governance, "!governance"); healthFactor = _hf; } function activate() public { Aave(getAave()).setUserUseReserveAsCollateral(underlying(), true); } function repay(address reserve, uint amount) public { // Required for certain stable coins (USDT for example) IERC20(reserve).approve(address(getAaveCore()), 0); IERC20(reserve).approve(address(getAaveCore()), amount); Aave(getAave()).repay(reserve, amount, address(uint160(address(this)))); } function repayAll() public { address _reserve ; //inject UNINIT LOCAL/STATE VAR uint _amount ; //inject UNINIT LOCAL/STATE VAR repay(_reserve, _amount); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // Ignore insurance fund for balance calculations function balance() public view returns (uint) { return token.balanceOf(address(this)).sub(insurance); } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } function getAaveOracle() public view returns (address) { return LendingPoolAddressesProvider(aave).getPriceOracle(); } function getReservePriceETH(address reserve) public view returns (uint) { return Oracle(getAaveOracle()).getAssetPrice(reserve); } function shouldRebalance() external view returns (bool) { return (over() > 0); } function over() public view returns (uint) { over(0); } function getUnderlyingPriceETH(uint _amount) public view returns (uint) { _amount = _amount.mul(getUnderlyingPrice()).div(uint(10)**ERC20Detailed(address(token)).decimals()); // Calculate the amount we are withdrawing in ETH return _amount.mul(ltv).div(max).div(healthFactor); } function over(uint _amount) public view returns (uint) { address _reserve ; //inject UNINIT LOCAL/STATE VAR uint _eth ; //inject UNINIT LOCAL/STATE VAR (uint _maxSafeETH,uint _totalBorrowsETH,) = maxSafeETH(); _maxSafeETH = _maxSafeETH.mul(105).div(100); // 5% buffer so we don't go into a earn/rebalance loop if (_eth > _maxSafeETH) { _maxSafeETH = 0; } else { _maxSafeETH = _maxSafeETH.sub(_eth); // Add the ETH we are withdrawing } if (_maxSafeETH < _totalBorrowsETH) { uint _over ; //inject UNINIT LOCAL/STATE VAR _over = _over.mul(uint(10)**ERC20Detailed(_reserve).decimals()).div(getReservePrice()); return _over; } else { return 0; } } function _rebalance(uint _amount) internal { uint _over ; //inject UNINIT LOCAL/STATE VAR if (_over > 0) { if (_over > credit()) { _over = credit(); } if (_over > 0) { Controller(controller).withdraw(address(this), _over); repayAll(); } } } function rebalance() external { _rebalance(0); } function claimInsurance() external { require(msg.sender == controller, "!controller"); token.safeTransfer(controller, insurance); insurance = 0; } function maxSafeETH() public view returns (uint maxBorrowsETH, uint totalBorrowsETH, uint availableBorrowsETH) { (,,uint _totalBorrowsETH,,uint _availableBorrowsETH,,,) = Aave(getAave()).getUserAccountData(address(this)); uint _maxBorrowETH ; //inject UNINIT LOCAL/STATE VAR return (_maxBorrowETH.div(healthFactor), _totalBorrowsETH, _availableBorrowsETH); } function shouldBorrow() external view returns (bool) { return (availableToBorrowReserve() > 0); } function availableToBorrowETH() public view returns (uint) { (uint _maxSafeETH,uint _totalBorrowsETH, uint _availableBorrowsETH) = maxSafeETH(); _maxSafeETH = _maxSafeETH.mul(95).div(100); // 5% buffer so we don't go into a earn/rebalance loop if (_maxSafeETH > _totalBorrowsETH) { return _availableBorrowsETH.mul(_maxSafeETH.sub(_totalBorrowsETH)).div(_availableBorrowsETH); } else { return 0; } } function availableToBorrowReserve() public view returns (uint) { address _reserve ; //inject UNINIT LOCAL/STATE VAR uint _available ; //inject UNINIT LOCAL/STATE VAR if (_available > 0) { return _available.mul(uint(10)**ERC20Detailed(_reserve).decimals()).div(getReservePrice()); } else { return 0; } } function getReservePrice() public view returns (uint) { return getReservePriceETH(reserve()); } function getUnderlyingPrice() public view returns (uint) { return getReservePriceETH(underlying()); } function earn() external { address _reserve ; //inject UNINIT LOCAL/STATE VAR uint _borrow ; //inject UNINIT LOCAL/STATE VAR if (_borrow > 0) { Aave(getAave()).borrow(_reserve, _borrow, 2, 7); } //rebalance here uint _balance ; //inject UNINIT LOCAL/STATE VAR if (_balance > 0) { IERC20(_reserve).safeTransfer(controller, _balance); Controller(controller).earn(address(this), _balance); } } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint _amount) public { uint _pool ; //inject UNINIT LOCAL/STATE VAR token.safeTransferFrom(msg.sender, address(this), _amount); // 0.5% of deposits go into an insurance fund incase of negative profits to protect withdrawals // At a 4 health factor, this is a -2% position uint _insurance ; //inject UNINIT LOCAL/STATE VAR _amount = _amount.sub(_insurance); insurance = insurance.add(_insurance); //Controller can claim insurance to liquidate to cover interest uint shares ; //inject UNINIT LOCAL/STATE VAR if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function reserve() public view returns (address) { return Controller(controller).want(address(this)); } function underlying() public view returns (address) { return AaveToken(address(token)).underlyingAssetAddress(); } function withdrawAll() public { withdraw(balanceOf(msg.sender)); } // Calculates in impermanent lock due to debt function maxWithdrawal(address account) public view returns (uint) { uint _balance ; //inject UNINIT LOCAL/STATE VAR uint _safeWithdraw ; //inject UNINIT LOCAL/STATE VAR if (_safeWithdraw > _balance) { return _balance; } else { uint _diff ; //inject UNINIT LOCAL/STATE VAR return _balance.sub(_diff.mul(healthFactor)); // technically 150%, not 200%, but adding buffer } } function safeWithdraw() external { withdraw(maxWithdrawal(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint _shares) public { uint r ; //inject UNINIT LOCAL/STATE VAR _burn(msg.sender, _shares); _rebalance(r); token.safeTransfer(msg.sender, r); } function getPricePerFullShare() external view returns (uint) { return balance().mul(1e18).div(totalSupply()); } }
solhint-disable-next-line no-inline-assembly
function isContract(address account) internal view returns (bool) { bytes32 codehash; return (codehash != 0x0 && codehash != accountHash); }
12,682,076
pragma solidity ^0.4.24; /** @title Marketplace */ contract Marketplace { struct Product { string name; uint256 price; uint64 quantity; uint256 _index; } struct Store { mapping (uint256 => Product) products; uint256[] productIndices; uint256 productIdentifier; string name; address owner; uint256 funds; } mapping (address => bool) admins; mapping (address => bool) storeOwners; Store[] stores; mapping (address => uint256[]) storeIndices; address owner; bool stopped; /** @dev Deposit funds event. * @param who The address who deposited. * @param storeId The store in which the deposit was made. * @param value How much was deposited. */ event DepositFunds(address indexed who, uint256 indexed storeId, uint256 value); /** @dev Withdraw funds event. * @param who The address who withdrew. * @param storeId The store in which the withdrawal was made. * @param value How much was withdrawn. */ event WithdrawFunds(address indexed who, uint256 indexed storeId, uint256 value); /** @dev Emitted when a product is added to a store. * @param who The address who added the product. * @param storeId The store in which the product was added. * @param productIndex The index of the product in the store storage. * @param name Product name. * @param price Product price. * @param quantity Product quantity. */ event AddProduct(address indexed who, uint256 indexed storeId, uint256 productIndex, string name, uint256 price, uint64 quantity); /** @dev Emitted when a product is removed from a store. * @param who The address who removed the product. * @param storeId The store in which the product was removed. * @param productIndex The index of the product in the store storage. */ event RemoveProduct(address indexed who, uint256 indexed storeId, uint256 productIndex); /** @dev Emitted when a product is updated in a store. * @param who The address who updated the product. * @param storeId The store in which the product was updated. * @param productIndex The index of the product in the store storage. * @param name New product name. * @param price New product price. * @param quantity New product quantity. */ event UpdateProduct(address indexed who, uint256 indexed storeId, uint256 productIndex, string name, uint256 price, uint64 quantity); /** @dev Emitted when a store is created. * @param who The address who created the store. * @param storeId The id of the newly created store. * @param name The name of the newly created store. * @param funds The initial funds of the newly created store. */ event AddStore(address indexed who, uint256 storeId, string name, uint256 funds); /** @dev Emitted when a product is purchased from a store. * @param who The address who made the purchase. * @param storeId The id of the store where the purchase was made. * @param productIndex The id of the product that was purchased. */ event Purchase(address indexed who, uint256 indexed storeId, uint256 productIndex); /** @dev Halts execution if contract is stopped. */ modifier stopInEmergency { require(!isInEmergency()); _; } /** @dev Halts execution if user is not admin. */ modifier isAdmin() { require(isUserAdmin()); _; } /** @dev Halts execution if user is not store owner. */ modifier isStoreOwner() { require(isUserStoreOwner()); _; } /** @dev Halts execution if msg.sender does not own store with id == 'id'. */ modifier ownsStore(uint256 id) { require(userOwnsStore(id)); _; } constructor() public { owner = msg.sender; admins[msg.sender] = true; stopped = false; storeOwners[msg.sender] = true; } /** @dev Checks if sender owns the store with given id. */ function userOwnsStore(uint256 id) public view isStoreOwner returns(bool) { return stores[id].owner == msg.sender; } /** @dev Checks if contract is stopped. */ function isInEmergency() public view returns(bool) { return stopped; } /** @dev Stops contract. */ function stopContract() public isAdmin { stopped = true; } /** @dev Resumes contract. */ function resumeContract() public isAdmin { stopped = false; } /** @dev Checks if sender is admin. */ function isUserAdmin() public view returns(bool) { return admins[msg.sender]; } /** @dev Checks if sender is store owner. */ function isUserStoreOwner() public view returns(bool) { return storeOwners[msg.sender]; } /** @dev Admin-only function that gives admin privileges. * @param candidate The new admin. */ function makeAdmin(address candidate) public isAdmin { admins[candidate] = true; } /** @dev Admin-only function that gives store owner privileges. * @param candidate The new store owner. */ function makeStoreOwner(address candidate) public isAdmin { storeOwners[candidate] = true; } /** @dev Returns the number of stores. */ function getNumberOfStores() public view returns(uint256) { return stores.length; } /** @dev Get store by id. * @param id Id of store. */ function getStore(uint256 id) public view returns(string, address, uint256) { Store storage s = stores[id]; return (s.name, s.owner, s.funds); } /** @dev Adds new store. * @param name The name of the newly added store. */ function addStore(string name) public isStoreOwner stopInEmergency returns(uint256) { stores.push(Store({ productIndices: new uint256[](0), name: name, funds: 0, owner: msg.sender, productIdentifier: 0 })); storeIndices[msg.sender].push(stores.length-1); emit AddStore(msg.sender, stores.length-1, name, 0); return stores.length-1; } /** @dev Add a new product to a store. * @param storeId The store in which the product will be added. * @param name The name of the product. * @param price The price of the product. * @param quantity The quantity of the product. */ function addProduct(uint256 storeId, string name, uint256 price, uint64 quantity) public isStoreOwner ownsStore(storeId) stopInEmergency returns(uint256) { Store storage store = stores[storeId]; uint256 productId = store.productIdentifier; store.productIdentifier++; store.products[productId] = Product({ name: name, price: price, quantity: quantity, _index: productId }); store.productIndices.push(productId); emit AddProduct(msg.sender, storeId, productId, name, price, quantity); return productId; } /** @dev Update existing product in store. * @param storeId The store in which the product will be updated. * @param productIndex The index of the product in store storage. * @param name The new name of the product. * @param price The new price of the product. * @param quantity The new quantity of the product. */ function updateProduct(uint256 storeId, uint256 productIndex, string name, uint256 price, uint64 quantity) public isStoreOwner ownsStore(storeId) stopInEmergency returns(bool) { uint256 index = stores[storeId].productIndices[productIndex]; Product storage product = stores[storeId].products[index]; product.name = name; product.price = price; product.quantity = quantity; emit UpdateProduct(msg.sender, storeId, productIndex, name, price, quantity); return true; } /** @dev Get the available funds in a store. * @param storeId The id of the store in which the funds will be checked. */ function getFunds(uint256 storeId) public view isStoreOwner ownsStore(storeId) returns(uint256) { return stores[storeId].funds; } /** @dev Deposits funds to a store. * @param storeId The id of the store in which the funds will be deposited. */ function depositFunds(uint256 storeId) public payable isStoreOwner ownsStore(storeId) stopInEmergency returns(bool) { require(stores[storeId].funds + msg.value >= stores[storeId].funds); stores[storeId].funds += msg.value; emit DepositFunds(msg.sender, storeId, msg.value); return true; } /** @dev Withdraws funds from a store. * @param storeId The id of the store from which the funds will be withdrawn. */ function withdrawFunds(uint256 storeId, uint256 amount) public payable isStoreOwner ownsStore(storeId) stopInEmergency returns(bool) { require(stores[storeId].funds >= amount && stores[storeId].funds - amount <= stores[storeId].funds); stores[storeId].funds -= amount; msg.sender.transfer(amount); emit WithdrawFunds(msg.sender, storeId, amount); return true; } /** @dev Gets the number of products in a store. * @param storeId The id of the store from which the number of unique products will be calculated (not including quantity). */ function getProductCount(uint256 storeId) public view returns(uint256) { return stores[storeId].productIndices.length; } /** @dev Purchases a product from a store. * @param storeId The id of the store from which the product will be purchased. * @param productId The id of the the product that will be purchased. */ function purchase(uint256 storeId, uint256 productId) public payable stopInEmergency returns(string) { uint256 index = stores[storeId].productIndices[productId]; Product storage product = stores[storeId].products[index]; require(msg.value == product.price); require(product.quantity > 0); product.quantity--; stores[storeId].funds += msg.value; emit Purchase(msg.sender, storeId, productId); return product.name; } /** @dev Get details for a product. * @param storeId The id of the store in which the product is present. * @param productIndex The id of the the product in the store storage. */ function getProduct(uint256 storeId, uint256 productIndex) public view returns(string, uint256, uint64) { uint256 index = stores[storeId].productIndices[productIndex]; Product storage product = stores[storeId].products[index]; return (product.name, product.price, product.quantity); } /** @dev Deletes a product from the store storage. * @param storeId The id of the store from which the product will be deleted. * @param productIndex The id of the the product in the store storage. */ function deleteProduct(uint256 storeId, uint256 productIndex) public isStoreOwner ownsStore(storeId) stopInEmergency returns(bool) { Store storage store = stores[storeId]; require(store.productIndices.length > 0); // prevents underflow uint256 last = store.productIndices[store.productIndices.length-1]; store.productIndices[store.productIndices.length-1] = store.productIndices[productIndex]; store.productIndices[productIndex] = last; delete store.products[store.productIndices[store.productIndices.length-1]]; delete store.productIndices[store.productIndices.length-1]; store.productIndices.length--; emit RemoveProduct(msg.sender, storeId, productIndex); return true; } }
Get details for a product. storeId The id of the store in which the product is present. productIndex The id of the the product in the store storage./
function getProduct(uint256 storeId, uint256 productIndex) public view returns(string, uint256, uint64) { uint256 index = stores[storeId].productIndices[productIndex]; Product storage product = stores[storeId].products[index]; return (product.name, product.price, product.quantity); }
2,537,780
./full_match/1/0x12D02cf6aa7BDaD802777e9D55Ce6cD901215B8c/sources/localhost/contracts/UniswapOTC.sol
Fund contract and set limit price (in the form of min purchased tokens). Excess value is refunded to sender in the case of a re-balancing./Increment client balance
function setLimitOrder(uint256 _tokenAmount, uint256 _etherAmount) public payable { require(_etherAmount >= minEthLimit, "Insufficient ETH volume"); require((_tokenAmount / _etherAmount) <= maxTokenPerEth, "Excessive token per ETH"); require(_etherAmount == clientEthBalances[msg.sender] + msg.value, "Balance must equal purchase eth amount."); clientEthBalances[msg.sender] += msg.value; clientMinTokens[msg.sender] = _tokenAmount; }
16,509,885
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; import "./OraclesManager.sol"; import "../interfaces/ISignatureVerifier.sol"; import "../libraries/SignatureUtil.sol"; /// @dev It's used to verify that a transfer is signed by oracles. contract SignatureVerifier is OraclesManager, ISignatureVerifier { using SignatureUtil for bytes; using SignatureUtil for bytes32; /* ========== STATE VARIABLES ========== */ /// @dev Number of required confirmations per block after the extra check is enabled uint8 public confirmationThreshold; /// @dev submissions count in current block uint40 public submissionsInBlock; /// @dev Current block uint40 public currentBlock; /// @dev Debridge gate address address public debridgeAddress; /* ========== ERRORS ========== */ error DeBridgeGateBadRole(); error NotConfirmedByRequiredOracles(); error NotConfirmedThreshold(); error SubmissionNotConfirmed(); error DuplicateSignatures(); /* ========== MODIFIERS ========== */ modifier onlyDeBridgeGate() { if (msg.sender != debridgeAddress) revert DeBridgeGateBadRole(); _; } /* ========== CONSTRUCTOR ========== */ /// @dev Constructor that initializes the most important configurations. /// @param _minConfirmations Common confirmations count. /// @param _confirmationThreshold Confirmations per block after the extra check is enabled. /// @param _excessConfirmations Confirmations count in case of excess activity. function initialize( uint8 _minConfirmations, uint8 _confirmationThreshold, uint8 _excessConfirmations, address _debridgeAddress ) public initializer { OraclesManager.initialize(_minConfirmations, _excessConfirmations); confirmationThreshold = _confirmationThreshold; debridgeAddress = _debridgeAddress; } /// @inheritdoc ISignatureVerifier function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external override onlyDeBridgeGate { //Need confirmation to confirm submission uint8 needConfirmations = _excessConfirmations > minConfirmations ? _excessConfirmations : minConfirmations; // Count of required(DSRM) oracles confirmation uint256 currentRequiredOraclesCount; // stack variable to aggregate confirmations and write to storage once uint8 confirmations; uint256 signaturesCount = _countSignatures(_signatures); address[] memory validators = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { (bytes32 r, bytes32 s, uint8 v) = _signatures.parseSignature(i * 65); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); if (getOracleInfo[oracle].isValid) { for (uint256 k = 0; k < i; k++) { if (validators[k] == oracle) revert DuplicateSignatures(); } validators[i] = oracle; confirmations += 1; emit Confirmed(_submissionId, oracle); if (getOracleInfo[oracle].required) { currentRequiredOraclesCount += 1; } if ( confirmations >= needConfirmations && currentRequiredOraclesCount >= requiredOraclesCount ) { break; } } } if (currentRequiredOraclesCount != requiredOraclesCount) revert NotConfirmedByRequiredOracles(); if (confirmations >= minConfirmations) { if (currentBlock == uint40(block.number)) { submissionsInBlock += 1; } else { currentBlock = uint40(block.number); submissionsInBlock = 1; } emit SubmissionApproved(_submissionId); } if (submissionsInBlock > confirmationThreshold) { if (confirmations < excessConfirmations) revert NotConfirmedThreshold(); } if (confirmations < needConfirmations) revert SubmissionNotConfirmed(); } /* ========== ADMIN ========== */ /// @dev Sets minimal required confirmations. /// @param _confirmationThreshold Confirmation info. function setThreshold(uint8 _confirmationThreshold) external onlyAdmin { if (_confirmationThreshold == 0) revert WrongArgument(); confirmationThreshold = _confirmationThreshold; } /// @dev Sets core debridge conrtact address. /// @param _debridgeAddress Debridge address. function setDebridgeAddress(address _debridgeAddress) external onlyAdmin { debridgeAddress = _debridgeAddress; } /* ========== VIEW ========== */ /// @dev Check is valid signature /// @param _submissionId Submission identifier. /// @param _signature signature by oracle. function isValidSignature(bytes32 _submissionId, bytes memory _signature) external view returns (bool) { (bytes32 r, bytes32 s, uint8 v) = _signature.splitSignature(); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); return getOracleInfo[oracle].isValid; } /* ========== INTERNAL ========== */ function _countSignatures(bytes memory _signatures) internal pure returns (uint256) { return _signatures.length % 65 == 0 ? _signatures.length / 65 : 0; } // ============ Version Control ============ /// @dev Get this contract's version function version() external pure returns (uint256) { return 201; // 2.0.1 } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "../interfaces/IOraclesManager.sol"; /// @dev The base contract for oracles management. Allows adding/removing oracles, /// managing the minimal required amount of confirmations. contract OraclesManager is Initializable, AccessControlUpgradeable, IOraclesManager { /* ========== STATE VARIABLES ========== */ /// @dev Minimal required confirmations uint8 public minConfirmations; /// @dev Minimal required confirmations in case of too many confirmations uint8 public excessConfirmations; /// @dev Count of required oracles uint8 public requiredOraclesCount; /// @dev Oracle addresses address[] public oracleAddresses; /// @dev Maps an oracle address to the oracle details mapping(address => OracleInfo) public getOracleInfo; /* ========== ERRORS ========== */ error AdminBadRole(); error OracleBadRole(); error OracleAlreadyExist(); error OracleNotFound(); error WrongArgument(); error LowMinConfirmations(); /* ========== MODIFIERS ========== */ modifier onlyAdmin() { if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert AdminBadRole(); _; } modifier onlyOracle() { if (!getOracleInfo[msg.sender].isValid) revert OracleBadRole(); _; } /* ========== CONSTRUCTOR ========== */ /// @dev Constructor that initializes the most important configurations. /// @param _minConfirmations Minimal required confirmations. /// @param _excessConfirmations Minimal required confirmations in case of too many confirmations. function initialize(uint8 _minConfirmations, uint8 _excessConfirmations) internal { if (_minConfirmations == 0 || _excessConfirmations < _minConfirmations) revert LowMinConfirmations(); minConfirmations = _minConfirmations; excessConfirmations = _excessConfirmations; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /* ========== ADMIN ========== */ /// @dev Sets minimal required confirmations. /// @param _minConfirmations Minimal required confirmations. function setMinConfirmations(uint8 _minConfirmations) external onlyAdmin { if (_minConfirmations < oracleAddresses.length / 2 + 1) revert LowMinConfirmations(); minConfirmations = _minConfirmations; } /// @dev Sets minimal required confirmations in case of too many confirmations. /// @param _excessConfirmations Minimal required confirmations in case of too many confirmations. function setExcessConfirmations(uint8 _excessConfirmations) external onlyAdmin { if (_excessConfirmations < minConfirmations) revert LowMinConfirmations(); excessConfirmations = _excessConfirmations; } /// @dev Add oracles. /// @param _oracles Oracles' addresses. /// @param _required A transfer will not be confirmed without oracles having required set to true, function addOracles( address[] memory _oracles, bool[] memory _required ) external onlyAdmin { if (_oracles.length != _required.length) revert WrongArgument(); if (minConfirmations < (oracleAddresses.length + _oracles.length) / 2 + 1) revert LowMinConfirmations(); for (uint256 i = 0; i < _oracles.length; i++) { OracleInfo storage oracleInfo = getOracleInfo[_oracles[i]]; if (oracleInfo.exist) revert OracleAlreadyExist(); oracleAddresses.push(_oracles[i]); if (_required[i]) { requiredOraclesCount += 1; } oracleInfo.exist = true; oracleInfo.isValid = true; oracleInfo.required = _required[i]; emit AddOracle(_oracles[i], _required[i]); } } /// @dev Update an oracle. /// @param _oracle An oracle address. /// @param _isValid Is this oracle valid, i.e. should it be treated as an oracle. /// @param _required If set to true a transfer will not be confirmed without this oracle. function updateOracle( address _oracle, bool _isValid, bool _required ) external onlyAdmin { //If oracle is invalid, it must be not required if (!_isValid && _required) revert WrongArgument(); OracleInfo storage oracleInfo = getOracleInfo[_oracle]; if (!oracleInfo.exist) revert OracleNotFound(); if (oracleInfo.required && !_required) { requiredOraclesCount -= 1; } else if (!oracleInfo.required && _required) { requiredOraclesCount += 1; } if (oracleInfo.isValid && !_isValid) { // remove oracle from oracleAddresses array without keeping an order for (uint256 i = 0; i < oracleAddresses.length; i++) { if (oracleAddresses[i] == _oracle) { oracleAddresses[i] = oracleAddresses[oracleAddresses.length - 1]; oracleAddresses.pop(); break; } } } else if (!oracleInfo.isValid && _isValid) { if (minConfirmations < (oracleAddresses.length + 1) / 2 + 1) revert LowMinConfirmations(); oracleAddresses.push(_oracle); } oracleInfo.isValid = _isValid; oracleInfo.required = _required; emit UpdateOracle(_oracle, _required, _isValid); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface ISignatureVerifier { /* ========== EVENTS ========== */ /// @dev Emitted once the submission is confirmed by one oracle. event Confirmed(bytes32 submissionId, address operator); /// @dev Emitted once the submission is confirmed by min required amount of oracles. event DeployConfirmed(bytes32 deployId, address operator); /* ========== FUNCTIONS ========== */ /// @dev Check confirmation (validate signatures) for the transfer request. /// @param _submissionId Submission identifier. /// @param _signatures Array of signatures by oracles. /// @param _excessConfirmations override min confirmations count function submit( bytes32 _submissionId, bytes memory _signatures, uint8 _excessConfirmations ) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.7; library SignatureUtil { /* ========== ERRORS ========== */ error WrongArgumentLength(); error SignatureInvalidLength(); error SignatureInvalidV(); /// @dev Prepares raw msg that was signed by the oracle. /// @param _submissionId Submission identifier. function getUnsignedMsg(bytes32 _submissionId) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _submissionId)); } /// @dev Splits signature bytes to r,s,v components. /// @param _signature Signature bytes in format r+s+v. function splitSignature(bytes memory _signature) internal pure returns ( bytes32 r, bytes32 s, uint8 v ) { if (_signature.length != 65) revert SignatureInvalidLength(); return parseSignature(_signature, 0); } function parseSignature(bytes memory _signatures, uint256 offset) internal pure returns ( bytes32 r, bytes32 s, uint8 v ) { assembly { r := mload(add(_signatures, add(32, offset))) s := mload(add(_signatures, add(64, offset))) v := and(mload(add(_signatures, add(65, offset))), 0xff) } if (v < 27) v += 27; if (v != 27 && v != 28) revert SignatureInvalidV(); } function toUint256(bytes memory _bytes, uint256 _offset) internal pure returns (uint256 result) { if (_bytes.length < _offset + 32) revert WrongArgumentLength(); assembly { result := mload(add(add(_bytes, 0x20), _offset)) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IOraclesManager { /* ========== STRUCTS ========== */ struct OracleInfo { bool exist; // exist oracle bool isValid; // is valid oracle bool required; // without this oracle (DSRM), the transfer will not be confirmed } /* ========== EVENTS ========== */ /// @dev Emitted when an oracle is added /// @param oracle Address of an added oracle /// @param required Is this oracle's signature required for every transfer event AddOracle(address oracle, bool required); /// @dev Emitted when an oracle is updated /// @param oracle Address of an updated oracle /// @param required Is this oracle's signature required for every transfer /// @param isValid Is this oracle valid, i.e. should it be treated as an oracle event UpdateOracle(address oracle, bool required, bool isValid); /// @dev Emitted once the submission is confirmed by min required amount of oracles event DeployApproved(bytes32 deployId); /// @dev Emitted once the submission is confirmed by min required amount of oracles event SubmissionApproved(bytes32 submissionId); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Check is valid signature _submissionId Submission identifier. _signature signature by oracle.
function isValidSignature(bytes32 _submissionId, bytes memory _signature) external view returns (bool) { (bytes32 r, bytes32 s, uint8 v) = _signature.splitSignature(); address oracle = ecrecover(_submissionId.getUnsignedMsg(), v, r, s); return getOracleInfo[oracle].isValid; }
1,698,409
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.6; import "@yield-protocol/utils-v2/contracts/interfaces/IWETH9.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; import "./UniswapImports.sol"; import "./YieldImports.sol"; contract FlashLiquidator is IUniswapV3FlashCallback, PeripheryImmutableState, PeripheryPayments { using TransferHelper for address; ISwapRouter public immutable swapRouter; IWitch public immutable witch; ICauldron public immutable cauldron; address public immutable recipient; struct FlashCallbackData { bytes12 vaultId; address base; address collateral; uint256 baseLoan; address baseJoin; PoolAddress.PoolKey poolKey; } constructor( address _recipient, ISwapRouter _swapRouter, address _factory, address _WETH9, IWitch _witch ) PeripheryImmutableState(_factory, _WETH9) { swapRouter = _swapRouter; witch = _witch; cauldron = _witch.cauldron(); recipient = _recipient; } function collateralToDebtRatio(bytes12 vaultId, bytes6 seriesId, bytes6 baseId, bytes6 ilkId, uint128 art) public returns (uint256) { if (art == 0) { return 0; } int256 level = cauldron.level(vaultId); uint128 accrued_debt = cauldron.debtToBase(seriesId, art); (, uint32 ratio_u32) = cauldron.spotOracles(baseId, ilkId); level = (level * 1e18 / int256(int128(accrued_debt))) + int256(uint256(ratio_u32)) * 1e12; require(level >= 0, "level is negative"); return uint256(level); } function isAtMinimalPrice(bytes12 vaultId, bytes6 ilkId) public returns (bool) { (, uint32 auction_start) = witch.auctions(vaultId); (, uint32 duration, , ) = witch.ilks(ilkId); uint256 elapsed = uint32(block.timestamp) - auction_start; return elapsed >= duration; } /// @param fee0 The fee from calling flash for token0 /// @param fee1 The fee from calling flash for token1 /// @param data The data needed in the callback passed as FlashCallbackData from `initFlash` /// @notice implements the callback called from flash function uniswapV3FlashCallback( uint256 fee0, uint256 fee1, bytes calldata data ) external override { // we only borrow 1 token require(fee0 == 0 || fee1 == 0, 'fee0 == 0 || fee1 == 0'); uint256 fee = fee0 + fee1; // decode and verify FlashCallbackData memory decoded = abi.decode(data, (FlashCallbackData)); CallbackValidation.verifyCallback(factory, decoded.poolKey); // liquidate the vault decoded.base.safeApprove(decoded.baseJoin, decoded.baseLoan); uint256 collateralReceived = witch.payAll(decoded.vaultId, 0); // sell the collateral uint256 debtToReturn = decoded.baseLoan + fee; decoded.collateral.safeApprove(address(swapRouter), collateralReceived); uint256 debtRecovered = swapRouter.exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: decoded.collateral, tokenOut: decoded.base, fee: 500, // can't use the same fee as the flash loan // because of reentrancy protection recipient: address(this), deadline: block.timestamp + 180, amountIn: collateralReceived, amountOutMinimum: debtToReturn, sqrtPriceLimitX96: 0 }) ); // if profitable pay profits to recipient if (debtRecovered > debtToReturn) { uint256 profit = debtRecovered - debtToReturn; decoded.base.safeApprove(address(this), profit); pay(decoded.base, address(this), recipient, profit); } // repay flash loan decoded.base.safeApprove(address(this), debtToReturn); // TODO: Does this do anything? pay(decoded.base, address(this), msg.sender, debtToReturn); } /// @param vaultId The vault to liquidate /// @notice Liquidates a vault with help from a Uniswap v3 flash loan function liquidate(bytes12 vaultId) external { uint24 poolFee = 3000; // 0.3% DataTypes.Vault memory vault = cauldron.vaults(vaultId); DataTypes.Balances memory balances = cauldron.balances(vaultId); DataTypes.Series memory series = cauldron.series(vault.seriesId); address base = cauldron.assets(series.baseId); address collateral = cauldron.assets(vault.ilkId); uint128 baseLoan = cauldron.debtToBase(vault.seriesId, uint128(balances.art)); // tokens in PoolKey must be ordered bool ordered = (collateral < base); PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({ token0: ordered ? collateral : base, token1: ordered ? base : collateral, fee: poolFee }); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey)); // data for the callback to know what to do FlashCallbackData memory args = FlashCallbackData({ vaultId: vaultId, base: base, collateral: collateral, baseLoan: baseLoan, baseJoin: address(witch.ladle().joins(series.baseId)), poolKey: poolKey }); // initiate flash loan, with the liquidation logic embedded in the flash loan callback pool.flash( address(this), ordered ? 0 : baseLoan, ordered ? baseLoan : 0, abi.encode( args ) ); } } // SPDX-License-Identifier: MIT import "../token/IERC20.sol"; pragma solidity ^0.8.0; interface IWETH9 is IERC20 { event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); function deposit() external payable; function withdraw(uint wad) external; } // 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: GPL-2.0-or-later pragma solidity >=0.8.6; import "@yield-protocol/utils-v2/contracts/interfaces/IWETH9.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; // File @uniswap/v3-core/contracts/interfaces/pool/[email protected] // /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // File @uniswap/v3-core/contracts/interfaces/pool/[email protected] // /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // File @uniswap/v3-core/contracts/interfaces/pool/[email protected] // /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // File @uniswap/v3-core/contracts/interfaces/pool/[email protected] // /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // File @uniswap/v3-core/contracts/interfaces/pool/[email protected] // /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // File @uniswap/v3-core/contracts/interfaces/pool/[email protected] // /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // File @uniswap/v3-core/contracts/interfaces/[email protected] // /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // File @uniswap/v3-core/contracts/interfaces/callback/[email protected] // /// @title Callback for IUniswapV3PoolActions#flash /// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface interface IUniswapV3FlashCallback { /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash. /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param fee0 The fee amount in token0 due to the pool by the end of the flash /// @param fee1 The fee amount in token1 due to the pool by the end of the flash /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call function uniswapV3FlashCallback( uint256 fee0, uint256 fee1, bytes calldata data ) external; } // File @uniswap/v3-periphery/contracts/interfaces/[email protected] // /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } // File @uniswap/v3-periphery/contracts/libraries/[email protected] // library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // File @uniswap/v3-periphery/contracts/interfaces/[email protected] // /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // File @uniswap/v3-periphery/contracts/base/[email protected] // /// @title Immutable state /// @notice Immutable state used by periphery contracts abstract contract PeripheryImmutableState is IPeripheryImmutableState { /// @inheritdoc IPeripheryImmutableState address public immutable override factory; /// @inheritdoc IPeripheryImmutableState address public immutable override WETH9; constructor(address _factory, address _WETH9) { factory = _factory; WETH9 = _WETH9; } } // File @uniswap/v3-periphery/contracts/base/[email protected] // abstract contract PeripheryPayments is IPeripheryPayments, PeripheryImmutableState { receive() external payable { require(msg.sender == WETH9, 'Not WETH9'); } /// @inheritdoc IPeripheryPayments function unwrapWETH9(uint256 amountMinimum, address recipient) external payable override { uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this)); require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9'); if (balanceWETH9 > 0) { IWETH9(WETH9).withdraw(balanceWETH9); TransferHelper.safeTransferETH(recipient, balanceWETH9); } } /// @inheritdoc IPeripheryPayments function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable override { uint256 balanceToken = IERC20(token).balanceOf(address(this)); require(balanceToken >= amountMinimum, 'Insufficient token'); if (balanceToken > 0) { TransferHelper.safeTransfer(token, recipient, balanceToken); } } /// @inheritdoc IPeripheryPayments function refundETH() external payable override { if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance); } /// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == WETH9 && address(this).balance >= value) { // pay with WETH9 IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay IWETH9(WETH9).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } } } // File @uniswap/v3-core/contracts/interfaces/callback/[email protected] // /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // File @uniswap/v3-periphery/contracts/interfaces/[email protected] // pragma abicoder v2; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // File contracts/liquidator/Flash.sol // pragma abicoder v2; /// from 'uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol'; /// @notice Provides validation for callbacks from Uniswap V3 Pools library CallbackValidation { /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The V3 pool contract address function verifyCallback( address factory, address tokenA, address tokenB, uint24 fee ) internal view returns (IUniswapV3Pool pool) { return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param poolKey The identifying key of the V3 pool /// @return pool The V3 pool contract address function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey) internal view returns (IUniswapV3Pool pool) { pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey)); require(msg.sender == address(pool)); } } /// from 'uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { 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: GPL-2.0-or-later pragma solidity >=0.8.6; import "@yield-protocol/utils-v2/contracts/interfaces/IWETH9.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; library DataTypes { struct Series { IFYToken fyToken; // Redeemable token for the series. bytes6 baseId; // Asset received on redemption. uint32 maturity; // Unix time at which redemption becomes possible. } struct Vault { address owner; bytes6 seriesId; // Each vault is related to only one series, which also determines the underlying. bytes6 ilkId; // Asset accepted as collateral } struct Balances { uint128 art; // Debt amount uint128 ink; // Collateral amount } } interface IJoin { } interface IFYToken { } interface ILadle { function joins(bytes6) external view returns (IJoin); } interface IWitch { function payAll(bytes12 vaultId, uint128 min) external returns (uint256 ink); function ladle() external returns (ILadle); function cauldron() external returns (ICauldron); function auctions(bytes12 vaultId) external returns (address owner, uint32 start); function ilks(bytes6 ilkId) external returns (bool initialized, uint32 duration, uint64 initialOffer, uint128 dust); } interface ICauldron { function vaults(bytes12 vault) external view returns (DataTypes.Vault memory); function series(bytes6 seriesId) external view returns (DataTypes.Series memory); function assets(bytes6 assetsId) external view returns (address); function balances(bytes12 vault) external view returns (DataTypes.Balances memory); function spotOracles(bytes6 baseId, bytes6 ilkId) external returns (address oracle, uint32 ratio); function level(bytes12 vaultId) external returns (int256); function debtToBase(bytes6 seriesId, uint128 art) external returns (uint128 base); }
Deterministically computes the pool address given the factory and PoolKey factory The Uniswap V3 factory contract address 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 ) ) )) ); }
635,719
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface IWeth { function deposit() external payable; function withdraw(uint256 wad) external; } contract IERC20 { string public name; uint8 public decimals; string public symbol; 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 approve(address _spender, uint256 _value) public returns (bool); function transfer(address _to, 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); } contract IWethERC20 is IWeth, IERC20 {} contract Constants { uint256 internal constant WEI_PRECISION = 10**18; uint256 internal constant WEI_PERCENT_PRECISION = 10**20; uint256 internal constant DAYS_IN_A_YEAR = 365; uint256 internal constant ONE_MONTH = 2628000; // approx. seconds in a month IWethERC20 public constant wethToken = IWethERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant bzrxTokenAddress = 0x56d811088235F11C8920698a204A5010a788f4b3; address public constant vbzrxTokenAddress = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; } /** * @dev Library for managing loan sets * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. * */ library EnumerableBytes32Set { struct Bytes32Set { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) index; bytes32[] values; } /** * @dev Add an address value to a set. O(1). * Returns false if the value was already in the set. */ function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return addBytes32(set, value); } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)){ set.index[value] = set.values.push(value); return true; } else { return false; } } /** * @dev Removes an address value from a set. O(1). * Returns false if the value was not present in the set. */ function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return removeBytes32(set, value); } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (lastIndex != toDeleteIndex) { bytes32 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns true if the value is in the set. O(1). */ function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool) { bytes32 value; assembly { value := addrvalue } return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(Bytes32Set storage set, uint256 start, uint256 count) internal view returns (bytes32[] memory output) { uint256 end = start + count; require(end >= start, "addition overflow"); end = set.values.length < end ? set.values.length : end; if (end == 0 || start >= end) { return output; } output = new bytes32[](end-start); for (uint256 i = start; i < end; i++) { output[i-start] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return set.values.length; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function get(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return set.values[index]; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function getAddress(Bytes32Set storage set, uint256 index) internal view returns (address) { bytes32 value = set.values[index]; address addrvalue; assembly { addrvalue := value } return addrvalue; } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <alexey@mixbytes.io> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs. /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056 uint256 internal constant REENTRANCY_GUARD_FREE = 1; /// @dev Constant for locked guard state uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; /** * @dev We use a single lock for the whole contract. */ uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "unauthorized"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @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; } } /** * @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 Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return divCeil(a, b, "SafeMath: division by zero"); } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); if (a == 0) { return 0; } uint256 c = ((a - 1) / b) + 1; 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; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address 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 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"); } } } contract LoanStruct { struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } } contract LoanParamsStruct { struct LoanParams { bytes32 id; // id of loan params object bool active; // if false, this object has been disabled by the owner and can't be used for future loans address owner; // owner of this object address loanToken; // the token being loaned address collateralToken; // the required collateral token uint256 minInitialMargin; // the minimum allowed initial margin uint256 maintenanceMargin; // an unhealthy loan when current margin is at or below this value uint256 maxLoanTerm; // the maximum term for new loans (0 means there's no max term) } } contract OrderStruct { struct Order { uint256 lockedAmount; // escrowed amount waiting for a counterparty uint256 interestRate; // interest rate defined by the creator of this order uint256 minLoanTerm; // minimum loan term allowed uint256 maxLoanTerm; // maximum loan term allowed uint256 createdTimestamp; // timestamp when this order was created uint256 expirationTimestamp; // timestamp when this order expires } } contract LenderInterestStruct { struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset uint256 owedPerDay; // interest owed per day for all loans of asset uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term) uint256 paidTotal; // total interest paid so far for asset uint256 updatedTimestamp; // last update } } contract LoanInterestStruct { struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan uint256 depositTotal; // total escrowed interest for loan uint256 updatedTimestamp; // last update } } contract Objects is LoanStruct, LoanParamsStruct, OrderStruct, LenderInterestStruct, LoanInterestStruct {} contract State is Constants, Objects, ReentrancyGuard, Ownable { using SafeMath for uint256; using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; address public priceFeeds; // handles asset reference price lookups address public swapsImpl; // handles asset swaps using dex liquidity mapping (bytes4 => address) public logicTargets; // implementations of protocol functions mapping (bytes32 => Loan) public loans; // loanId => Loan mapping (bytes32 => LoanParams) public loanParams; // loanParamsId => LoanParams mapping (address => mapping (bytes32 => Order)) public lenderOrders; // lender => orderParamsId => Order mapping (address => mapping (bytes32 => Order)) public borrowerOrders; // borrower => orderParamsId => Order mapping (bytes32 => mapping (address => bool)) public delegatedManagers; // loanId => delegated => approved // Interest mapping (address => mapping (address => LenderInterest)) public lenderInterest; // lender => loanToken => LenderInterest object mapping (bytes32 => LoanInterest) public loanInterest; // loanId => LoanInterest object // Internals EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; // implementations set EnumerableBytes32Set.Bytes32Set internal activeLoansSet; // active loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; // lender loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; // borrow loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; // user loan params set address public feesController; // address controlling fee withdrawals uint256 public lendingFeePercent = 10 ether; // 10% fee // fee taken from lender interest payments mapping (address => uint256) public lendingFeeTokensHeld; // total interest fees received and not withdrawn per asset mapping (address => uint256) public lendingFeeTokensPaid; // total interest fees withdraw per asset (lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid) uint256 public tradingFeePercent = 0.15 ether; // 0.15% fee // fee paid for each trade mapping (address => uint256) public tradingFeeTokensHeld; // total trading fees received and not withdrawn per asset mapping (address => uint256) public tradingFeeTokensPaid; // total trading fees withdraw per asset (lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid) uint256 public borrowingFeePercent = 0.09 ether; // 0.09% fee // origination fee paid for each loan mapping (address => uint256) public borrowingFeeTokensHeld; // total borrowing fees received and not withdrawn per asset mapping (address => uint256) public borrowingFeeTokensPaid; // total borrowing fees withdraw per asset (lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid) uint256 public protocolTokenHeld; // current protocol token deposit balance uint256 public protocolTokenPaid; // lifetime total payout of protocol token uint256 public affiliateFeePercent = 30 ether; // 30% fee share // fee share for affiliate program mapping (address => mapping (address => uint256)) public liquidationIncentivePercent; // percent discount on collateral for liquidators per loanToken and collateralToken mapping (address => address) public loanPoolToUnderlying; // loanPool => underlying mapping (address => address) public underlyingToLoanPool; // underlying => loanPool EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; // loan pools set mapping (address => bool) public supportedTokens; // supported tokens for swaps uint256 public maxDisagreement = 5 ether; // % disagreement between swap rate and reference rate uint256 public sourceBufferPercent = 5 ether; // used to estimate kyber swap source amount uint256 public maxSwapSize = 1500 ether; // maximum supported swap size in ETH function _setTarget( bytes4 sig, address target) internal { logicTargets[sig] = target; if (target != address(0)) { logicTargetsSet.addBytes32(bytes32(sig)); } else { logicTargetsSet.removeBytes32(bytes32(sig)); } } } interface IPriceFeeds { function queryRate( address sourceToken, address destToken) external view returns (uint256 rate, uint256 precision); function queryPrecision( address sourceToken, address destToken) external view returns (uint256 precision); function queryReturn( address sourceToken, address destToken, uint256 sourceAmount) external view returns (uint256 destAmount); function checkPriceDisagreement( address sourceToken, address destToken, uint256 sourceAmount, uint256 destAmount, uint256 maxSlippage) external view returns (uint256 sourceToDestSwapRate); function amountInEth( address Token, uint256 amount) external view returns (uint256 ethAmount); function getMaxDrawdown( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (uint256); function getCurrentMarginAndCollateralSize( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralInEthAmount); function getCurrentMargin( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralToLoanRate); function shouldLiquidate( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (bool); function getFastGasPrice( address payToken) external view returns (uint256); } contract ProtocolTokenUser is State { using SafeERC20 for IERC20; function _withdrawProtocolToken( address receiver, uint256 amount) internal returns (address, uint256) { uint256 withdrawAmount = amount; uint256 tokenBalance = protocolTokenHeld; if (withdrawAmount > tokenBalance) { withdrawAmount = tokenBalance; } if (withdrawAmount == 0) { return (vbzrxTokenAddress, 0); } protocolTokenHeld = tokenBalance .sub(withdrawAmount); IERC20(vbzrxTokenAddress).safeTransfer( receiver, withdrawAmount ); return (vbzrxTokenAddress, withdrawAmount); } } contract FeesEvents { event PayLendingFee( address indexed payer, address indexed token, uint256 amount ); event PayTradingFee( address indexed payer, address indexed token, bytes32 indexed loanId, uint256 amount ); event PayBorrowingFee( address indexed payer, address indexed token, bytes32 indexed loanId, uint256 amount ); event EarnReward( address indexed receiver, address indexed token, bytes32 indexed loanId, uint256 amount ); } contract FeesHelper is State, ProtocolTokenUser, FeesEvents { using SafeERC20 for IERC20; // calculate trading fee function _getTradingFee( uint256 feeTokenAmount) internal view returns (uint256) { return feeTokenAmount .mul(tradingFeePercent) .divCeil(WEI_PERCENT_PRECISION); } // calculate loan origination fee function _getBorrowingFee( uint256 feeTokenAmount) internal view returns (uint256) { return feeTokenAmount .mul(borrowingFeePercent) .divCeil(WEI_PERCENT_PRECISION); } // settle trading fee function _payTradingFee( address user, bytes32 loanId, address feeToken, uint256 tradingFee) internal { if (tradingFee != 0) { tradingFeeTokensHeld[feeToken] = tradingFeeTokensHeld[feeToken] .add(tradingFee); emit PayTradingFee( user, feeToken, loanId, tradingFee ); _payFeeReward( user, loanId, feeToken, tradingFee ); } } // settle loan origination fee function _payBorrowingFee( address user, bytes32 loanId, address feeToken, uint256 borrowingFee) internal { if (borrowingFee != 0) { borrowingFeeTokensHeld[feeToken] = borrowingFeeTokensHeld[feeToken] .add(borrowingFee); emit PayBorrowingFee( user, feeToken, loanId, borrowingFee ); _payFeeReward( user, loanId, feeToken, borrowingFee ); } } // settle lender (interest) fee function _payLendingFee( address user, address feeToken, uint256 lendingFee) internal { if (lendingFee != 0) { lendingFeeTokensHeld[feeToken] = lendingFeeTokensHeld[feeToken] .add(lendingFee); emit PayLendingFee( user, feeToken, lendingFee ); //// NOTE: Lenders do not receive a fee reward //// } } // settles and pays borrowers based on the fees generated by their interest payments function _settleFeeRewardForInterestExpense( LoanInterest storage loanInterestLocal, bytes32 loanId, address feeToken, address user, uint256 interestTime) internal { uint256 updatedTimestamp = loanInterestLocal.updatedTimestamp; uint256 interestExpenseFee; if (updatedTimestamp != 0) { // this represents the fee generated by a borrower's interest payment interestExpenseFee = interestTime .sub(updatedTimestamp) .mul(loanInterestLocal.owedPerDay) .mul(lendingFeePercent) .div(1 days * WEI_PERCENT_PRECISION); } loanInterestLocal.updatedTimestamp = interestTime; if (interestExpenseFee != 0) { _payFeeReward( user, loanId, feeToken, interestExpenseFee ); } } // pay protocolToken reward to user function _payFeeReward( address user, bytes32 loanId, address feeToken, uint256 feeAmount) internal { // The protocol is designed to allow positions and loans to be closed, if for whatever reason // the price lookup is failing, returning 0, or is otherwise paused. Therefore, we allow this // call to fail silently, rather than revert, to allow the transaction to continue without a // BZRX token reward. uint256 rewardAmount; address _priceFeeds = priceFeeds; (bool success, bytes memory data) = _priceFeeds.staticcall( abi.encodeWithSelector( IPriceFeeds(_priceFeeds).queryReturn.selector, feeToken, bzrxTokenAddress, // price rewards using BZRX price rather than vesting token price feeAmount / 2 // 50% of fee value ) ); assembly { if eq(success, 1) { rewardAmount := mload(add(data, 32)) } } if (rewardAmount != 0) { address rewardToken; (rewardToken, rewardAmount) = _withdrawProtocolToken( user, rewardAmount ); if (rewardAmount != 0) { protocolTokenPaid = protocolTokenPaid .add(rewardAmount); emit EarnReward( user, rewardToken, loanId, rewardAmount ); } } } } contract VaultController is Constants { using SafeERC20 for IERC20; event VaultDeposit( address indexed asset, address indexed from, uint256 amount ); event VaultWithdraw( address indexed asset, address indexed to, uint256 amount ); function vaultEtherDeposit( address from, uint256 value) internal { IWethERC20 _wethToken = wethToken; _wethToken.deposit.value(value)(); emit VaultDeposit( address(_wethToken), from, value ); } function vaultEtherWithdraw( address to, uint256 value) internal { if (value != 0) { IWethERC20 _wethToken = wethToken; uint256 balance = address(this).balance; if (value > balance) { _wethToken.withdraw(value - balance); } Address.sendValue(to, value); emit VaultWithdraw( address(_wethToken), to, value ); } } function vaultDeposit( address token, address from, uint256 value) internal { if (value != 0) { IERC20(token).safeTransferFrom( from, address(this), value ); emit VaultDeposit( token, from, value ); } } function vaultWithdraw( address token, address to, uint256 value) internal { if (value != 0) { IERC20(token).safeTransfer( to, value ); emit VaultWithdraw( token, to, value ); } } function vaultTransfer( address token, address from, address to, uint256 value) internal { if (value != 0) { if (from == address(this)) { IERC20(token).safeTransfer( to, value ); } else { IERC20(token).safeTransferFrom( from, to, value ); } } } function vaultApprove( address token, address to, uint256 value) internal { if (value != 0 && IERC20(token).allowance(address(this), to) != 0) { IERC20(token).safeApprove(to, 0); } IERC20(token).safeApprove(to, value); } } contract InterestUser is State, VaultController, FeesHelper { using SafeERC20 for IERC20; function _payInterest( address lender, address interestToken) internal { LenderInterest storage lenderInterestLocal = lenderInterest[lender][interestToken]; uint256 interestOwedNow = 0; if (lenderInterestLocal.owedPerDay != 0 && lenderInterestLocal.updatedTimestamp != 0) { interestOwedNow = block.timestamp .sub(lenderInterestLocal.updatedTimestamp) .mul(lenderInterestLocal.owedPerDay) .div(1 days); lenderInterestLocal.updatedTimestamp = block.timestamp; if (interestOwedNow > lenderInterestLocal.owedTotal) interestOwedNow = lenderInterestLocal.owedTotal; if (interestOwedNow != 0) { lenderInterestLocal.paidTotal = lenderInterestLocal.paidTotal .add(interestOwedNow); lenderInterestLocal.owedTotal = lenderInterestLocal.owedTotal .sub(interestOwedNow); _payInterestTransfer( lender, interestToken, interestOwedNow ); } } else { lenderInterestLocal.updatedTimestamp = block.timestamp; } } function _payInterestTransfer( address lender, address interestToken, uint256 interestOwedNow) internal { uint256 lendingFee = interestOwedNow .mul(lendingFeePercent) .divCeil(WEI_PERCENT_PRECISION); _payLendingFee( lender, interestToken, lendingFee ); // transfers the interest to the lender, less the interest fee vaultWithdraw( interestToken, lender, interestOwedNow .sub(lendingFee) ); } } contract LiquidationHelper is State { function _getLiquidationAmounts( uint256 principal, uint256 collateral, uint256 currentMargin, uint256 maintenanceMargin, uint256 collateralToLoanRate, uint256 incentivePercent) internal view returns (uint256 maxLiquidatable, uint256 maxSeizable) { if (currentMargin > maintenanceMargin || collateralToLoanRate == 0) { return (maxLiquidatable, maxSeizable); } else if (currentMargin <= incentivePercent) { return (principal, collateral); } uint256 desiredMargin = maintenanceMargin .add(5 ether); // 5 percentage points above maintenance // maxLiquidatable = ((1 + desiredMargin)*principal - collateralToLoanRate*collateral) / (desiredMargin - incentivePercent) maxLiquidatable = desiredMargin .add(WEI_PERCENT_PRECISION) .mul(principal) .div(WEI_PERCENT_PRECISION); maxLiquidatable = maxLiquidatable .sub( collateral .mul(collateralToLoanRate) .div(WEI_PRECISION) ); maxLiquidatable = maxLiquidatable .mul(WEI_PERCENT_PRECISION) .div( desiredMargin .sub(incentivePercent) ); if (maxLiquidatable > principal) { maxLiquidatable = principal; } // maxSeizable = maxLiquidatable * (1 + incentivePercent) / collateralToLoanRate maxSeizable = maxLiquidatable .mul( incentivePercent .add(WEI_PERCENT_PRECISION) ); maxSeizable = maxSeizable .div(collateralToLoanRate) .div(100); if (maxSeizable > collateral) { maxSeizable = collateral; } return (maxLiquidatable, maxSeizable); } } contract SwapsEvents { event LoanSwap( bytes32 indexed loanId, address indexed sourceToken, address indexed destToken, address borrower, uint256 sourceAmount, uint256 destAmount ); event ExternalSwap( address indexed user, address indexed sourceToken, address indexed destToken, uint256 sourceAmount, uint256 destAmount ); } interface ISwapsImpl { function dexSwap( address sourceTokenAddress, address destTokenAddress, address receiverAddress, address returnToSenderAddress, uint256 minSourceTokenAmount, uint256 maxSourceTokenAmount, uint256 requiredDestTokenAmount) external returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); function dexExpectedRate( address sourceTokenAddress, address destTokenAddress, uint256 sourceTokenAmount) external view returns (uint256); } contract SwapsUser is State, SwapsEvents, FeesHelper { function _loanSwap( bytes32 loanId, address sourceToken, address destToken, address user, uint256 minSourceTokenAmount, uint256 maxSourceTokenAmount, uint256 requiredDestTokenAmount, bool bypassFee, bytes memory loanDataBytes) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 sourceToDestSwapRate) { (destTokenAmountReceived, sourceTokenAmountUsed) = _swapsCall( [ sourceToken, destToken, address(this), // receiver address(this), // returnToSender user ], [ minSourceTokenAmount, maxSourceTokenAmount, requiredDestTokenAmount ], loanId, bypassFee, loanDataBytes ); // will revert if swap size too large _checkSwapSize(sourceToken, sourceTokenAmountUsed); // will revert if disagreement found sourceToDestSwapRate = IPriceFeeds(priceFeeds).checkPriceDisagreement( sourceToken, destToken, sourceTokenAmountUsed, destTokenAmountReceived, maxDisagreement ); emit LoanSwap( loanId, sourceToken, destToken, user, sourceTokenAmountUsed, destTokenAmountReceived ); } function _swapsCall( address[5] memory addrs, uint256[3] memory vals, bytes32 loanId, bool miscBool, // bypassFee bytes memory loanDataBytes) internal returns (uint256, uint256) { //addrs[0]: sourceToken //addrs[1]: destToken //addrs[2]: receiver //addrs[3]: returnToSender //addrs[4]: user //vals[0]: minSourceTokenAmount //vals[1]: maxSourceTokenAmount //vals[2]: requiredDestTokenAmount require(vals[0] != 0, "sourceAmount == 0"); uint256 destTokenAmountReceived; uint256 sourceTokenAmountUsed; uint256 tradingFee; if (!miscBool) { // bypassFee if (vals[2] == 0) { // condition: vals[0] will always be used as sourceAmount tradingFee = _getTradingFee(vals[0]); if (tradingFee != 0) { _payTradingFee( addrs[4], // user loanId, addrs[0], // sourceToken tradingFee ); vals[0] = vals[0] .sub(tradingFee); } } else { // condition: unknown sourceAmount will be used tradingFee = _getTradingFee(vals[2]); if (tradingFee != 0) { vals[2] = vals[2] .add(tradingFee); } } } if (vals[1] == 0) { vals[1] = vals[0]; } else { require(vals[0] <= vals[1], "min greater than max"); } require(loanDataBytes.length == 0, "invalid state"); (destTokenAmountReceived, sourceTokenAmountUsed) = _swapsCall_internal( addrs, vals ); if (vals[2] == 0) { // there's no minimum destTokenAmount, but all of vals[0] (minSourceTokenAmount) must be spent, and amount spent can't exceed vals[0] require(sourceTokenAmountUsed == vals[0], "swap too large to fill"); if (tradingFee != 0) { sourceTokenAmountUsed = sourceTokenAmountUsed + tradingFee; // will never overflow } } else { // there's a minimum destTokenAmount required, but sourceTokenAmountUsed won't be greater than vals[1] (maxSourceTokenAmount) require(sourceTokenAmountUsed <= vals[1], "swap fill too large"); require(destTokenAmountReceived >= vals[2], "insufficient swap liquidity"); if (tradingFee != 0) { _payTradingFee( addrs[4], // user loanId, // loanId, addrs[1], // destToken tradingFee ); destTokenAmountReceived = destTokenAmountReceived - tradingFee; // will never overflow } } return (destTokenAmountReceived, sourceTokenAmountUsed); } function _swapsCall_internal( address[5] memory addrs, uint256[3] memory vals) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed) { bytes memory data = abi.encodeWithSelector( ISwapsImpl(swapsImpl).dexSwap.selector, addrs[0], // sourceToken addrs[1], // destToken addrs[2], // receiverAddress addrs[3], // returnToSenderAddress vals[0], // minSourceTokenAmount vals[1], // maxSourceTokenAmount vals[2] // requiredDestTokenAmount ); bool success; (success, data) = swapsImpl.delegatecall(data); require(success, "swap failed"); (destTokenAmountReceived, sourceTokenAmountUsed) = abi.decode(data, (uint256, uint256)); } function _swapsExpectedReturn( address sourceToken, address destToken, uint256 sourceTokenAmount) internal view returns (uint256) { uint256 tradingFee = _getTradingFee(sourceTokenAmount); if (tradingFee != 0) { sourceTokenAmount = sourceTokenAmount .sub(tradingFee); } uint256 sourceToDestRate = ISwapsImpl(swapsImpl).dexExpectedRate( sourceToken, destToken, sourceTokenAmount ); uint256 sourceToDestPrecision = IPriceFeeds(priceFeeds).queryPrecision( sourceToken, destToken ); return sourceTokenAmount .mul(sourceToDestRate) .div(sourceToDestPrecision); } function _checkSwapSize( address tokenAddress, uint256 amount) internal view { uint256 _maxSwapSize = maxSwapSize; if (_maxSwapSize != 0) { uint256 amountInEth; if (tokenAddress == address(wethToken)) { amountInEth = amount; } else { amountInEth = IPriceFeeds(priceFeeds).amountInEth(tokenAddress, amount); } require(amountInEth <= _maxSwapSize, "swap too large"); } } } interface ILoanPool { function tokenPrice() external view returns (uint256 price); function borrowInterestRate() external view returns (uint256); function totalAssetSupply() external view returns (uint256); } contract ITokenHolderLike { function balanceOf(address _who) public view returns (uint256); function freeUpTo(uint256 value) public returns (uint256); function freeFromUpTo(address from, uint256 value) public returns (uint256); } contract GasTokenUser { ITokenHolderLike constant public gasToken = ITokenHolderLike(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); ITokenHolderLike constant public tokenHolder = ITokenHolderLike(0x55Eb3DD3f738cfdda986B8Eff3fa784477552C61); modifier usesGasToken(address holder) { if (holder == address(0)) { holder = address(tokenHolder); } if (gasToken.balanceOf(holder) != 0) { uint256 gasCalcValue = gasleft(); _; gasCalcValue = (_gasUsed(gasCalcValue) + 14154) / 41947; if (holder == address(tokenHolder)) { tokenHolder.freeUpTo( gasCalcValue ); } else { tokenHolder.freeFromUpTo( holder, gasCalcValue ); } } else { _; } } function _gasUsed( uint256 startingGas) internal view returns (uint256) { return 21000 + startingGas - gasleft() + 16 * msg.data.length; } } contract LoanClosingsEvents { event CloseWithDeposit( address indexed user, address indexed lender, bytes32 indexed loanId, address closer, address loanToken, address collateralToken, uint256 repayAmount, uint256 collateralWithdrawAmount, uint256 collateralToLoanRate, uint256 currentMargin ); event CloseWithSwap( address indexed user, address indexed lender, bytes32 indexed loanId, address collateralToken, address loanToken, address closer, uint256 positionCloseSize, uint256 loanCloseAmount, uint256 exitPrice, // one unit of collateralToken, denominated in loanToken uint256 currentLeverage ); event Liquidate( address indexed user, address indexed liquidator, bytes32 indexed loanId, address lender, address loanToken, address collateralToken, uint256 repayAmount, uint256 collateralWithdrawAmount, uint256 collateralToLoanRate, uint256 currentMargin ); event Rollover( address indexed user, address indexed caller, bytes32 indexed loanId, address lender, address loanToken, address collateralToken, uint256 collateralAmountUsed, uint256 interestAmountAdded, uint256 loanEndTimestamp, uint256 gasRebate ); } contract LoanClosingsBase is State, LoanClosingsEvents, VaultController, InterestUser, GasTokenUser, SwapsUser, LiquidationHelper { enum CloseTypes { Deposit, Swap, Liquidation } function _liquidate( bytes32 loanId, address receiver, uint256 closeAmount) internal returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ) { Loan memory loanLocal = loans[loanId]; require(loanLocal.active, "loan is closed"); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; (uint256 currentMargin, uint256 collateralToLoanRate) = IPriceFeeds(priceFeeds).getCurrentMargin( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral ); require( currentMargin <= loanParamsLocal.maintenanceMargin, "healthy position" ); loanCloseAmount = closeAmount; (uint256 maxLiquidatable, uint256 maxSeizable) = _getLiquidationAmounts( loanLocal.principal, loanLocal.collateral, currentMargin, loanParamsLocal.maintenanceMargin, collateralToLoanRate, liquidationIncentivePercent[loanParamsLocal.loanToken][loanParamsLocal.collateralToken] ); if (loanCloseAmount < maxLiquidatable) { seizedAmount = maxSeizable .mul(loanCloseAmount) .div(maxLiquidatable); } else { if (loanCloseAmount > maxLiquidatable) { // adjust down the close amount to the max loanCloseAmount = maxLiquidatable; } seizedAmount = maxSeizable; } require(loanCloseAmount != 0, "nothing to liquidate"); // liquidator deposits the principal being closed _returnPrincipalWithDeposit( loanParamsLocal.loanToken, address(this), loanCloseAmount ); // a portion of the principal is repaid to the lender out of interest refunded uint256 loanCloseAmountLessInterest = _settleInterestToPrincipal( loanLocal, loanParamsLocal, loanCloseAmount, loanLocal.borrower ); if (loanCloseAmount > loanCloseAmountLessInterest) { // full interest refund goes to the borrower _withdrawAsset( loanParamsLocal.loanToken, loanLocal.borrower, loanCloseAmount - loanCloseAmountLessInterest ); } if (loanCloseAmountLessInterest != 0) { // The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than // use the _withdrawAsset helper function vaultWithdraw( loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest ); } seizedToken = loanParamsLocal.collateralToken; if (seizedAmount != 0) { loanLocal.collateral = loanLocal.collateral .sub(seizedAmount); _withdrawAsset( seizedToken, receiver, seizedAmount ); } _emitClosingEvents( loanParamsLocal, loanLocal, loanCloseAmount, seizedAmount, collateralToLoanRate, 0, // collateralToLoanSwapRate currentMargin, CloseTypes.Liquidation ); _closeLoan( loanLocal, loanCloseAmount ); } function _rollover( bytes32 loanId, uint256 startingGas, bytes memory loanDataBytes) internal { Loan memory loanLocal = loans[loanId]; require(loanLocal.active, "loan is closed"); require( block.timestamp > loanLocal.endTimestamp.sub(1 hours), "healthy position" ); require( loanPoolToUnderlying[loanLocal.lender] != address(0), "invalid lender" ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; // pay outstanding interest to lender _payInterest( loanLocal.lender, loanParamsLocal.loanToken ); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken]; _settleFeeRewardForInterestExpense( loanInterestLocal, loanLocal.id, loanParamsLocal.loanToken, loanLocal.borrower, block.timestamp ); // Handle back interest: calculates interest owned since the loan endtime passed but the loan remained open uint256 backInterestTime; uint256 backInterestOwed; if (block.timestamp > loanLocal.endTimestamp) { backInterestTime = block.timestamp .sub(loanLocal.endTimestamp); backInterestOwed = backInterestTime .mul(loanInterestLocal.owedPerDay); backInterestOwed = backInterestOwed .div(24 hours); } uint256 maxDuration = loanParamsLocal.maxLoanTerm; if (maxDuration != 0) { // fixed-term loan, so need to query iToken for latest variable rate uint256 owedPerDay = loanLocal.principal .mul(ILoanPool(loanLocal.lender).borrowInterestRate()) .div(DAYS_IN_A_YEAR * WEI_PERCENT_PRECISION); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .add(owedPerDay); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .sub(loanInterestLocal.owedPerDay); loanInterestLocal.owedPerDay = owedPerDay; } else { // loanInterestLocal.owedPerDay doesn't change maxDuration = ONE_MONTH; } if (backInterestTime >= maxDuration) { maxDuration = backInterestTime .add(24 hours); // adds an extra 24 hours } // update loan end time loanLocal.endTimestamp = loanLocal.endTimestamp .add(maxDuration); uint256 interestAmountRequired = loanLocal.endTimestamp .sub(block.timestamp); interestAmountRequired = interestAmountRequired .mul(loanInterestLocal.owedPerDay); interestAmountRequired = interestAmountRequired .div(24 hours); loanInterestLocal.depositTotal = loanInterestLocal.depositTotal .add(interestAmountRequired); lenderInterestLocal.owedTotal = lenderInterestLocal.owedTotal .add(interestAmountRequired); // add backInterestOwed interestAmountRequired = interestAmountRequired .add(backInterestOwed); // collect interest (,uint256 sourceTokenAmountUsed,) = _doCollateralSwap( loanLocal, loanParamsLocal, loanLocal.collateral, interestAmountRequired, true, // returnTokenIsCollateral loanDataBytes ); loanLocal.collateral = loanLocal.collateral .sub(sourceTokenAmountUsed); if (backInterestOwed != 0) { // pay out backInterestOwed _payInterestTransfer( loanLocal.lender, loanParamsLocal.loanToken, backInterestOwed ); } uint256 gasRebate = _getRebate( loanLocal, loanParamsLocal, startingGas ); if (gasRebate != 0) { // pay out gas rebate to caller // the preceeding logic should ensure gasRebate <= collateral, but just in case, will use SafeMath here loanLocal.collateral = loanLocal.collateral .sub(gasRebate, "gasRebate too high"); _withdrawAsset( loanParamsLocal.collateralToken, msg.sender, gasRebate ); } _rolloverEvent( loanLocal, loanParamsLocal, sourceTokenAmountUsed, interestAmountRequired, gasRebate ); loans[loanId] = loanLocal; } function _closeWithDeposit( bytes32 loanId, address receiver, uint256 depositAmount) // denominated in loanToken internal returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { require(depositAmount != 0, "depositAmount == 0"); Loan memory loanLocal = loans[loanId]; _checkAuthorized( loanLocal.id, loanLocal.active, loanLocal.borrower ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; // can't close more than the full principal loanCloseAmount = depositAmount > loanLocal.principal ? loanLocal.principal : depositAmount; uint256 loanCloseAmountLessInterest = _settleInterestToPrincipal( loanLocal, loanParamsLocal, loanCloseAmount, receiver ); if (loanCloseAmountLessInterest != 0) { _returnPrincipalWithDeposit( loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest ); } if (loanCloseAmount == loanLocal.principal) { withdrawAmount = loanLocal.collateral; } else { withdrawAmount = loanLocal.collateral .mul(loanCloseAmount) .div(loanLocal.principal); } withdrawToken = loanParamsLocal.collateralToken; if (withdrawAmount != 0) { loanLocal.collateral = loanLocal.collateral - withdrawAmount; // overflow not possible _withdrawAsset( withdrawToken, receiver, withdrawAmount ); } _finalizeClose( loanLocal, loanParamsLocal, loanCloseAmount, withdrawAmount, // collateralCloseAmount 0, // collateralToLoanSwapRate CloseTypes.Deposit ); } function _closeWithSwap( bytes32 loanId, address receiver, uint256 swapAmount, bool returnTokenIsCollateral, bytes memory loanDataBytes) internal returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { require(swapAmount != 0, "swapAmount == 0"); Loan memory loanLocal = loans[loanId]; _checkAuthorized( loanLocal.id, loanLocal.active, loanLocal.borrower ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; if (swapAmount > loanLocal.collateral) { swapAmount = loanLocal.collateral; } loanCloseAmount = loanLocal.principal; if (swapAmount != loanLocal.collateral) { loanCloseAmount = loanCloseAmount .mul(swapAmount) .div(loanLocal.collateral); } require(loanCloseAmount != 0, "loanCloseAmount == 0"); uint256 loanCloseAmountLessInterest = _settleInterestToPrincipal( loanLocal, loanParamsLocal, loanCloseAmount, receiver ); uint256 usedCollateral; uint256 collateralToLoanSwapRate; (usedCollateral, withdrawAmount, collateralToLoanSwapRate) = _coverPrincipalWithSwap( loanLocal, loanParamsLocal, swapAmount, loanCloseAmountLessInterest, returnTokenIsCollateral, loanDataBytes ); if (loanCloseAmountLessInterest != 0) { // Repays principal to lender // The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than // use the _withdrawAsset helper function vaultWithdraw( loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest ); } if (usedCollateral != 0) { loanLocal.collateral = loanLocal.collateral .sub(usedCollateral); } withdrawToken = returnTokenIsCollateral ? loanParamsLocal.collateralToken : loanParamsLocal.loanToken; if (withdrawAmount != 0) { _withdrawAsset( withdrawToken, receiver, withdrawAmount ); } _finalizeClose( loanLocal, loanParamsLocal, loanCloseAmount, usedCollateral, collateralToLoanSwapRate, CloseTypes.Swap ); } function _checkAuthorized( bytes32 _id, bool _active, address _borrower) internal view { require(_active, "loan is closed"); require( msg.sender == _borrower || delegatedManagers[_id][msg.sender], "unauthorized" ); } function _settleInterestToPrincipal( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 loanCloseAmount, address receiver) internal returns (uint256) { uint256 loanCloseAmountLessInterest = loanCloseAmount; uint256 interestRefundToBorrower = _settleInterest( loanParamsLocal, loanLocal, loanCloseAmountLessInterest ); uint256 interestAppliedToPrincipal; if (loanCloseAmountLessInterest >= interestRefundToBorrower) { // apply all of borrower interest refund torwards principal interestAppliedToPrincipal = interestRefundToBorrower; // principal needed is reduced by this amount loanCloseAmountLessInterest -= interestRefundToBorrower; // no interest refund remaining interestRefundToBorrower = 0; } else { // principal fully covered by excess interest interestAppliedToPrincipal = loanCloseAmountLessInterest; // amount refunded is reduced by this amount interestRefundToBorrower -= loanCloseAmountLessInterest; // principal fully covered by excess interest loanCloseAmountLessInterest = 0; // refund overage _withdrawAsset( loanParamsLocal.loanToken, receiver, interestRefundToBorrower ); } if (interestAppliedToPrincipal != 0) { // The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than // use the _withdrawAsset helper function vaultWithdraw( loanParamsLocal.loanToken, loanLocal.lender, interestAppliedToPrincipal ); } return loanCloseAmountLessInterest; } // The receiver always gets back an ERC20 (even WETH) function _returnPrincipalWithDeposit( address loanToken, address receiver, uint256 principalNeeded) internal { if (principalNeeded != 0) { if (msg.value == 0) { vaultTransfer( loanToken, msg.sender, receiver, principalNeeded ); } else { require(loanToken == address(wethToken), "wrong asset sent"); require(msg.value >= principalNeeded, "not enough ether"); wethToken.deposit.value(principalNeeded)(); if (receiver != address(this)) { vaultTransfer( loanToken, address(this), receiver, principalNeeded ); } if (msg.value > principalNeeded) { // refund overage Address.sendValue( msg.sender, msg.value - principalNeeded ); } } } else { require(msg.value == 0, "wrong asset sent"); } } function _coverPrincipalWithSwap( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 swapAmount, uint256 principalNeeded, bool returnTokenIsCollateral, bytes memory loanDataBytes) internal returns (uint256 usedCollateral, uint256 withdrawAmount, uint256 collateralToLoanSwapRate) { uint256 destTokenAmountReceived; uint256 sourceTokenAmountUsed; (destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _doCollateralSwap( loanLocal, loanParamsLocal, swapAmount, principalNeeded, returnTokenIsCollateral, loanDataBytes ); if (returnTokenIsCollateral) { if (destTokenAmountReceived > principalNeeded) { // better fill than expected, so send excess to borrower _withdrawAsset( loanParamsLocal.loanToken, loanLocal.borrower, destTokenAmountReceived - principalNeeded ); } withdrawAmount = swapAmount > sourceTokenAmountUsed ? swapAmount - sourceTokenAmountUsed : 0; } else { require(sourceTokenAmountUsed == swapAmount, "swap error"); withdrawAmount = destTokenAmountReceived - principalNeeded; } usedCollateral = sourceTokenAmountUsed > swapAmount ? sourceTokenAmountUsed : swapAmount; } function _doCollateralSwap( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 swapAmount, uint256 principalNeeded, bool returnTokenIsCollateral, bytes memory loanDataBytes) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 collateralToLoanSwapRate) { (destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _loanSwap( loanLocal.id, loanParamsLocal.collateralToken, loanParamsLocal.loanToken, loanLocal.borrower, swapAmount, // minSourceTokenAmount loanLocal.collateral, // maxSourceTokenAmount returnTokenIsCollateral ? principalNeeded : // requiredDestTokenAmount 0, false, // bypassFee loanDataBytes ); require(destTokenAmountReceived >= principalNeeded, "insufficient dest amount"); require(sourceTokenAmountUsed <= loanLocal.collateral, "excessive source amount"); } // withdraws asset to receiver function _withdrawAsset( address assetToken, address receiver, uint256 assetAmount) internal { if (assetAmount != 0) { if (assetToken == address(wethToken)) { vaultEtherWithdraw( receiver, assetAmount ); } else { vaultWithdraw( assetToken, receiver, assetAmount ); } } } function _finalizeClose( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 loanCloseAmount, uint256 collateralCloseAmount, uint256 collateralToLoanSwapRate, CloseTypes closeType) internal { _closeLoan( loanLocal, loanCloseAmount ); address _priceFeeds = priceFeeds; uint256 currentMargin; uint256 collateralToLoanRate; // this is still called even with full loan close to return collateralToLoanRate (bool success, bytes memory data) = _priceFeeds.staticcall( abi.encodeWithSelector( IPriceFeeds(_priceFeeds).getCurrentMargin.selector, loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral ) ); assembly { if eq(success, 1) { currentMargin := mload(add(data, 32)) collateralToLoanRate := mload(add(data, 64)) } } //// Note: We can safely skip the margin check if closing via closeWithDeposit or if closing the loan in full by any method //// require( closeType == CloseTypes.Deposit || loanLocal.principal == 0 || // loan fully closed currentMargin > loanParamsLocal.maintenanceMargin, "unhealthy position" ); _emitClosingEvents( loanParamsLocal, loanLocal, loanCloseAmount, collateralCloseAmount, collateralToLoanRate, collateralToLoanSwapRate, currentMargin, closeType ); } function _closeLoan( Loan memory loanLocal, uint256 loanCloseAmount) internal returns (uint256) { require(loanCloseAmount != 0, "nothing to close"); if (loanCloseAmount == loanLocal.principal) { loanLocal.principal = 0; loanLocal.active = false; loanLocal.endTimestamp = block.timestamp; loanLocal.pendingTradesId = 0; activeLoansSet.removeBytes32(loanLocal.id); lenderLoanSets[loanLocal.lender].removeBytes32(loanLocal.id); borrowerLoanSets[loanLocal.borrower].removeBytes32(loanLocal.id); } else { loanLocal.principal = loanLocal.principal .sub(loanCloseAmount); } loans[loanLocal.id] = loanLocal; } function _settleInterest( LoanParams memory loanParamsLocal, Loan memory loanLocal, uint256 closePrincipal) internal returns (uint256) { // pay outstanding interest to lender _payInterest( loanLocal.lender, loanParamsLocal.loanToken ); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken]; uint256 interestTime = block.timestamp; if (interestTime > loanLocal.endTimestamp) { interestTime = loanLocal.endTimestamp; } _settleFeeRewardForInterestExpense( loanInterestLocal, loanLocal.id, loanParamsLocal.loanToken, loanLocal.borrower, interestTime ); uint256 owedPerDayRefund; if (closePrincipal < loanLocal.principal) { owedPerDayRefund = loanInterestLocal.owedPerDay .mul(closePrincipal) .div(loanLocal.principal); } else { owedPerDayRefund = loanInterestLocal.owedPerDay; } // update stored owedPerDay loanInterestLocal.owedPerDay = loanInterestLocal.owedPerDay .sub(owedPerDayRefund); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .sub(owedPerDayRefund); // update borrower interest uint256 interestRefundToBorrower = loanLocal.endTimestamp .sub(interestTime); interestRefundToBorrower = interestRefundToBorrower .mul(owedPerDayRefund); interestRefundToBorrower = interestRefundToBorrower .div(24 hours); if (closePrincipal < loanLocal.principal) { loanInterestLocal.depositTotal = loanInterestLocal.depositTotal .sub(interestRefundToBorrower); } else { loanInterestLocal.depositTotal = 0; } // update remaining lender interest values lenderInterestLocal.principalTotal = lenderInterestLocal.principalTotal .sub(closePrincipal); uint256 owedTotal = lenderInterestLocal.owedTotal; lenderInterestLocal.owedTotal = owedTotal > interestRefundToBorrower ? owedTotal - interestRefundToBorrower : 0; return interestRefundToBorrower; } function _getRebate( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 startingGas) internal returns (uint256 gasRebate) { // the amount of collateral drop needed to reach the maintenanceMargin level of the loan uint256 maxDrawdown = IPriceFeeds(priceFeeds).getMaxDrawdown( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral, loanParamsLocal.maintenanceMargin ); require(maxDrawdown != 0, "unhealthy position"); // gets the gas rebate denominated in collateralToken gasRebate = SafeMath.mul( IPriceFeeds(priceFeeds).getFastGasPrice(loanParamsLocal.collateralToken) * 2, _gasUsed(startingGas) ); // ensures the gas rebate will not drop the current margin below the maintenance level gasRebate = gasRebate .min256(maxDrawdown); } function _rolloverEvent( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 sourceTokenAmountUsed, uint256 interestAmountRequired, uint256 gasRebate) internal { emit Rollover( loanLocal.borrower, // user (borrower) msg.sender, // caller loanLocal.id, // loanId loanLocal.lender, // lender loanParamsLocal.loanToken, // loanToken loanParamsLocal.collateralToken, // collateralToken sourceTokenAmountUsed, // collateralAmountUsed interestAmountRequired, // interestAmountAdded loanLocal.endTimestamp, // loanEndTimestamp gasRebate // gasRebate ); } function _emitClosingEvents( LoanParams memory loanParamsLocal, Loan memory loanLocal, uint256 loanCloseAmount, uint256 collateralCloseAmount, uint256 collateralToLoanRate, uint256 collateralToLoanSwapRate, uint256 currentMargin, CloseTypes closeType) internal { if (closeType == CloseTypes.Deposit) { emit CloseWithDeposit( loanLocal.borrower, // user (borrower) loanLocal.lender, // lender loanLocal.id, // loanId msg.sender, // closer loanParamsLocal.loanToken, // loanToken loanParamsLocal.collateralToken, // collateralToken loanCloseAmount, // loanCloseAmount collateralCloseAmount, // collateralCloseAmount collateralToLoanRate, // collateralToLoanRate currentMargin // currentMargin ); } else if (closeType == CloseTypes.Swap) { // exitPrice = 1 / collateralToLoanSwapRate if (collateralToLoanSwapRate != 0) { collateralToLoanSwapRate = SafeMath.div(WEI_PRECISION * WEI_PRECISION, collateralToLoanSwapRate); } // currentLeverage = 100 / currentMargin if (currentMargin != 0) { currentMargin = SafeMath.div(10**38, currentMargin); } emit CloseWithSwap( loanLocal.borrower, // user (trader) loanLocal.lender, // lender loanLocal.id, // loanId loanParamsLocal.collateralToken, // collateralToken loanParamsLocal.loanToken, // loanToken msg.sender, // closer collateralCloseAmount, // positionCloseSize loanCloseAmount, // loanCloseAmount collateralToLoanSwapRate, // exitPrice (1 / collateralToLoanSwapRate) currentMargin // currentLeverage ); } else { // closeType == CloseTypes.Liquidation emit Liquidate( loanLocal.borrower, // user (borrower) msg.sender, // liquidator loanLocal.id, // loanId loanLocal.lender, // lender loanParamsLocal.loanToken, // loanToken loanParamsLocal.collateralToken, // collateralToken loanCloseAmount, // loanCloseAmount collateralCloseAmount, // collateralCloseAmount collateralToLoanRate, // collateralToLoanRate currentMargin // currentMargin ); } } } contract LoanClosingsWithGasToken is LoanClosingsBase { function initialize( address target) external onlyOwner { _setTarget(this.liquidateWithGasToken.selector, target); _setTarget(this.rolloverWithGasToken.selector, target); _setTarget(this.closeWithDepositWithGasToken.selector, target); _setTarget(this.closeWithSwapWithGasToken.selector, target); } function liquidateWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 closeAmount) // denominated in loanToken external payable usesGasToken(gasTokenUser) nonReentrant returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ) { return _liquidate( loanId, receiver, closeAmount ); } function rolloverWithGasToken( bytes32 loanId, address gasTokenUser, bytes calldata /*loanDataBytes*/) // for future use external usesGasToken(gasTokenUser) nonReentrant { uint256 startingGas = 21000 + gasleft() + 16 * msg.data.length; // restrict to EOAs to prevent griefing attacks, during interest rate recalculation require(msg.sender == tx.origin, "only EOAs can call"); return _rollover( loanId, startingGas, "" // loanDataBytes ); } function closeWithDepositWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 depositAmount) // denominated in loanToken public payable usesGasToken(gasTokenUser) nonReentrant returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { return _closeWithDeposit( loanId, receiver, depositAmount ); } function closeWithSwapWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 swapAmount, // denominated in collateralToken bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken bytes memory /*loanDataBytes*/) // for future use public usesGasToken(gasTokenUser) nonReentrant returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { return _closeWithSwap( loanId, receiver, swapAmount, returnTokenIsCollateral, "" // loanDataBytes ); } }
calculate loan origination fee
function _getBorrowingFee( uint256 feeTokenAmount) internal view returns (uint256) { return feeTokenAmount .mul(borrowingFeePercent) .divCeil(WEI_PERCENT_PRECISION); }
382,221
./partial_match/1/0x81Ae47602889DB4151416A72F94f3074A5519f2C/sources/DevToken.sol
solhint-disable-next-line high-level-success
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]); require(allow[_from] == true); 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; }
2,715,045
./full_match/1/0x1863B0c9F63e686A3E7928a21b527C7b3CEd5895/sources/bsb2.sol
should not be needed, but...
function recoverEth() external onlyOwner timeIsUp { payable(owner).transfer(address(this).balance); }
3,173,716
pragma solidity ^0.5.10; /** * @title A Supply Chain prototype contract implementation. * @author Brian Ludlam * @notice All Supply Chain relevant data is stored on-chain, with all data erroneous * to the system stored on IPFS. All information in the system, whether on-chain or on * IPFS, is impossible to change without a contract event logging the change, and all * versions of all data can be permanently referenced on IPFS. * A Supply Chain is defined in this system as a Directed Acyclic Graph of supply steps * that follow the production of something back to it's conception. A supply step always * references a single item in the system, and may extend one or more previous supply steps, * or precedents. A new step may only be added as a first step, or the last step of an existing * supply chain. Approval must be granted to create a new supply step, which extends a supply * step not owned directly. */ contract SupplyChain { /** * Struct IPFile - IPFS file signature data structure. */ struct IPFile { bytes32 digest;//file digest = file hash uint8 meta;//file meta = file hashing algorithm type uint8 size;//file size } /** * Struct SupplyNode - Supply Node data structure. */ struct SupplyNode { address owner;//owner / creator of Supply Node IPFile nodeFile;//IPFS File for Supply Node uint256 steps;//number of Supply Steps setup on this Supply Node mapping(address => bool) operator;//Supply Node Operators } /** * Struct SupplyStep - Supply Step data structure. */ struct SupplyStep { uint256 node;//Origin Supply Node uint256 item;//Referenced Supply Item IPFile stepFile;//IPFS File for Supply Step uint256[] precedents;//preceding Supply Steps to this Supply Step uint256 approvals;//number of Supply Node access approvals for this Supply Step mapping(uint256 => bool) approval;//mapping of Supply Node access approvals } //developer account with primary contract control address payable private _developer; //Supply Node Index uint256 private _nodeIndex; //Supply Node index mapping to SupplyNode data structure mapping(uint256 => SupplyNode) private _supplyNode; //Supply Item Index uint256 _itemIndex; //Supply Item index mapping to IPFS file data structure mapping(uint256 => IPFile) _itemFile; //Supply Item index mapping to origin Supply Node mapping(uint256 => uint256) _itemNode; //Supply Item index mapping to index of it's last Supply Step (zero if none.) mapping(uint256 => uint256) _itemStep; //Supply Step Index uint256 private _stepIndex; //Supply Step mapping from index to SupplyStep data structure mapping(uint256 => SupplyStep) private _supplyStep; /** * Event SupplyNodeAdded - Log each time a new Supply Node is added. * @return nodeId = Supply Node ID * @return owner = Supply Node owner * @return timestamp = Timestamp when Supply Node was added. */ event SupplyNodeAdded( uint256 indexed nodeId, address indexed owner, uint256 timestamp ); /** * Event SupplyNodeRemoved - Log each time a new Supply Node is removed. * @return nodeId = Supply Node ID * @return owner = Supply Node owner * @return timestamp = Timestamp when Supply Node was removed. */ event SupplyNodeRemoved( uint256 indexed nodeId, address indexed owner, uint256 timestamp ); /** * Event NodeOpApproval - Log each change in new Supply Node operator approval status. * @return nodeId = Supply Node ID * @return operator = Supply Node operator * @return approved = Supply Node operator approval status * @return timestamp = Timestamp of Supply Node operator status change. */ event NodeOpApproval( uint256 indexed nodeId, address indexed operator, bool approved, uint256 timestamp ); /** * Event SupplyItemAdded - Log each time a new Supply Item is added. * @return itemId = Supply Item ID that was added. * @return nodeId = Supply Node ID that Supply Item was added to. * @return timestamp = Timestamp when Supply Item was added. */ event SupplyItemAdded( uint256 indexed itemId, uint256 indexed nodeId, uint256 timestamp ); /** * Event SupplyItemRemoved - Log each time a new Supply Item is removed. * @return itemId = Supply Item ID that was removed. * @return nodeId = Supply Node ID that Supply Item was removed from. * @return timestamp = Timestamp when Supply Item was removed. */ event SupplyItemRemoved( uint256 indexed itemId, uint256 indexed nodeId, uint256 timestamp ); /** * Event SupplyStepAdded - Log each time a new Supply Step is added. * @return stepId = Supply Step ID that was added. * @return nodeId = Supply Node ID that Supply Step was added to. * @return itemId = Supply Item ID that Supply Step references. * @return timestamp = Timestamp when Supply Step was added. */ event SupplyStepAdded( uint256 indexed stepId, uint256 indexed nodeId, uint256 indexed itemId, uint256 timestamp ); /** * Event SupplyStepRemoved - Log each time a new Supply Step is removed. * @return stepId = Supply Step ID that was added. * @return nodeId = Supply Node ID that Supply Step was added to. * @return itemId = Supply Item ID that Supply Step references. * @return timestamp = Timestamp when Supply Step was removed. */ event SupplyStepRemoved( uint256 indexed stepId, uint256 indexed nodeId, uint256 indexed itemId, uint256 timestamp ); /** * Event SupplyStepRequest - Log Supply Step access requested by Supply Node. * @return stepId = Supply Step ID being requested for access. * @return owner = Owner of Supply Node requesting access. * @return nodeId = Supply Node ID requesting access. * @return timestamp = Timestamp when Supply Step access was requested. */ event SupplyStepRequest( uint256 indexed stepId, address indexed owner, uint256 indexed nodeId, uint256 timestamp ); /** * Event SupplyNodeApproval - Log Supply Step access approval status change for Supply Node. * @return stepId = Supply Step ID approving access to Supply Node. * @return owner = Owner of Supply Node receiving approval for access. * @return nodeId = Supply Node ID receiving approval for access. * @return approved = Supply Node approval status * @return timestamp = Timestamp when Supply Node access approval status changed. */ event SupplyNodeApproval( uint256 indexed stepId, address indexed owner, uint256 indexed nodeId, bool approved, uint256 timestamp ); //Contract constructor sets developer account control and initializes indexes. constructor() public { _developer = msg.sender; _nodeIndex = _stepIndex = _itemIndex = 0; } /** * Transaction addSupplyNode - Add Supply Node with IPFS file data. * @param fileDigest = IPFS file multihash - hash data part * @param fileMeta = IPFS file multihash - hash algorythm part * @param fileSize = IPFS file multihash - file size part * @return uint256 new Supply Node index value * @notice IPFS File multihash parts must be relatively valid. */ function addSupplyNode ( bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) public returns(uint256) { //Check require (fileDigest != 0x0, "Invalid file digest."); require (fileMeta != 0, "Invalid file meta."); require (fileSize != 0, "Invalid file size."); //Effect IPFile memory nodeFile = IPFile(fileDigest, fileMeta, fileSize); SupplyNode memory newNode = SupplyNode(msg.sender, nodeFile, 0); _supplyNode[++_nodeIndex] = newNode; //Reflect emit SupplyNodeAdded (_nodeIndex, msg.sender, now); return _nodeIndex; } /** * Transaction removeSupplyNode - Remove Supply Node by ID. * @param nodeId = Valid ID of a Supply Node * @return boolean transaction success * @notice must be owner of Supply Node, Supply Node must exist and be inactive. */ function removeSupplyNode (uint256 nodeId) public returns(bool) { //Check require (nodeId != 0, "Node doesn't exist."); SupplyNode storage node = _supplyNode[nodeId]; require (node.owner == msg.sender, "Must be node owner."); require (node.steps == 0, "Cannot remove node with active steps."); //Effect delete _supplyNode[nodeId].nodeFile; delete _supplyNode[nodeId]; //Reflect emit SupplyNodeRemoved (nodeId, msg.sender, now); return true; } /** * Transaction approveNodeOp - Set approval for Supply Node operators by account address. * @param nodeId = Valid ID of a Supply Node * @return boolean transaction success * @notice must be owner of Supply Node. */ function approveNodeOp ( uint256 nodeId, address operator, bool approved ) public returns(bool) { //Check require (_supplyNode[nodeId].owner == msg.sender, "Node owner only."); require (operator != address(0), "Invalid operator address."); //Effect if (_supplyNode[nodeId].operator[operator] != approved) { _supplyNode[nodeId].operator[operator] = approved; } //Reflect emit NodeOpApproval (nodeId, operator, approved, now); return true; } /** * Transaction addSupplyItem - Add Supply Item to Supply Node as IPFS file. * @param nodeId = Origin Supply Node * @param fileDigest = IPFS file multihash - hash data part * @param fileMeta = IPFS file multihash - hash algorythm part * @param fileSize = IPFS file multihash - file size part * @return uint256 new Supply Item index value * @notice Must be Supply Node owner or operator, IPFS File multihash parts * must be relatively valid. */ function addSupplyItem ( uint256 nodeId, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) public returns(uint256) { //Check require (_supplyNode[nodeId].nodeFile.size != 0, "Invalid supply node."); require (_supplyNode[nodeId].owner == msg.sender || _supplyNode[nodeId].operator[msg.sender], "Invalid owner / operator."); require (fileDigest != 0x0, "Invalid file digest."); require (fileMeta != 0, "Invalid file meta."); require (fileSize != 0, "Invalid file size."); //Effect IPFile memory itemFile = IPFile(fileDigest, fileMeta, fileSize); _itemFile[++_itemIndex] = itemFile; _itemNode[_itemIndex] = nodeId; _itemStep[_itemIndex] = 0;//no steps //Reflect emit SupplyItemAdded (_itemIndex, nodeId, now); return _itemIndex; } /** * Transaction removeSupplyItem - Remove Supply Item by ID. * @param itemId = Valid Supply Item ID * @return boolean transaction success * @notice Must be Supply Node owner or operator, Item may not have active * Supply Steps. */ function removeSupplyItem (uint256 itemId) public returns(bool) { //Check require (_itemNode[itemId] == 0 || _itemFile[itemId].size != 0, "Invalid item."); require (_itemStep[itemId] == 0, "Cannot remove item with active steps."); uint256 nodeId = _itemNode[itemId]; require (_supplyNode[nodeId].nodeFile.size != 0, "Invalid supply item root node."); require (_supplyNode[nodeId].owner == msg.sender || _supplyNode[nodeId].operator[msg.sender], "Invalid owner / operator."); //Effect delete _itemFile[itemId]; delete _itemStep[itemId]; delete _itemNode[itemId]; //Reflect emit SupplyItemRemoved (itemId, nodeId, now); return true; } /** * Transaction addSupplyStep - Add Supply Step for Supply Item at Supply Node. * @param nodeId = Supply Node to end Supply Step to. * @param itemId = Supply Item this Supply Step references. * @param precedents = Array of Supply Step IDs, which this Supply Step extends. * @param fileDigest = IPFS file multihash - hash data part * @param fileMeta = IPFS file multihash - hash algorythm part * @param fileSize = IPFS file multihash - file size part * @return uint256 new supply step index value * @notice Must be valid Supply Step (see validateSupplyStep(), IPFS File * multihash parts must be relatively valid. */ function addSupplyStep ( uint256 nodeId, uint256 itemId, uint256[] memory precedents, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) public returns(uint256) { //Check require (fileDigest != 0x0, "Invalid file digest."); require (fileMeta != 0, "Invalid file meta."); require (fileSize != 0, "Invalid file size."); require (validateSupplyStep(nodeId, itemId, precedents), "Invalid Supply Step."); //Effect IPFile memory stepFile = IPFile(fileDigest, fileMeta, fileSize); SupplyStep memory newStep = SupplyStep(nodeId, itemId, stepFile, precedents, 0); _supplyStep[++_stepIndex] = newStep; _itemStep[itemId] = _stepIndex; _supplyNode[nodeId].steps += 1; //Reflect emit SupplyStepAdded (_stepIndex, nodeId, itemId, now); return _stepIndex; } /** * Transaction removeSupplyStep - Remove Supply Step by ID. * @param stepId = Valid Supply Step ID * @return boolean transaction success * @notice Must be Supply Node owner or operator, must be Supply Items's * last Supply Step, must not have any active Supply Node approvals. */ function removeSupplyStep (uint256 stepId) public returns(bool) { //Check SupplyStep storage step = _supplyStep[stepId]; uint256 nodeId = step.node; uint256 itemId = step.item; require (nodeId != 0, "Invalid step."); require (_supplyNode[nodeId].owner == msg.sender || _supplyNode[nodeId].operator[msg.sender], "Invalid owner / operator."); require (_itemStep[itemId] == stepId, "Only item's last step removable."); require (step.approvals == 0, "Cannot remove step with active approvals."); //Effect if (step.precedents.length > 0) { //reset itemStep to previous itemStep if exists in precedents. uint8 index = 0; while (index < step.precedents.length) { if (_supplyStep[step.precedents[index]].item == itemId) { _itemStep[itemId] = step.precedents[index]; break;//can only be one } else index++; } if (index == step.precedents.length) _itemStep[itemId] = 0; }else _itemStep[itemId] = 0; if (_supplyNode[nodeId].steps > 0) _supplyNode[nodeId].steps -= 1; delete _supplyStep[stepId].stepFile; delete _supplyStep[stepId]; //Reflect emit SupplyStepRemoved (stepId, nodeId, itemId, now); return true; } /** * Transaction requestSupplyStep - Request for Supply Node access to existing Supply Step. * @param stepId = Valid ID of a Supply Step beign requested. * @param nodeId = Valid ID of a Supply Node doing the requesting. * @return boolean transaction success * @notice Must be owner of Supply Node doing the request. Event-only effect, * address of Supply Step's Supply Node owner included for event trigger. */ function requestSupplyStep ( uint256 stepId, uint256 nodeId ) public returns(bool) { //Check require (_supplyStep[stepId].node != 0, "Invalid step."); require (_supplyNode[nodeId].owner == msg.sender, "Node owner only."); //Reflect emit SupplyStepRequest ( stepId, _supplyNode[_supplyStep[stepId].node].owner, nodeId, now ); return true; } /** * Transaction approveSupplyNode - Set approval for Supply Node access to existing * Supply Step. * @param stepId = Valid ID of a Supply Step approving. * @param nodeId = Valid ID of a Supply Node being approved. * @param approved = State of approval. * @return boolean transaction success * @notice Must be owner of Supply Node owning Supply Step doing the approval. * . */ function approveSupplyNode ( uint256 stepId, uint256 nodeId, bool approved ) public returns(bool) { //Check uint256 stepNode = _supplyStep[stepId].node; require (stepNode != 0, "Invalid step."); require (_supplyNode[stepNode].owner == msg.sender, "Step Node owner only."); //Effect if (_supplyStep[stepId].approval[nodeId] != approved) { _supplyStep[stepId].approval[nodeId] = approved; if (approved) _supplyStep[stepId].approvals += 1; else if (_supplyStep[stepId].approvals > 0) _supplyStep[stepId].approvals -= 1; } //Reflect emit SupplyNodeApproval (stepId, msg.sender, nodeId, approved, now); return true; } /** * View supplyNode - Get Supply Node data by ID. * @param nodeId = Valid ID of a Supply Node. * @return owner = Supply Node owner address. * @return fileDigest = Node File - IPFS file multihash - hash data part * @return fileMeta = Node File - IPFS file multihash - hash algorythm part * @return fileSize = Node File - IPFS file multihash - file size part * */ function supplyNode(uint256 nodeId) external view returns (address owner, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) { owner = _supplyNode[nodeId].owner; fileDigest = _supplyNode[nodeId].nodeFile.digest; fileMeta = _supplyNode[nodeId].nodeFile.meta; fileSize = _supplyNode[nodeId].nodeFile.size; } /** * View supplyItem - Get Supply Item data by ID. * @param itemId = Valid ID of a Supply Item. * @return nodeId =ID of Supply Item's origin Supply Node. * @return lastStep = Supply Item's last Supply Step ID. (zero if none) * @return fileDigest = Item File - IPFS file multihash - hash data part * @return fileMeta = Item File - IPFS file multihash - hash algorythm part * @return fileSize = Item File - IPFS file multihash - file size part * */ function supplyItem(uint256 itemId) external view returns (uint256 nodeId, uint256 lastStep, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) { nodeId = _itemNode[itemId]; lastStep = _itemStep[itemId]; fileDigest = _itemFile[itemId].digest; fileMeta = _itemFile[itemId].meta; fileSize = _itemFile[itemId].size; } /** * View supplyStep - Get Supply Step data by ID. * @param stepId = Valid ID of a Supply Step. * @return nodeId = ID of Supply Step's Supply Item's origin Supply Node. * @return itemId = Supply Item referenced by Supply Step. * @return precedents = Array of Supply Step IDs, which this Supply Step extends. * @return fileDigest = Step File - IPFS file multihash - hash data part * @return fileMeta = Step File - IPFS file multihash - hash algorythm part * @return fileSize = Step File - IPFS file multihash - file size part * */ function supplyStep(uint256 stepId) external view returns ( uint256 nodeId, uint256 itemId, uint256[] memory precedents, bytes32 fileDigest, uint8 fileMeta, uint8 fileSize ) { nodeId = _supplyStep[stepId].node; itemId = _supplyStep[stepId].item; precedents = _supplyStep[stepId].precedents; fileDigest = _supplyStep[stepId].stepFile.digest; fileMeta = _supplyStep[stepId].stepFile.meta; fileSize = _supplyStep[stepId].stepFile.size; } /** * View validateSupplyStep - Validates a potential Supply Step entry to see if it's valid. * @param nodeId = ID of Supply Supply Node to create Supply Step on. * @param itemId = Supply Item referenced by Supply Step. * @param precedents = Array of Supply Step IDs, which this Supply Step extends. * @return boolean = valid or not * @notice this check always occurs before adSupplyStep transaction, however can be called * independently first to check vaidiity, to avoid transaction fail. * Checks: Node is valid, sender is owner or operator of Supply Node adding the step, * item referenced is valid, all included precedents are themselves last steps of there * respective items, the nodeId adding them has approval to extend those steps, and adding * a step that is not the first step of a given item, must include that item's last step * as a precedent, given approval to do so. * */ function validateSupplyStep ( uint256 nodeId, uint256 itemId, uint256[] memory precedents ) public view returns(bool) { if (_supplyNode[nodeId].nodeFile.size == 0) return false; if (_supplyNode[nodeId].owner != msg.sender && !_supplyNode[nodeId].operator[msg.sender]) return false; if (_itemFile[itemId].size == 0) return false; uint8 itemRepeatStep = 0; if (precedents.length > 0) { uint8 index = 0; while (index < precedents.length) { if (_supplyStep[precedents[index]].item == 0 || !(_supplyStep[precedents[index]].node == nodeId || _supplyStep[precedents[index]].approval[nodeId]) || _itemStep[_supplyStep[precedents[index]].item] != precedents[index]) { return false; } if (_supplyStep[precedents[index]].item == itemId) itemRepeatStep++; index++; } } if (itemRepeatStep > 1 || (itemRepeatStep == 0 && _itemStep[itemId] != 0)) return false; return true; } /** * View isNodeOp - Check address as Node operator. * @param nodeId = Valid ID of a Supply Node. * @param operator = account address. * @return boolean = is node operator * @notice Supply Node owner only */ function isNodeOp(uint256 nodeId, address operator) external view returns (bool) { require (_supplyNode[nodeId].owner == msg.sender); return _supplyNode[nodeId].operator[operator]; } /** * View itemLastStep - Get last Supply Step of given Supply Item ID * @param itemId = Valid ID of a Supply Item. * @return stepId = Supply Step ID */ function itemLastStep(uint256 itemId) public view returns (uint256 stepId) { stepId = _itemStep[itemId]; } /** * View stepPrecedents - Get precedents of given Supply Step ID * @param stepId = Valid ID of a Supply Step. * @return precedents = Array of Supply Step IDs */ function stepPrecedents(uint256 stepId) public view returns (uint256[] memory precedents) { precedents = _supplyStep[stepId].precedents; } /** * View stepNodeApproved - Get Supply Step approval status for Supply Node * @param stepId = Valid ID of a Supply Step. * @param nodeId = Valid ID of a Supply Node. * @return approved = Boolean approval status */ function stepNodeApproved(uint256 stepId, uint256 nodeId) external view returns (bool approved) { approved = (_supplyStep[stepId].node == nodeId || _supplyStep[stepId].approval[nodeId]); } //developer only destroy method function destroy() external { require (_developer == msg.sender); selfdestruct(_developer); } //Return to sender, any abstract transfers function () external payable { msg.sender.transfer(msg.value); } }
developer only destroy method
function destroy() external { require (_developer == msg.sender); selfdestruct(_developer); }
15,838,715
./full_match/5/0x7871802cc13357fae0f467eBBE435E862A7352aB/sources/contracts/PGFINDER.sol
require( campaign.deadline < block.timestamp, "The deadline should be a date in the future" );
function AddPg( address _owner, string memory _PgName, string memory _PgAddress, string memory _PgServices, string memory _image ) public returns (uint256) { Pg storage pg = PgFind[numberOfPg]; pg.owner = _owner; pg.PgName = _PgName; pg.PgAddress = _PgAddress; pg.PgServices = _PgServices; pg.image = _image; numberOfPg++; return numberOfPg - 1; }
1,936,297